json.hpp 693 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406
  1. /*
  2. __ _____ _____ _____
  3. __| | __| | | | JSON for Modern C++
  4. | | |__ | | | | | | version 3.5.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 5
  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> // 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. } // namespace nlohmann
  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__) < 40800
  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. #undef JSON_INTERNAL_CATCH
  152. #define JSON_INTERNAL_CATCH JSON_CATCH_USER
  153. #endif
  154. #if defined(JSON_INTERNAL_CATCH_USER)
  155. #undef JSON_INTERNAL_CATCH
  156. #define JSON_INTERNAL_CATCH JSON_INTERNAL_CATCH_USER
  157. #endif
  158. // manual branch prediction
  159. #if defined(__clang__) || defined(__GNUC__) || defined(__GNUG__)
  160. #define JSON_LIKELY(x) __builtin_expect(!!(x), 1)
  161. #define JSON_UNLIKELY(x) __builtin_expect(!!(x), 0)
  162. #else
  163. #define JSON_LIKELY(x) x
  164. #define JSON_UNLIKELY(x) x
  165. #endif
  166. // C++ language standard detection
  167. #if (defined(__cplusplus) && __cplusplus >= 201703L) || (defined(_HAS_CXX17) && _HAS_CXX17 == 1) // fix for issue #464
  168. #define JSON_HAS_CPP_17
  169. #define JSON_HAS_CPP_14
  170. #elif (defined(__cplusplus) && __cplusplus >= 201402L) || (defined(_HAS_CXX14) && _HAS_CXX14 == 1)
  171. #define JSON_HAS_CPP_14
  172. #endif
  173. /*!
  174. @brief macro to briefly define a mapping between an enum and JSON
  175. @def NLOHMANN_JSON_SERIALIZE_ENUM
  176. @since version 3.4.0
  177. */
  178. #define NLOHMANN_JSON_SERIALIZE_ENUM(ENUM_TYPE, ...) \
  179. template<typename BasicJsonType> \
  180. inline void to_json(BasicJsonType& j, const ENUM_TYPE& e) \
  181. { \
  182. static_assert(std::is_enum<ENUM_TYPE>::value, #ENUM_TYPE " must be an enum!"); \
  183. static const std::pair<ENUM_TYPE, BasicJsonType> m[] = __VA_ARGS__; \
  184. auto it = std::find_if(std::begin(m), std::end(m), \
  185. [e](const std::pair<ENUM_TYPE, BasicJsonType>& ej_pair) -> bool \
  186. { \
  187. return ej_pair.first == e; \
  188. }); \
  189. j = ((it != std::end(m)) ? it : std::begin(m))->second; \
  190. } \
  191. template<typename BasicJsonType> \
  192. inline void from_json(const BasicJsonType& j, ENUM_TYPE& e) \
  193. { \
  194. static_assert(std::is_enum<ENUM_TYPE>::value, #ENUM_TYPE " must be an enum!"); \
  195. static const std::pair<ENUM_TYPE, BasicJsonType> m[] = __VA_ARGS__; \
  196. auto it = std::find_if(std::begin(m), std::end(m), \
  197. [j](const std::pair<ENUM_TYPE, BasicJsonType>& ej_pair) -> bool \
  198. { \
  199. return ej_pair.second == j; \
  200. }); \
  201. e = ((it != std::end(m)) ? it : std::begin(m))->first; \
  202. }
  203. // Ugly macros to avoid uglier copy-paste when specializing basic_json. They
  204. // may be removed in the future once the class is split.
  205. #define NLOHMANN_BASIC_JSON_TPL_DECLARATION \
  206. template<template<typename, typename, typename...> class ObjectType, \
  207. template<typename, typename...> class ArrayType, \
  208. class StringType, class BooleanType, class NumberIntegerType, \
  209. class NumberUnsignedType, class NumberFloatType, \
  210. template<typename> class AllocatorType, \
  211. template<typename, typename = void> class JSONSerializer>
  212. #define NLOHMANN_BASIC_JSON_TPL \
  213. basic_json<ObjectType, ArrayType, StringType, BooleanType, \
  214. NumberIntegerType, NumberUnsignedType, NumberFloatType, \
  215. AllocatorType, JSONSerializer>
  216. // #include <nlohmann/detail/meta/cpp_future.hpp>
  217. #include <ciso646> // not
  218. #include <cstddef> // size_t
  219. #include <type_traits> // conditional, enable_if, false_type, integral_constant, is_constructible, is_integral, is_same, remove_cv, remove_reference, true_type
  220. namespace nlohmann
  221. {
  222. namespace detail
  223. {
  224. // alias templates to reduce boilerplate
  225. template<bool B, typename T = void>
  226. using enable_if_t = typename std::enable_if<B, T>::type;
  227. template<typename T>
  228. using uncvref_t = typename std::remove_cv<typename std::remove_reference<T>::type>::type;
  229. // implementation of C++14 index_sequence and affiliates
  230. // source: https://stackoverflow.com/a/32223343
  231. template<std::size_t... Ints>
  232. struct index_sequence
  233. {
  234. using type = index_sequence;
  235. using value_type = std::size_t;
  236. static constexpr std::size_t size() noexcept
  237. {
  238. return sizeof...(Ints);
  239. }
  240. };
  241. template<class Sequence1, class Sequence2>
  242. struct merge_and_renumber;
  243. template<std::size_t... I1, std::size_t... I2>
  244. struct merge_and_renumber<index_sequence<I1...>, index_sequence<I2...>>
  245. : index_sequence < I1..., (sizeof...(I1) + I2)... > {};
  246. template<std::size_t N>
  247. struct make_index_sequence
  248. : merge_and_renumber < typename make_index_sequence < N / 2 >::type,
  249. typename make_index_sequence < N - N / 2 >::type > {};
  250. template<> struct make_index_sequence<0> : index_sequence<> {};
  251. template<> struct make_index_sequence<1> : index_sequence<0> {};
  252. template<typename... Ts>
  253. using index_sequence_for = make_index_sequence<sizeof...(Ts)>;
  254. // dispatch utility (taken from ranges-v3)
  255. template<unsigned N> struct priority_tag : priority_tag < N - 1 > {};
  256. template<> struct priority_tag<0> {};
  257. // taken from ranges-v3
  258. template<typename T>
  259. struct static_const
  260. {
  261. static constexpr T value{};
  262. };
  263. template<typename T>
  264. constexpr T static_const<T>::value;
  265. } // namespace detail
  266. } // namespace nlohmann
  267. // #include <nlohmann/detail/meta/type_traits.hpp>
  268. #include <ciso646> // not
  269. #include <limits> // numeric_limits
  270. #include <type_traits> // false_type, is_constructible, is_integral, is_same, true_type
  271. #include <utility> // declval
  272. // #include <nlohmann/json_fwd.hpp>
  273. // #include <nlohmann/detail/iterators/iterator_traits.hpp>
  274. #include <iterator> // random_access_iterator_tag
  275. // #include <nlohmann/detail/meta/void_t.hpp>
  276. namespace nlohmann
  277. {
  278. namespace detail
  279. {
  280. template <typename ...Ts> struct make_void
  281. {
  282. using type = void;
  283. };
  284. template <typename ...Ts> using void_t = typename make_void<Ts...>::type;
  285. } // namespace detail
  286. } // namespace nlohmann
  287. // #include <nlohmann/detail/meta/cpp_future.hpp>
  288. namespace nlohmann
  289. {
  290. namespace detail
  291. {
  292. template <typename It, typename = void>
  293. struct iterator_types {};
  294. template <typename It>
  295. struct iterator_types <
  296. It,
  297. void_t<typename It::difference_type, typename It::value_type, typename It::pointer,
  298. typename It::reference, typename It::iterator_category >>
  299. {
  300. using difference_type = typename It::difference_type;
  301. using value_type = typename It::value_type;
  302. using pointer = typename It::pointer;
  303. using reference = typename It::reference;
  304. using iterator_category = typename It::iterator_category;
  305. };
  306. // This is required as some compilers implement std::iterator_traits in a way that
  307. // doesn't work with SFINAE. See https://github.com/nlohmann/json/issues/1341.
  308. template <typename T, typename = void>
  309. struct iterator_traits
  310. {
  311. };
  312. template <typename T>
  313. struct iterator_traits < T, enable_if_t < !std::is_pointer<T>::value >>
  314. : iterator_types<T>
  315. {
  316. };
  317. template <typename T>
  318. struct iterator_traits<T*, enable_if_t<std::is_object<T>::value>>
  319. {
  320. using iterator_category = std::random_access_iterator_tag;
  321. using value_type = T;
  322. using difference_type = ptrdiff_t;
  323. using pointer = T*;
  324. using reference = T&;
  325. };
  326. }
  327. }
  328. // #include <nlohmann/detail/meta/cpp_future.hpp>
  329. // #include <nlohmann/detail/meta/detected.hpp>
  330. #include <type_traits>
  331. // #include <nlohmann/detail/meta/void_t.hpp>
  332. // http://en.cppreference.com/w/cpp/experimental/is_detected
  333. namespace nlohmann
  334. {
  335. namespace detail
  336. {
  337. struct nonesuch
  338. {
  339. nonesuch() = delete;
  340. ~nonesuch() = delete;
  341. nonesuch(nonesuch const&) = delete;
  342. void operator=(nonesuch const&) = delete;
  343. };
  344. template <class Default,
  345. class AlwaysVoid,
  346. template <class...> class Op,
  347. class... Args>
  348. struct detector
  349. {
  350. using value_t = std::false_type;
  351. using type = Default;
  352. };
  353. template <class Default, template <class...> class Op, class... Args>
  354. struct detector<Default, void_t<Op<Args...>>, Op, Args...>
  355. {
  356. using value_t = std::true_type;
  357. using type = Op<Args...>;
  358. };
  359. template <template <class...> class Op, class... Args>
  360. using is_detected = typename detector<nonesuch, void, Op, Args...>::value_t;
  361. template <template <class...> class Op, class... Args>
  362. using detected_t = typename detector<nonesuch, void, Op, Args...>::type;
  363. template <class Default, template <class...> class Op, class... Args>
  364. using detected_or = detector<Default, void, Op, Args...>;
  365. template <class Default, template <class...> class Op, class... Args>
  366. using detected_or_t = typename detected_or<Default, Op, Args...>::type;
  367. template <class Expected, template <class...> class Op, class... Args>
  368. using is_detected_exact = std::is_same<Expected, detected_t<Op, Args...>>;
  369. template <class To, template <class...> class Op, class... Args>
  370. using is_detected_convertible =
  371. std::is_convertible<detected_t<Op, Args...>, To>;
  372. } // namespace detail
  373. } // namespace nlohmann
  374. // #include <nlohmann/detail/macro_scope.hpp>
  375. namespace nlohmann
  376. {
  377. /*!
  378. @brief detail namespace with internal helper functions
  379. This namespace collects functions that should not be exposed,
  380. implementations of some @ref basic_json methods, and meta-programming helpers.
  381. @since version 2.1.0
  382. */
  383. namespace detail
  384. {
  385. /////////////
  386. // helpers //
  387. /////////////
  388. // Note to maintainers:
  389. //
  390. // Every trait in this file expects a non CV-qualified type.
  391. // The only exceptions are in the 'aliases for detected' section
  392. // (i.e. those of the form: decltype(T::member_function(std::declval<T>())))
  393. //
  394. // In this case, T has to be properly CV-qualified to constraint the function arguments
  395. // (e.g. to_json(BasicJsonType&, const T&))
  396. template<typename> struct is_basic_json : std::false_type {};
  397. NLOHMANN_BASIC_JSON_TPL_DECLARATION
  398. struct is_basic_json<NLOHMANN_BASIC_JSON_TPL> : std::true_type {};
  399. //////////////////////////
  400. // aliases for detected //
  401. //////////////////////////
  402. template <typename T>
  403. using mapped_type_t = typename T::mapped_type;
  404. template <typename T>
  405. using key_type_t = typename T::key_type;
  406. template <typename T>
  407. using value_type_t = typename T::value_type;
  408. template <typename T>
  409. using difference_type_t = typename T::difference_type;
  410. template <typename T>
  411. using pointer_t = typename T::pointer;
  412. template <typename T>
  413. using reference_t = typename T::reference;
  414. template <typename T>
  415. using iterator_category_t = typename T::iterator_category;
  416. template <typename T>
  417. using iterator_t = typename T::iterator;
  418. template <typename T, typename... Args>
  419. using to_json_function = decltype(T::to_json(std::declval<Args>()...));
  420. template <typename T, typename... Args>
  421. using from_json_function = decltype(T::from_json(std::declval<Args>()...));
  422. template <typename T, typename U>
  423. using get_template_function = decltype(std::declval<T>().template get<U>());
  424. // trait checking if JSONSerializer<T>::from_json(json const&, udt&) exists
  425. template <typename BasicJsonType, typename T, typename = void>
  426. struct has_from_json : std::false_type {};
  427. template <typename BasicJsonType, typename T>
  428. struct has_from_json<BasicJsonType, T,
  429. enable_if_t<not is_basic_json<T>::value>>
  430. {
  431. using serializer = typename BasicJsonType::template json_serializer<T, void>;
  432. static constexpr bool value =
  433. is_detected_exact<void, from_json_function, serializer,
  434. const BasicJsonType&, T&>::value;
  435. };
  436. // This trait checks if JSONSerializer<T>::from_json(json const&) exists
  437. // this overload is used for non-default-constructible user-defined-types
  438. template <typename BasicJsonType, typename T, typename = void>
  439. struct has_non_default_from_json : std::false_type {};
  440. template<typename BasicJsonType, typename T>
  441. struct has_non_default_from_json<BasicJsonType, T, enable_if_t<not is_basic_json<T>::value>>
  442. {
  443. using serializer = typename BasicJsonType::template json_serializer<T, void>;
  444. static constexpr bool value =
  445. is_detected_exact<T, from_json_function, serializer,
  446. const BasicJsonType&>::value;
  447. };
  448. // This trait checks if BasicJsonType::json_serializer<T>::to_json exists
  449. // Do not evaluate the trait when T is a basic_json type, to avoid template instantiation infinite recursion.
  450. template <typename BasicJsonType, typename T, typename = void>
  451. struct has_to_json : std::false_type {};
  452. template <typename BasicJsonType, typename T>
  453. struct has_to_json<BasicJsonType, T, enable_if_t<not is_basic_json<T>::value>>
  454. {
  455. using serializer = typename BasicJsonType::template json_serializer<T, void>;
  456. static constexpr bool value =
  457. is_detected_exact<void, to_json_function, serializer, BasicJsonType&,
  458. T>::value;
  459. };
  460. ///////////////////
  461. // is_ functions //
  462. ///////////////////
  463. template <typename T, typename = void>
  464. struct is_iterator_traits : std::false_type {};
  465. template <typename T>
  466. struct is_iterator_traits<iterator_traits<T>>
  467. {
  468. private:
  469. using traits = iterator_traits<T>;
  470. public:
  471. static constexpr auto value =
  472. is_detected<value_type_t, traits>::value &&
  473. is_detected<difference_type_t, traits>::value &&
  474. is_detected<pointer_t, traits>::value &&
  475. is_detected<iterator_category_t, traits>::value &&
  476. is_detected<reference_t, traits>::value;
  477. };
  478. // source: https://stackoverflow.com/a/37193089/4116453
  479. template <typename T, typename = void>
  480. struct is_complete_type : std::false_type {};
  481. template <typename T>
  482. struct is_complete_type<T, decltype(void(sizeof(T)))> : std::true_type {};
  483. template <typename BasicJsonType, typename CompatibleObjectType,
  484. typename = void>
  485. struct is_compatible_object_type_impl : std::false_type {};
  486. template <typename BasicJsonType, typename CompatibleObjectType>
  487. struct is_compatible_object_type_impl <
  488. BasicJsonType, CompatibleObjectType,
  489. enable_if_t<is_detected<mapped_type_t, CompatibleObjectType>::value and
  490. is_detected<key_type_t, CompatibleObjectType>::value >>
  491. {
  492. using object_t = typename BasicJsonType::object_t;
  493. // macOS's is_constructible does not play well with nonesuch...
  494. static constexpr bool value =
  495. std::is_constructible<typename object_t::key_type,
  496. typename CompatibleObjectType::key_type>::value and
  497. std::is_constructible<typename object_t::mapped_type,
  498. typename CompatibleObjectType::mapped_type>::value;
  499. };
  500. template <typename BasicJsonType, typename CompatibleObjectType>
  501. struct is_compatible_object_type
  502. : is_compatible_object_type_impl<BasicJsonType, CompatibleObjectType> {};
  503. template <typename BasicJsonType, typename ConstructibleObjectType,
  504. typename = void>
  505. struct is_constructible_object_type_impl : std::false_type {};
  506. template <typename BasicJsonType, typename ConstructibleObjectType>
  507. struct is_constructible_object_type_impl <
  508. BasicJsonType, ConstructibleObjectType,
  509. enable_if_t<is_detected<mapped_type_t, ConstructibleObjectType>::value and
  510. is_detected<key_type_t, ConstructibleObjectType>::value >>
  511. {
  512. using object_t = typename BasicJsonType::object_t;
  513. static constexpr bool value =
  514. (std::is_constructible<typename ConstructibleObjectType::key_type, typename object_t::key_type>::value and
  515. std::is_same<typename object_t::mapped_type, typename ConstructibleObjectType::mapped_type>::value) or
  516. (has_from_json<BasicJsonType, typename ConstructibleObjectType::mapped_type>::value or
  517. has_non_default_from_json<BasicJsonType, typename ConstructibleObjectType::mapped_type >::value);
  518. };
  519. template <typename BasicJsonType, typename ConstructibleObjectType>
  520. struct is_constructible_object_type
  521. : is_constructible_object_type_impl<BasicJsonType,
  522. ConstructibleObjectType> {};
  523. template <typename BasicJsonType, typename CompatibleStringType,
  524. typename = void>
  525. struct is_compatible_string_type_impl : std::false_type {};
  526. template <typename BasicJsonType, typename CompatibleStringType>
  527. struct is_compatible_string_type_impl <
  528. BasicJsonType, CompatibleStringType,
  529. enable_if_t<is_detected_exact<typename BasicJsonType::string_t::value_type,
  530. value_type_t, CompatibleStringType>::value >>
  531. {
  532. static constexpr auto value =
  533. std::is_constructible<typename BasicJsonType::string_t, CompatibleStringType>::value;
  534. };
  535. template <typename BasicJsonType, typename ConstructibleStringType>
  536. struct is_compatible_string_type
  537. : is_compatible_string_type_impl<BasicJsonType, ConstructibleStringType> {};
  538. template <typename BasicJsonType, typename ConstructibleStringType,
  539. typename = void>
  540. struct is_constructible_string_type_impl : std::false_type {};
  541. template <typename BasicJsonType, typename ConstructibleStringType>
  542. struct is_constructible_string_type_impl <
  543. BasicJsonType, ConstructibleStringType,
  544. enable_if_t<is_detected_exact<typename BasicJsonType::string_t::value_type,
  545. value_type_t, ConstructibleStringType>::value >>
  546. {
  547. static constexpr auto value =
  548. std::is_constructible<ConstructibleStringType,
  549. typename BasicJsonType::string_t>::value;
  550. };
  551. template <typename BasicJsonType, typename ConstructibleStringType>
  552. struct is_constructible_string_type
  553. : is_constructible_string_type_impl<BasicJsonType, ConstructibleStringType> {};
  554. template <typename BasicJsonType, typename CompatibleArrayType, typename = void>
  555. struct is_compatible_array_type_impl : std::false_type {};
  556. template <typename BasicJsonType, typename CompatibleArrayType>
  557. struct is_compatible_array_type_impl <
  558. BasicJsonType, CompatibleArrayType,
  559. enable_if_t<is_detected<value_type_t, CompatibleArrayType>::value and
  560. is_detected<iterator_t, CompatibleArrayType>::value and
  561. // This is needed because json_reverse_iterator has a ::iterator type...
  562. // Therefore it is detected as a CompatibleArrayType.
  563. // The real fix would be to have an Iterable concept.
  564. not is_iterator_traits<
  565. iterator_traits<CompatibleArrayType>>::value >>
  566. {
  567. static constexpr bool value =
  568. std::is_constructible<BasicJsonType,
  569. typename CompatibleArrayType::value_type>::value;
  570. };
  571. template <typename BasicJsonType, typename CompatibleArrayType>
  572. struct is_compatible_array_type
  573. : is_compatible_array_type_impl<BasicJsonType, CompatibleArrayType> {};
  574. template <typename BasicJsonType, typename ConstructibleArrayType, typename = void>
  575. struct is_constructible_array_type_impl : std::false_type {};
  576. template <typename BasicJsonType, typename ConstructibleArrayType>
  577. struct is_constructible_array_type_impl <
  578. BasicJsonType, ConstructibleArrayType,
  579. enable_if_t<std::is_same<ConstructibleArrayType,
  580. typename BasicJsonType::value_type>::value >>
  581. : std::true_type {};
  582. template <typename BasicJsonType, typename ConstructibleArrayType>
  583. struct is_constructible_array_type_impl <
  584. BasicJsonType, ConstructibleArrayType,
  585. enable_if_t<not std::is_same<ConstructibleArrayType,
  586. typename BasicJsonType::value_type>::value and
  587. is_detected<value_type_t, ConstructibleArrayType>::value and
  588. is_detected<iterator_t, ConstructibleArrayType>::value and
  589. is_complete_type<
  590. detected_t<value_type_t, ConstructibleArrayType>>::value >>
  591. {
  592. static constexpr bool value =
  593. // This is needed because json_reverse_iterator has a ::iterator type,
  594. // furthermore, std::back_insert_iterator (and other iterators) have a base class `iterator`...
  595. // Therefore it is detected as a ConstructibleArrayType.
  596. // The real fix would be to have an Iterable concept.
  597. not is_iterator_traits <
  598. iterator_traits<ConstructibleArrayType >>::value and
  599. (std::is_same<typename ConstructibleArrayType::value_type, typename BasicJsonType::array_t::value_type>::value or
  600. has_from_json<BasicJsonType,
  601. typename ConstructibleArrayType::value_type>::value or
  602. has_non_default_from_json <
  603. BasicJsonType, typename ConstructibleArrayType::value_type >::value);
  604. };
  605. template <typename BasicJsonType, typename ConstructibleArrayType>
  606. struct is_constructible_array_type
  607. : is_constructible_array_type_impl<BasicJsonType, ConstructibleArrayType> {};
  608. template <typename RealIntegerType, typename CompatibleNumberIntegerType,
  609. typename = void>
  610. struct is_compatible_integer_type_impl : std::false_type {};
  611. template <typename RealIntegerType, typename CompatibleNumberIntegerType>
  612. struct is_compatible_integer_type_impl <
  613. RealIntegerType, CompatibleNumberIntegerType,
  614. enable_if_t<std::is_integral<RealIntegerType>::value and
  615. std::is_integral<CompatibleNumberIntegerType>::value and
  616. not std::is_same<bool, CompatibleNumberIntegerType>::value >>
  617. {
  618. // is there an assert somewhere on overflows?
  619. using RealLimits = std::numeric_limits<RealIntegerType>;
  620. using CompatibleLimits = std::numeric_limits<CompatibleNumberIntegerType>;
  621. static constexpr auto value =
  622. std::is_constructible<RealIntegerType,
  623. CompatibleNumberIntegerType>::value and
  624. CompatibleLimits::is_integer and
  625. RealLimits::is_signed == CompatibleLimits::is_signed;
  626. };
  627. template <typename RealIntegerType, typename CompatibleNumberIntegerType>
  628. struct is_compatible_integer_type
  629. : is_compatible_integer_type_impl<RealIntegerType,
  630. CompatibleNumberIntegerType> {};
  631. template <typename BasicJsonType, typename CompatibleType, typename = void>
  632. struct is_compatible_type_impl: std::false_type {};
  633. template <typename BasicJsonType, typename CompatibleType>
  634. struct is_compatible_type_impl <
  635. BasicJsonType, CompatibleType,
  636. enable_if_t<is_complete_type<CompatibleType>::value >>
  637. {
  638. static constexpr bool value =
  639. has_to_json<BasicJsonType, CompatibleType>::value;
  640. };
  641. template <typename BasicJsonType, typename CompatibleType>
  642. struct is_compatible_type
  643. : is_compatible_type_impl<BasicJsonType, CompatibleType> {};
  644. } // namespace detail
  645. } // namespace nlohmann
  646. // #include <nlohmann/detail/exceptions.hpp>
  647. #include <exception> // exception
  648. #include <stdexcept> // runtime_error
  649. #include <string> // to_string
  650. // #include <nlohmann/detail/input/position_t.hpp>
  651. #include <cstddef> // size_t
  652. namespace nlohmann
  653. {
  654. namespace detail
  655. {
  656. /// struct to capture the start position of the current token
  657. struct position_t
  658. {
  659. /// the total number of characters read
  660. std::size_t chars_read_total = 0;
  661. /// the number of characters read in the current line
  662. std::size_t chars_read_current_line = 0;
  663. /// the number of lines read
  664. std::size_t lines_read = 0;
  665. /// conversion to size_t to preserve SAX interface
  666. constexpr operator size_t() const
  667. {
  668. return chars_read_total;
  669. }
  670. };
  671. }
  672. }
  673. namespace nlohmann
  674. {
  675. namespace detail
  676. {
  677. ////////////////
  678. // exceptions //
  679. ////////////////
  680. /*!
  681. @brief general exception of the @ref basic_json class
  682. This class is an extension of `std::exception` objects with a member @a id for
  683. exception ids. It is used as the base class for all exceptions thrown by the
  684. @ref basic_json class. This class can hence be used as "wildcard" to catch
  685. exceptions.
  686. Subclasses:
  687. - @ref parse_error for exceptions indicating a parse error
  688. - @ref invalid_iterator for exceptions indicating errors with iterators
  689. - @ref type_error for exceptions indicating executing a member function with
  690. a wrong type
  691. - @ref out_of_range for exceptions indicating access out of the defined range
  692. - @ref other_error for exceptions indicating other library errors
  693. @internal
  694. @note To have nothrow-copy-constructible exceptions, we internally use
  695. `std::runtime_error` which can cope with arbitrary-length error messages.
  696. Intermediate strings are built with static functions and then passed to
  697. the actual constructor.
  698. @endinternal
  699. @liveexample{The following code shows how arbitrary library exceptions can be
  700. caught.,exception}
  701. @since version 3.0.0
  702. */
  703. class exception : public std::exception
  704. {
  705. public:
  706. /// returns the explanatory string
  707. const char* what() const noexcept override
  708. {
  709. return m.what();
  710. }
  711. /// the id of the exception
  712. const int id;
  713. protected:
  714. exception(int id_, const char* what_arg) : id(id_), m(what_arg) {}
  715. static std::string name(const std::string& ename, int id_)
  716. {
  717. return "[json.exception." + ename + "." + std::to_string(id_) + "] ";
  718. }
  719. private:
  720. /// an exception object as storage for error messages
  721. std::runtime_error m;
  722. };
  723. /*!
  724. @brief exception indicating a parse error
  725. This exception is thrown by the library when a parse error occurs. Parse errors
  726. can occur during the deserialization of JSON text, CBOR, MessagePack, as well
  727. as when using JSON Patch.
  728. Member @a byte holds the byte index of the last read character in the input
  729. file.
  730. Exceptions have ids 1xx.
  731. name / id | example message | description
  732. ------------------------------ | --------------- | -------------------------
  733. 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.
  734. 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.
  735. 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.
  736. 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.
  737. 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.
  738. 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`.
  739. 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.
  740. 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.
  741. json.exception.parse_error.109 | parse error: array index 'one' is not a number | A JSON Pointer array index must be a number.
  742. 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.
  743. 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.
  744. 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.
  745. json.exception.parse_error.114 | parse error: Unsupported BSON record type 0x0F | The parsing of the corresponding BSON record type is not implemented (yet).
  746. @note For an input with n bytes, 1 is the index of the first character and n+1
  747. is the index of the terminating null byte or the end of file. This also
  748. holds true when reading a byte vector (CBOR or MessagePack).
  749. @liveexample{The following code shows how a `parse_error` exception can be
  750. caught.,parse_error}
  751. @sa @ref exception for the base class of the library exceptions
  752. @sa @ref invalid_iterator for exceptions indicating errors with iterators
  753. @sa @ref type_error for exceptions indicating executing a member function with
  754. a wrong type
  755. @sa @ref out_of_range for exceptions indicating access out of the defined range
  756. @sa @ref other_error for exceptions indicating other library errors
  757. @since version 3.0.0
  758. */
  759. class parse_error : public exception
  760. {
  761. public:
  762. /*!
  763. @brief create a parse error exception
  764. @param[in] id_ the id of the exception
  765. @param[in] position the position where the error occurred (or with
  766. chars_read_total=0 if the position cannot be
  767. determined)
  768. @param[in] what_arg the explanatory string
  769. @return parse_error object
  770. */
  771. static parse_error create(int id_, const position_t& pos, const std::string& what_arg)
  772. {
  773. std::string w = exception::name("parse_error", id_) + "parse error" +
  774. position_string(pos) + ": " + what_arg;
  775. return parse_error(id_, pos.chars_read_total, w.c_str());
  776. }
  777. static parse_error create(int id_, std::size_t byte_, const std::string& what_arg)
  778. {
  779. std::string w = exception::name("parse_error", id_) + "parse error" +
  780. (byte_ != 0 ? (" at byte " + std::to_string(byte_)) : "") +
  781. ": " + what_arg;
  782. return parse_error(id_, byte_, w.c_str());
  783. }
  784. /*!
  785. @brief byte index of the parse error
  786. The byte index of the last read character in the input file.
  787. @note For an input with n bytes, 1 is the index of the first character and
  788. n+1 is the index of the terminating null byte or the end of file.
  789. This also holds true when reading a byte vector (CBOR or MessagePack).
  790. */
  791. const std::size_t byte;
  792. private:
  793. parse_error(int id_, std::size_t byte_, const char* what_arg)
  794. : exception(id_, what_arg), byte(byte_) {}
  795. static std::string position_string(const position_t& pos)
  796. {
  797. return " at line " + std::to_string(pos.lines_read + 1) +
  798. ", column " + std::to_string(pos.chars_read_current_line);
  799. }
  800. };
  801. /*!
  802. @brief exception indicating errors with iterators
  803. This exception is thrown if iterators passed to a library function do not match
  804. the expected semantics.
  805. Exceptions have ids 2xx.
  806. name / id | example message | description
  807. ----------------------------------- | --------------- | -------------------------
  808. 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.
  809. 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.
  810. 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.
  811. 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.
  812. 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.
  813. 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.
  814. 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.
  815. 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.
  816. 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.
  817. 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.
  818. 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.
  819. json.exception.invalid_iterator.212 | cannot compare iterators of different containers | When two iterators are compared, they must belong to the same container.
  820. json.exception.invalid_iterator.213 | cannot compare order of object iterators | The order of object iterators cannot be compared, because JSON objects are unordered.
  821. 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().
  822. @liveexample{The following code shows how an `invalid_iterator` exception can be
  823. caught.,invalid_iterator}
  824. @sa @ref exception for the base class of the library exceptions
  825. @sa @ref parse_error for exceptions indicating a parse error
  826. @sa @ref type_error for exceptions indicating executing a member function with
  827. a wrong type
  828. @sa @ref out_of_range for exceptions indicating access out of the defined range
  829. @sa @ref other_error for exceptions indicating other library errors
  830. @since version 3.0.0
  831. */
  832. class invalid_iterator : public exception
  833. {
  834. public:
  835. static invalid_iterator create(int id_, const std::string& what_arg)
  836. {
  837. std::string w = exception::name("invalid_iterator", id_) + what_arg;
  838. return invalid_iterator(id_, w.c_str());
  839. }
  840. private:
  841. invalid_iterator(int id_, const char* what_arg)
  842. : exception(id_, what_arg) {}
  843. };
  844. /*!
  845. @brief exception indicating executing a member function with a wrong type
  846. This exception is thrown in case of a type error; that is, a library function is
  847. executed on a JSON value whose type does not match the expected semantics.
  848. Exceptions have ids 3xx.
  849. name / id | example message | description
  850. ----------------------------- | --------------- | -------------------------
  851. 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.
  852. 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.
  853. 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&.
  854. json.exception.type_error.304 | cannot use at() with string | The @ref at() member functions can only be executed for certain JSON types.
  855. json.exception.type_error.305 | cannot use operator[] with string | The @ref operator[] member functions can only be executed for certain JSON types.
  856. json.exception.type_error.306 | cannot use value() with string | The @ref value() member functions can only be executed for certain JSON types.
  857. json.exception.type_error.307 | cannot use erase() with string | The @ref erase() member functions can only be executed for certain JSON types.
  858. 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.
  859. json.exception.type_error.309 | cannot use insert() with | The @ref insert() member functions can only be executed for certain JSON types.
  860. json.exception.type_error.310 | cannot use swap() with number | The @ref swap() member functions can only be executed for certain JSON types.
  861. 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.
  862. json.exception.type_error.312 | cannot use update() with string | The @ref update() member functions can only be executed for certain JSON types.
  863. 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.
  864. json.exception.type_error.314 | only objects can be unflattened | The @ref unflatten function only works for an object whose keys are JSON Pointers.
  865. 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.
  866. 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. |
  867. json.exception.type_error.317 | JSON value cannot be serialized to requested format | The dynamic type of the object cannot be represented in the requested serialization format (e.g. a raw `true` or `null` JSON object cannot be serialized to BSON) |
  868. @liveexample{The following code shows how a `type_error` exception can be
  869. caught.,type_error}
  870. @sa @ref exception for the base class of the library exceptions
  871. @sa @ref parse_error for exceptions indicating a parse error
  872. @sa @ref invalid_iterator for exceptions indicating errors with iterators
  873. @sa @ref out_of_range for exceptions indicating access out of the defined range
  874. @sa @ref other_error for exceptions indicating other library errors
  875. @since version 3.0.0
  876. */
  877. class type_error : public exception
  878. {
  879. public:
  880. static type_error create(int id_, const std::string& what_arg)
  881. {
  882. std::string w = exception::name("type_error", id_) + what_arg;
  883. return type_error(id_, w.c_str());
  884. }
  885. private:
  886. type_error(int id_, const char* what_arg) : exception(id_, what_arg) {}
  887. };
  888. /*!
  889. @brief exception indicating access out of the defined range
  890. This exception is thrown in case a library function is called on an input
  891. parameter that exceeds the expected range, for instance in case of array
  892. indices or nonexisting object keys.
  893. Exceptions have ids 4xx.
  894. name / id | example message | description
  895. ------------------------------- | --------------- | -------------------------
  896. 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.
  897. 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.
  898. json.exception.out_of_range.403 | key 'foo' not found | The provided key was not found in the JSON object.
  899. json.exception.out_of_range.404 | unresolved reference token 'foo' | A reference token in a JSON Pointer could not be resolved.
  900. 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.
  901. 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.
  902. json.exception.out_of_range.407 | number overflow serializing '9223372036854775808' | UBJSON and BSON only support integer numbers up to 9223372036854775807. |
  903. json.exception.out_of_range.408 | excessive array size: 8658170730974374167 | The size (following `#`) of an UBJSON array or object exceeds the maximal capacity. |
  904. json.exception.out_of_range.409 | BSON key cannot contain code point U+0000 (at byte 2) | Key identifiers to be serialized to BSON cannot contain code point U+0000, since the key is stored as zero-terminated c-string |
  905. @liveexample{The following code shows how an `out_of_range` exception can be
  906. caught.,out_of_range}
  907. @sa @ref exception for the base class of the library exceptions
  908. @sa @ref parse_error for exceptions indicating a parse error
  909. @sa @ref invalid_iterator for exceptions indicating errors with iterators
  910. @sa @ref type_error for exceptions indicating executing a member function with
  911. a wrong type
  912. @sa @ref other_error for exceptions indicating other library errors
  913. @since version 3.0.0
  914. */
  915. class out_of_range : public exception
  916. {
  917. public:
  918. static out_of_range create(int id_, const std::string& what_arg)
  919. {
  920. std::string w = exception::name("out_of_range", id_) + what_arg;
  921. return out_of_range(id_, w.c_str());
  922. }
  923. private:
  924. out_of_range(int id_, const char* what_arg) : exception(id_, what_arg) {}
  925. };
  926. /*!
  927. @brief exception indicating other library errors
  928. This exception is thrown in case of errors that cannot be classified with the
  929. other exception types.
  930. Exceptions have ids 5xx.
  931. name / id | example message | description
  932. ------------------------------ | --------------- | -------------------------
  933. json.exception.other_error.501 | unsuccessful: {"op":"test","path":"/baz", "value":"bar"} | A JSON Patch operation 'test' failed. The unsuccessful operation is also printed.
  934. @sa @ref exception for the base class of the library exceptions
  935. @sa @ref parse_error for exceptions indicating a parse error
  936. @sa @ref invalid_iterator for exceptions indicating errors with iterators
  937. @sa @ref type_error for exceptions indicating executing a member function with
  938. a wrong type
  939. @sa @ref out_of_range for exceptions indicating access out of the defined range
  940. @liveexample{The following code shows how an `other_error` exception can be
  941. caught.,other_error}
  942. @since version 3.0.0
  943. */
  944. class other_error : public exception
  945. {
  946. public:
  947. static other_error create(int id_, const std::string& what_arg)
  948. {
  949. std::string w = exception::name("other_error", id_) + what_arg;
  950. return other_error(id_, w.c_str());
  951. }
  952. private:
  953. other_error(int id_, const char* what_arg) : exception(id_, what_arg) {}
  954. };
  955. } // namespace detail
  956. } // namespace nlohmann
  957. // #include <nlohmann/detail/value_t.hpp>
  958. #include <array> // array
  959. #include <ciso646> // and
  960. #include <cstddef> // size_t
  961. #include <cstdint> // uint8_t
  962. namespace nlohmann
  963. {
  964. namespace detail
  965. {
  966. ///////////////////////////
  967. // JSON type enumeration //
  968. ///////////////////////////
  969. /*!
  970. @brief the JSON type enumeration
  971. This enumeration collects the different JSON types. It is internally used to
  972. distinguish the stored values, and the functions @ref basic_json::is_null(),
  973. @ref basic_json::is_object(), @ref basic_json::is_array(),
  974. @ref basic_json::is_string(), @ref basic_json::is_boolean(),
  975. @ref basic_json::is_number() (with @ref basic_json::is_number_integer(),
  976. @ref basic_json::is_number_unsigned(), and @ref basic_json::is_number_float()),
  977. @ref basic_json::is_discarded(), @ref basic_json::is_primitive(), and
  978. @ref basic_json::is_structured() rely on it.
  979. @note There are three enumeration entries (number_integer, number_unsigned, and
  980. number_float), because the library distinguishes these three types for numbers:
  981. @ref basic_json::number_unsigned_t is used for unsigned integers,
  982. @ref basic_json::number_integer_t is used for signed integers, and
  983. @ref basic_json::number_float_t is used for floating-point numbers or to
  984. approximate integers which do not fit in the limits of their respective type.
  985. @sa @ref basic_json::basic_json(const value_t value_type) -- create a JSON
  986. value with the default value for a given type
  987. @since version 1.0.0
  988. */
  989. enum class value_t : std::uint8_t
  990. {
  991. null, ///< null value
  992. object, ///< object (unordered set of name/value pairs)
  993. array, ///< array (ordered collection of values)
  994. string, ///< string value
  995. boolean, ///< boolean value
  996. number_integer, ///< number value (signed integer)
  997. number_unsigned, ///< number value (unsigned integer)
  998. number_float, ///< number value (floating-point)
  999. discarded ///< discarded by the the parser callback function
  1000. };
  1001. /*!
  1002. @brief comparison operator for JSON types
  1003. Returns an ordering that is similar to Python:
  1004. - order: null < boolean < number < object < array < string
  1005. - furthermore, each type is not smaller than itself
  1006. - discarded values are not comparable
  1007. @since version 1.0.0
  1008. */
  1009. inline bool operator<(const value_t lhs, const value_t rhs) noexcept
  1010. {
  1011. static constexpr std::array<std::uint8_t, 8> order = {{
  1012. 0 /* null */, 3 /* object */, 4 /* array */, 5 /* string */,
  1013. 1 /* boolean */, 2 /* integer */, 2 /* unsigned */, 2 /* float */
  1014. }
  1015. };
  1016. const auto l_index = static_cast<std::size_t>(lhs);
  1017. const auto r_index = static_cast<std::size_t>(rhs);
  1018. return l_index < order.size() and r_index < order.size() and order[l_index] < order[r_index];
  1019. }
  1020. } // namespace detail
  1021. } // namespace nlohmann
  1022. // #include <nlohmann/detail/conversions/from_json.hpp>
  1023. #include <algorithm> // transform
  1024. #include <array> // array
  1025. #include <ciso646> // and, not
  1026. #include <forward_list> // forward_list
  1027. #include <iterator> // inserter, front_inserter, end
  1028. #include <map> // map
  1029. #include <string> // string
  1030. #include <tuple> // tuple, make_tuple
  1031. #include <type_traits> // is_arithmetic, is_same, is_enum, underlying_type, is_convertible
  1032. #include <unordered_map> // unordered_map
  1033. #include <utility> // pair, declval
  1034. #include <valarray> // valarray
  1035. // #include <nlohmann/detail/exceptions.hpp>
  1036. // #include <nlohmann/detail/macro_scope.hpp>
  1037. // #include <nlohmann/detail/meta/cpp_future.hpp>
  1038. // #include <nlohmann/detail/meta/type_traits.hpp>
  1039. // #include <nlohmann/detail/value_t.hpp>
  1040. namespace nlohmann
  1041. {
  1042. namespace detail
  1043. {
  1044. template<typename BasicJsonType>
  1045. void from_json(const BasicJsonType& j, typename std::nullptr_t& n)
  1046. {
  1047. if (JSON_UNLIKELY(not j.is_null()))
  1048. {
  1049. JSON_THROW(type_error::create(302, "type must be null, but is " + std::string(j.type_name())));
  1050. }
  1051. n = nullptr;
  1052. }
  1053. // overloads for basic_json template parameters
  1054. template<typename BasicJsonType, typename ArithmeticType,
  1055. enable_if_t<std::is_arithmetic<ArithmeticType>::value and
  1056. not std::is_same<ArithmeticType, typename BasicJsonType::boolean_t>::value,
  1057. int> = 0>
  1058. void get_arithmetic_value(const BasicJsonType& j, ArithmeticType& val)
  1059. {
  1060. switch (static_cast<value_t>(j))
  1061. {
  1062. case value_t::number_unsigned:
  1063. {
  1064. val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::number_unsigned_t*>());
  1065. break;
  1066. }
  1067. case value_t::number_integer:
  1068. {
  1069. val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::number_integer_t*>());
  1070. break;
  1071. }
  1072. case value_t::number_float:
  1073. {
  1074. val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::number_float_t*>());
  1075. break;
  1076. }
  1077. default:
  1078. JSON_THROW(type_error::create(302, "type must be number, but is " + std::string(j.type_name())));
  1079. }
  1080. }
  1081. template<typename BasicJsonType>
  1082. void from_json(const BasicJsonType& j, typename BasicJsonType::boolean_t& b)
  1083. {
  1084. if (JSON_UNLIKELY(not j.is_boolean()))
  1085. {
  1086. JSON_THROW(type_error::create(302, "type must be boolean, but is " + std::string(j.type_name())));
  1087. }
  1088. b = *j.template get_ptr<const typename BasicJsonType::boolean_t*>();
  1089. }
  1090. template<typename BasicJsonType>
  1091. void from_json(const BasicJsonType& j, typename BasicJsonType::string_t& s)
  1092. {
  1093. if (JSON_UNLIKELY(not j.is_string()))
  1094. {
  1095. JSON_THROW(type_error::create(302, "type must be string, but is " + std::string(j.type_name())));
  1096. }
  1097. s = *j.template get_ptr<const typename BasicJsonType::string_t*>();
  1098. }
  1099. template <
  1100. typename BasicJsonType, typename ConstructibleStringType,
  1101. enable_if_t <
  1102. is_constructible_string_type<BasicJsonType, ConstructibleStringType>::value and
  1103. not std::is_same<typename BasicJsonType::string_t,
  1104. ConstructibleStringType>::value,
  1105. int > = 0 >
  1106. void from_json(const BasicJsonType& j, ConstructibleStringType& s)
  1107. {
  1108. if (JSON_UNLIKELY(not j.is_string()))
  1109. {
  1110. JSON_THROW(type_error::create(302, "type must be string, but is " + std::string(j.type_name())));
  1111. }
  1112. s = *j.template get_ptr<const typename BasicJsonType::string_t*>();
  1113. }
  1114. template<typename BasicJsonType>
  1115. void from_json(const BasicJsonType& j, typename BasicJsonType::number_float_t& val)
  1116. {
  1117. get_arithmetic_value(j, val);
  1118. }
  1119. template<typename BasicJsonType>
  1120. void from_json(const BasicJsonType& j, typename BasicJsonType::number_unsigned_t& val)
  1121. {
  1122. get_arithmetic_value(j, val);
  1123. }
  1124. template<typename BasicJsonType>
  1125. void from_json(const BasicJsonType& j, typename BasicJsonType::number_integer_t& val)
  1126. {
  1127. get_arithmetic_value(j, val);
  1128. }
  1129. template<typename BasicJsonType, typename EnumType,
  1130. enable_if_t<std::is_enum<EnumType>::value, int> = 0>
  1131. void from_json(const BasicJsonType& j, EnumType& e)
  1132. {
  1133. typename std::underlying_type<EnumType>::type val;
  1134. get_arithmetic_value(j, val);
  1135. e = static_cast<EnumType>(val);
  1136. }
  1137. // forward_list doesn't have an insert method
  1138. template<typename BasicJsonType, typename T, typename Allocator,
  1139. enable_if_t<std::is_convertible<BasicJsonType, T>::value, int> = 0>
  1140. void from_json(const BasicJsonType& j, std::forward_list<T, Allocator>& l)
  1141. {
  1142. if (JSON_UNLIKELY(not j.is_array()))
  1143. {
  1144. JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(j.type_name())));
  1145. }
  1146. std::transform(j.rbegin(), j.rend(),
  1147. std::front_inserter(l), [](const BasicJsonType & i)
  1148. {
  1149. return i.template get<T>();
  1150. });
  1151. }
  1152. // valarray doesn't have an insert method
  1153. template<typename BasicJsonType, typename T,
  1154. enable_if_t<std::is_convertible<BasicJsonType, T>::value, int> = 0>
  1155. void from_json(const BasicJsonType& j, std::valarray<T>& l)
  1156. {
  1157. if (JSON_UNLIKELY(not j.is_array()))
  1158. {
  1159. JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(j.type_name())));
  1160. }
  1161. l.resize(j.size());
  1162. std::copy(j.m_value.array->begin(), j.m_value.array->end(), std::begin(l));
  1163. }
  1164. template<typename BasicJsonType>
  1165. void from_json_array_impl(const BasicJsonType& j, typename BasicJsonType::array_t& arr, priority_tag<3> /*unused*/)
  1166. {
  1167. arr = *j.template get_ptr<const typename BasicJsonType::array_t*>();
  1168. }
  1169. template <typename BasicJsonType, typename T, std::size_t N>
  1170. auto from_json_array_impl(const BasicJsonType& j, std::array<T, N>& arr,
  1171. priority_tag<2> /*unused*/)
  1172. -> decltype(j.template get<T>(), void())
  1173. {
  1174. for (std::size_t i = 0; i < N; ++i)
  1175. {
  1176. arr[i] = j.at(i).template get<T>();
  1177. }
  1178. }
  1179. template<typename BasicJsonType, typename ConstructibleArrayType>
  1180. auto from_json_array_impl(const BasicJsonType& j, ConstructibleArrayType& arr, priority_tag<1> /*unused*/)
  1181. -> decltype(
  1182. arr.reserve(std::declval<typename ConstructibleArrayType::size_type>()),
  1183. j.template get<typename ConstructibleArrayType::value_type>(),
  1184. void())
  1185. {
  1186. using std::end;
  1187. arr.reserve(j.size());
  1188. std::transform(j.begin(), j.end(),
  1189. std::inserter(arr, end(arr)), [](const BasicJsonType & i)
  1190. {
  1191. // get<BasicJsonType>() returns *this, this won't call a from_json
  1192. // method when value_type is BasicJsonType
  1193. return i.template get<typename ConstructibleArrayType::value_type>();
  1194. });
  1195. }
  1196. template <typename BasicJsonType, typename ConstructibleArrayType>
  1197. void from_json_array_impl(const BasicJsonType& j, ConstructibleArrayType& arr,
  1198. priority_tag<0> /*unused*/)
  1199. {
  1200. using std::end;
  1201. std::transform(
  1202. j.begin(), j.end(), std::inserter(arr, end(arr)),
  1203. [](const BasicJsonType & i)
  1204. {
  1205. // get<BasicJsonType>() returns *this, this won't call a from_json
  1206. // method when value_type is BasicJsonType
  1207. return i.template get<typename ConstructibleArrayType::value_type>();
  1208. });
  1209. }
  1210. template <typename BasicJsonType, typename ConstructibleArrayType,
  1211. enable_if_t <
  1212. is_constructible_array_type<BasicJsonType, ConstructibleArrayType>::value and
  1213. not is_constructible_object_type<BasicJsonType, ConstructibleArrayType>::value and
  1214. not is_constructible_string_type<BasicJsonType, ConstructibleArrayType>::value and
  1215. not is_basic_json<ConstructibleArrayType>::value,
  1216. int > = 0 >
  1217. auto from_json(const BasicJsonType& j, ConstructibleArrayType& arr)
  1218. -> decltype(from_json_array_impl(j, arr, priority_tag<3> {}),
  1219. j.template get<typename ConstructibleArrayType::value_type>(),
  1220. void())
  1221. {
  1222. if (JSON_UNLIKELY(not j.is_array()))
  1223. {
  1224. JSON_THROW(type_error::create(302, "type must be array, but is " +
  1225. std::string(j.type_name())));
  1226. }
  1227. from_json_array_impl(j, arr, priority_tag<3> {});
  1228. }
  1229. template<typename BasicJsonType, typename ConstructibleObjectType,
  1230. enable_if_t<is_constructible_object_type<BasicJsonType, ConstructibleObjectType>::value, int> = 0>
  1231. void from_json(const BasicJsonType& j, ConstructibleObjectType& obj)
  1232. {
  1233. if (JSON_UNLIKELY(not j.is_object()))
  1234. {
  1235. JSON_THROW(type_error::create(302, "type must be object, but is " + std::string(j.type_name())));
  1236. }
  1237. auto inner_object = j.template get_ptr<const typename BasicJsonType::object_t*>();
  1238. using value_type = typename ConstructibleObjectType::value_type;
  1239. std::transform(
  1240. inner_object->begin(), inner_object->end(),
  1241. std::inserter(obj, obj.begin()),
  1242. [](typename BasicJsonType::object_t::value_type const & p)
  1243. {
  1244. return value_type(p.first, p.second.template get<typename ConstructibleObjectType::mapped_type>());
  1245. });
  1246. }
  1247. // overload for arithmetic types, not chosen for basic_json template arguments
  1248. // (BooleanType, etc..); note: Is it really necessary to provide explicit
  1249. // overloads for boolean_t etc. in case of a custom BooleanType which is not
  1250. // an arithmetic type?
  1251. template<typename BasicJsonType, typename ArithmeticType,
  1252. enable_if_t <
  1253. std::is_arithmetic<ArithmeticType>::value and
  1254. not std::is_same<ArithmeticType, typename BasicJsonType::number_unsigned_t>::value and
  1255. not std::is_same<ArithmeticType, typename BasicJsonType::number_integer_t>::value and
  1256. not std::is_same<ArithmeticType, typename BasicJsonType::number_float_t>::value and
  1257. not std::is_same<ArithmeticType, typename BasicJsonType::boolean_t>::value,
  1258. int> = 0>
  1259. void from_json(const BasicJsonType& j, ArithmeticType& val)
  1260. {
  1261. switch (static_cast<value_t>(j))
  1262. {
  1263. case value_t::number_unsigned:
  1264. {
  1265. val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::number_unsigned_t*>());
  1266. break;
  1267. }
  1268. case value_t::number_integer:
  1269. {
  1270. val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::number_integer_t*>());
  1271. break;
  1272. }
  1273. case value_t::number_float:
  1274. {
  1275. val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::number_float_t*>());
  1276. break;
  1277. }
  1278. case value_t::boolean:
  1279. {
  1280. val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::boolean_t*>());
  1281. break;
  1282. }
  1283. default:
  1284. JSON_THROW(type_error::create(302, "type must be number, but is " + std::string(j.type_name())));
  1285. }
  1286. }
  1287. template<typename BasicJsonType, typename A1, typename A2>
  1288. void from_json(const BasicJsonType& j, std::pair<A1, A2>& p)
  1289. {
  1290. p = {j.at(0).template get<A1>(), j.at(1).template get<A2>()};
  1291. }
  1292. template<typename BasicJsonType, typename Tuple, std::size_t... Idx>
  1293. void from_json_tuple_impl(const BasicJsonType& j, Tuple& t, index_sequence<Idx...> /*unused*/)
  1294. {
  1295. t = std::make_tuple(j.at(Idx).template get<typename std::tuple_element<Idx, Tuple>::type>()...);
  1296. }
  1297. template<typename BasicJsonType, typename... Args>
  1298. void from_json(const BasicJsonType& j, std::tuple<Args...>& t)
  1299. {
  1300. from_json_tuple_impl(j, t, index_sequence_for<Args...> {});
  1301. }
  1302. template <typename BasicJsonType, typename Key, typename Value, typename Compare, typename Allocator,
  1303. typename = enable_if_t<not std::is_constructible<
  1304. typename BasicJsonType::string_t, Key>::value>>
  1305. void from_json(const BasicJsonType& j, std::map<Key, Value, Compare, Allocator>& m)
  1306. {
  1307. if (JSON_UNLIKELY(not j.is_array()))
  1308. {
  1309. JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(j.type_name())));
  1310. }
  1311. for (const auto& p : j)
  1312. {
  1313. if (JSON_UNLIKELY(not p.is_array()))
  1314. {
  1315. JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(p.type_name())));
  1316. }
  1317. m.emplace(p.at(0).template get<Key>(), p.at(1).template get<Value>());
  1318. }
  1319. }
  1320. template <typename BasicJsonType, typename Key, typename Value, typename Hash, typename KeyEqual, typename Allocator,
  1321. typename = enable_if_t<not std::is_constructible<
  1322. typename BasicJsonType::string_t, Key>::value>>
  1323. void from_json(const BasicJsonType& j, std::unordered_map<Key, Value, Hash, KeyEqual, Allocator>& m)
  1324. {
  1325. if (JSON_UNLIKELY(not j.is_array()))
  1326. {
  1327. JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(j.type_name())));
  1328. }
  1329. for (const auto& p : j)
  1330. {
  1331. if (JSON_UNLIKELY(not p.is_array()))
  1332. {
  1333. JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(p.type_name())));
  1334. }
  1335. m.emplace(p.at(0).template get<Key>(), p.at(1).template get<Value>());
  1336. }
  1337. }
  1338. struct from_json_fn
  1339. {
  1340. template<typename BasicJsonType, typename T>
  1341. auto operator()(const BasicJsonType& j, T& val) const
  1342. noexcept(noexcept(from_json(j, val)))
  1343. -> decltype(from_json(j, val), void())
  1344. {
  1345. return from_json(j, val);
  1346. }
  1347. };
  1348. } // namespace detail
  1349. /// namespace to hold default `from_json` function
  1350. /// to see why this is required:
  1351. /// http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2015/n4381.html
  1352. namespace
  1353. {
  1354. constexpr const auto& from_json = detail::static_const<detail::from_json_fn>::value;
  1355. } // namespace
  1356. } // namespace nlohmann
  1357. // #include <nlohmann/detail/conversions/to_json.hpp>
  1358. #include <ciso646> // or, and, not
  1359. #include <iterator> // begin, end
  1360. #include <tuple> // tuple, get
  1361. #include <type_traits> // is_same, is_constructible, is_floating_point, is_enum, underlying_type
  1362. #include <utility> // move, forward, declval, pair
  1363. #include <valarray> // valarray
  1364. #include <vector> // vector
  1365. // #include <nlohmann/detail/meta/cpp_future.hpp>
  1366. // #include <nlohmann/detail/meta/type_traits.hpp>
  1367. // #include <nlohmann/detail/value_t.hpp>
  1368. // #include <nlohmann/detail/iterators/iteration_proxy.hpp>
  1369. #include <cstddef> // size_t
  1370. #include <string> // string, to_string
  1371. #include <iterator> // input_iterator_tag
  1372. #include <tuple> // tuple_size, get, tuple_element
  1373. // #include <nlohmann/detail/value_t.hpp>
  1374. // #include <nlohmann/detail/meta/type_traits.hpp>
  1375. namespace nlohmann
  1376. {
  1377. namespace detail
  1378. {
  1379. template <typename IteratorType> class iteration_proxy_value
  1380. {
  1381. public:
  1382. using difference_type = std::ptrdiff_t;
  1383. using value_type = iteration_proxy_value;
  1384. using pointer = value_type * ;
  1385. using reference = value_type & ;
  1386. using iterator_category = std::input_iterator_tag;
  1387. private:
  1388. /// the iterator
  1389. IteratorType anchor;
  1390. /// an index for arrays (used to create key names)
  1391. std::size_t array_index = 0;
  1392. /// last stringified array index
  1393. mutable std::size_t array_index_last = 0;
  1394. /// a string representation of the array index
  1395. mutable std::string array_index_str = "0";
  1396. /// an empty string (to return a reference for primitive values)
  1397. const std::string empty_str = "";
  1398. public:
  1399. explicit iteration_proxy_value(IteratorType it) noexcept : anchor(it) {}
  1400. /// dereference operator (needed for range-based for)
  1401. iteration_proxy_value& operator*()
  1402. {
  1403. return *this;
  1404. }
  1405. /// increment operator (needed for range-based for)
  1406. iteration_proxy_value& operator++()
  1407. {
  1408. ++anchor;
  1409. ++array_index;
  1410. return *this;
  1411. }
  1412. /// equality operator (needed for InputIterator)
  1413. bool operator==(const iteration_proxy_value& o) const noexcept
  1414. {
  1415. return anchor == o.anchor;
  1416. }
  1417. /// inequality operator (needed for range-based for)
  1418. bool operator!=(const iteration_proxy_value& o) const noexcept
  1419. {
  1420. return anchor != o.anchor;
  1421. }
  1422. /// return key of the iterator
  1423. const std::string& key() const
  1424. {
  1425. assert(anchor.m_object != nullptr);
  1426. switch (anchor.m_object->type())
  1427. {
  1428. // use integer array index as key
  1429. case value_t::array:
  1430. {
  1431. if (array_index != array_index_last)
  1432. {
  1433. array_index_str = std::to_string(array_index);
  1434. array_index_last = array_index;
  1435. }
  1436. return array_index_str;
  1437. }
  1438. // use key from the object
  1439. case value_t::object:
  1440. return anchor.key();
  1441. // use an empty key for all primitive types
  1442. default:
  1443. return empty_str;
  1444. }
  1445. }
  1446. /// return value of the iterator
  1447. typename IteratorType::reference value() const
  1448. {
  1449. return anchor.value();
  1450. }
  1451. };
  1452. /// proxy class for the items() function
  1453. template<typename IteratorType> class iteration_proxy
  1454. {
  1455. private:
  1456. /// the container to iterate
  1457. typename IteratorType::reference container;
  1458. public:
  1459. /// construct iteration proxy from a container
  1460. explicit iteration_proxy(typename IteratorType::reference cont) noexcept
  1461. : container(cont) {}
  1462. /// return iterator begin (needed for range-based for)
  1463. iteration_proxy_value<IteratorType> begin() noexcept
  1464. {
  1465. return iteration_proxy_value<IteratorType>(container.begin());
  1466. }
  1467. /// return iterator end (needed for range-based for)
  1468. iteration_proxy_value<IteratorType> end() noexcept
  1469. {
  1470. return iteration_proxy_value<IteratorType>(container.end());
  1471. }
  1472. };
  1473. // Structured Bindings Support
  1474. // For further reference see https://blog.tartanllama.xyz/structured-bindings/
  1475. // And see https://github.com/nlohmann/json/pull/1391
  1476. template <std::size_t N, typename IteratorType, enable_if_t<N == 0, int> = 0>
  1477. auto get(const nlohmann::detail::iteration_proxy_value<IteratorType>& i) -> decltype(i.key())
  1478. {
  1479. return i.key();
  1480. }
  1481. // Structured Bindings Support
  1482. // For further reference see https://blog.tartanllama.xyz/structured-bindings/
  1483. // And see https://github.com/nlohmann/json/pull/1391
  1484. template <std::size_t N, typename IteratorType, enable_if_t<N == 1, int> = 0>
  1485. auto get(const nlohmann::detail::iteration_proxy_value<IteratorType>& i) -> decltype(i.value())
  1486. {
  1487. return i.value();
  1488. }
  1489. } // namespace detail
  1490. } // namespace nlohmann
  1491. // The Addition to the STD Namespace is required to add
  1492. // Structured Bindings Support to the iteration_proxy_value class
  1493. // For further reference see https://blog.tartanllama.xyz/structured-bindings/
  1494. // And see https://github.com/nlohmann/json/pull/1391
  1495. namespace std
  1496. {
  1497. template <typename IteratorType>
  1498. class tuple_size<::nlohmann::detail::iteration_proxy_value<IteratorType>>
  1499. : public std::integral_constant<std::size_t, 2> {};
  1500. template <std::size_t N, typename IteratorType>
  1501. class tuple_element<N, ::nlohmann::detail::iteration_proxy_value<IteratorType >>
  1502. {
  1503. public:
  1504. using type = decltype(
  1505. get<N>(std::declval <
  1506. ::nlohmann::detail::iteration_proxy_value<IteratorType >> ()));
  1507. };
  1508. }
  1509. namespace nlohmann
  1510. {
  1511. namespace detail
  1512. {
  1513. //////////////////
  1514. // constructors //
  1515. //////////////////
  1516. template<value_t> struct external_constructor;
  1517. template<>
  1518. struct external_constructor<value_t::boolean>
  1519. {
  1520. template<typename BasicJsonType>
  1521. static void construct(BasicJsonType& j, typename BasicJsonType::boolean_t b) noexcept
  1522. {
  1523. j.m_type = value_t::boolean;
  1524. j.m_value = b;
  1525. j.assert_invariant();
  1526. }
  1527. };
  1528. template<>
  1529. struct external_constructor<value_t::string>
  1530. {
  1531. template<typename BasicJsonType>
  1532. static void construct(BasicJsonType& j, const typename BasicJsonType::string_t& s)
  1533. {
  1534. j.m_type = value_t::string;
  1535. j.m_value = s;
  1536. j.assert_invariant();
  1537. }
  1538. template<typename BasicJsonType>
  1539. static void construct(BasicJsonType& j, typename BasicJsonType::string_t&& s)
  1540. {
  1541. j.m_type = value_t::string;
  1542. j.m_value = std::move(s);
  1543. j.assert_invariant();
  1544. }
  1545. template<typename BasicJsonType, typename CompatibleStringType,
  1546. enable_if_t<not std::is_same<CompatibleStringType, typename BasicJsonType::string_t>::value,
  1547. int> = 0>
  1548. static void construct(BasicJsonType& j, const CompatibleStringType& str)
  1549. {
  1550. j.m_type = value_t::string;
  1551. j.m_value.string = j.template create<typename BasicJsonType::string_t>(str);
  1552. j.assert_invariant();
  1553. }
  1554. };
  1555. template<>
  1556. struct external_constructor<value_t::number_float>
  1557. {
  1558. template<typename BasicJsonType>
  1559. static void construct(BasicJsonType& j, typename BasicJsonType::number_float_t val) noexcept
  1560. {
  1561. j.m_type = value_t::number_float;
  1562. j.m_value = val;
  1563. j.assert_invariant();
  1564. }
  1565. };
  1566. template<>
  1567. struct external_constructor<value_t::number_unsigned>
  1568. {
  1569. template<typename BasicJsonType>
  1570. static void construct(BasicJsonType& j, typename BasicJsonType::number_unsigned_t val) noexcept
  1571. {
  1572. j.m_type = value_t::number_unsigned;
  1573. j.m_value = val;
  1574. j.assert_invariant();
  1575. }
  1576. };
  1577. template<>
  1578. struct external_constructor<value_t::number_integer>
  1579. {
  1580. template<typename BasicJsonType>
  1581. static void construct(BasicJsonType& j, typename BasicJsonType::number_integer_t val) noexcept
  1582. {
  1583. j.m_type = value_t::number_integer;
  1584. j.m_value = val;
  1585. j.assert_invariant();
  1586. }
  1587. };
  1588. template<>
  1589. struct external_constructor<value_t::array>
  1590. {
  1591. template<typename BasicJsonType>
  1592. static void construct(BasicJsonType& j, const typename BasicJsonType::array_t& arr)
  1593. {
  1594. j.m_type = value_t::array;
  1595. j.m_value = arr;
  1596. j.assert_invariant();
  1597. }
  1598. template<typename BasicJsonType>
  1599. static void construct(BasicJsonType& j, typename BasicJsonType::array_t&& arr)
  1600. {
  1601. j.m_type = value_t::array;
  1602. j.m_value = std::move(arr);
  1603. j.assert_invariant();
  1604. }
  1605. template<typename BasicJsonType, typename CompatibleArrayType,
  1606. enable_if_t<not std::is_same<CompatibleArrayType, typename BasicJsonType::array_t>::value,
  1607. int> = 0>
  1608. static void construct(BasicJsonType& j, const CompatibleArrayType& arr)
  1609. {
  1610. using std::begin;
  1611. using std::end;
  1612. j.m_type = value_t::array;
  1613. j.m_value.array = j.template create<typename BasicJsonType::array_t>(begin(arr), end(arr));
  1614. j.assert_invariant();
  1615. }
  1616. template<typename BasicJsonType>
  1617. static void construct(BasicJsonType& j, const std::vector<bool>& arr)
  1618. {
  1619. j.m_type = value_t::array;
  1620. j.m_value = value_t::array;
  1621. j.m_value.array->reserve(arr.size());
  1622. for (const bool x : arr)
  1623. {
  1624. j.m_value.array->push_back(x);
  1625. }
  1626. j.assert_invariant();
  1627. }
  1628. template<typename BasicJsonType, typename T,
  1629. enable_if_t<std::is_convertible<T, BasicJsonType>::value, int> = 0>
  1630. static void construct(BasicJsonType& j, const std::valarray<T>& arr)
  1631. {
  1632. j.m_type = value_t::array;
  1633. j.m_value = value_t::array;
  1634. j.m_value.array->resize(arr.size());
  1635. std::copy(std::begin(arr), std::end(arr), j.m_value.array->begin());
  1636. j.assert_invariant();
  1637. }
  1638. };
  1639. template<>
  1640. struct external_constructor<value_t::object>
  1641. {
  1642. template<typename BasicJsonType>
  1643. static void construct(BasicJsonType& j, const typename BasicJsonType::object_t& obj)
  1644. {
  1645. j.m_type = value_t::object;
  1646. j.m_value = obj;
  1647. j.assert_invariant();
  1648. }
  1649. template<typename BasicJsonType>
  1650. static void construct(BasicJsonType& j, typename BasicJsonType::object_t&& obj)
  1651. {
  1652. j.m_type = value_t::object;
  1653. j.m_value = std::move(obj);
  1654. j.assert_invariant();
  1655. }
  1656. template<typename BasicJsonType, typename CompatibleObjectType,
  1657. enable_if_t<not std::is_same<CompatibleObjectType, typename BasicJsonType::object_t>::value, int> = 0>
  1658. static void construct(BasicJsonType& j, const CompatibleObjectType& obj)
  1659. {
  1660. using std::begin;
  1661. using std::end;
  1662. j.m_type = value_t::object;
  1663. j.m_value.object = j.template create<typename BasicJsonType::object_t>(begin(obj), end(obj));
  1664. j.assert_invariant();
  1665. }
  1666. };
  1667. /////////////
  1668. // to_json //
  1669. /////////////
  1670. template<typename BasicJsonType, typename T,
  1671. enable_if_t<std::is_same<T, typename BasicJsonType::boolean_t>::value, int> = 0>
  1672. void to_json(BasicJsonType& j, T b) noexcept
  1673. {
  1674. external_constructor<value_t::boolean>::construct(j, b);
  1675. }
  1676. template<typename BasicJsonType, typename CompatibleString,
  1677. enable_if_t<std::is_constructible<typename BasicJsonType::string_t, CompatibleString>::value, int> = 0>
  1678. void to_json(BasicJsonType& j, const CompatibleString& s)
  1679. {
  1680. external_constructor<value_t::string>::construct(j, s);
  1681. }
  1682. template<typename BasicJsonType>
  1683. void to_json(BasicJsonType& j, typename BasicJsonType::string_t&& s)
  1684. {
  1685. external_constructor<value_t::string>::construct(j, std::move(s));
  1686. }
  1687. template<typename BasicJsonType, typename FloatType,
  1688. enable_if_t<std::is_floating_point<FloatType>::value, int> = 0>
  1689. void to_json(BasicJsonType& j, FloatType val) noexcept
  1690. {
  1691. external_constructor<value_t::number_float>::construct(j, static_cast<typename BasicJsonType::number_float_t>(val));
  1692. }
  1693. template<typename BasicJsonType, typename CompatibleNumberUnsignedType,
  1694. enable_if_t<is_compatible_integer_type<typename BasicJsonType::number_unsigned_t, CompatibleNumberUnsignedType>::value, int> = 0>
  1695. void to_json(BasicJsonType& j, CompatibleNumberUnsignedType val) noexcept
  1696. {
  1697. external_constructor<value_t::number_unsigned>::construct(j, static_cast<typename BasicJsonType::number_unsigned_t>(val));
  1698. }
  1699. template<typename BasicJsonType, typename CompatibleNumberIntegerType,
  1700. enable_if_t<is_compatible_integer_type<typename BasicJsonType::number_integer_t, CompatibleNumberIntegerType>::value, int> = 0>
  1701. void to_json(BasicJsonType& j, CompatibleNumberIntegerType val) noexcept
  1702. {
  1703. external_constructor<value_t::number_integer>::construct(j, static_cast<typename BasicJsonType::number_integer_t>(val));
  1704. }
  1705. template<typename BasicJsonType, typename EnumType,
  1706. enable_if_t<std::is_enum<EnumType>::value, int> = 0>
  1707. void to_json(BasicJsonType& j, EnumType e) noexcept
  1708. {
  1709. using underlying_type = typename std::underlying_type<EnumType>::type;
  1710. external_constructor<value_t::number_integer>::construct(j, static_cast<underlying_type>(e));
  1711. }
  1712. template<typename BasicJsonType>
  1713. void to_json(BasicJsonType& j, const std::vector<bool>& e)
  1714. {
  1715. external_constructor<value_t::array>::construct(j, e);
  1716. }
  1717. template <typename BasicJsonType, typename CompatibleArrayType,
  1718. enable_if_t<is_compatible_array_type<BasicJsonType,
  1719. CompatibleArrayType>::value and
  1720. not is_compatible_object_type<
  1721. BasicJsonType, CompatibleArrayType>::value and
  1722. not is_compatible_string_type<BasicJsonType, CompatibleArrayType>::value and
  1723. not is_basic_json<CompatibleArrayType>::value,
  1724. int> = 0>
  1725. void to_json(BasicJsonType& j, const CompatibleArrayType& arr)
  1726. {
  1727. external_constructor<value_t::array>::construct(j, arr);
  1728. }
  1729. template<typename BasicJsonType, typename T,
  1730. enable_if_t<std::is_convertible<T, BasicJsonType>::value, int> = 0>
  1731. void to_json(BasicJsonType& j, const std::valarray<T>& arr)
  1732. {
  1733. external_constructor<value_t::array>::construct(j, std::move(arr));
  1734. }
  1735. template<typename BasicJsonType>
  1736. void to_json(BasicJsonType& j, typename BasicJsonType::array_t&& arr)
  1737. {
  1738. external_constructor<value_t::array>::construct(j, std::move(arr));
  1739. }
  1740. template<typename BasicJsonType, typename CompatibleObjectType,
  1741. enable_if_t<is_compatible_object_type<BasicJsonType, CompatibleObjectType>::value and not is_basic_json<CompatibleObjectType>::value, int> = 0>
  1742. void to_json(BasicJsonType& j, const CompatibleObjectType& obj)
  1743. {
  1744. external_constructor<value_t::object>::construct(j, obj);
  1745. }
  1746. template<typename BasicJsonType>
  1747. void to_json(BasicJsonType& j, typename BasicJsonType::object_t&& obj)
  1748. {
  1749. external_constructor<value_t::object>::construct(j, std::move(obj));
  1750. }
  1751. template <
  1752. typename BasicJsonType, typename T, std::size_t N,
  1753. enable_if_t<not std::is_constructible<typename BasicJsonType::string_t,
  1754. const T(&)[N]>::value,
  1755. int> = 0 >
  1756. void to_json(BasicJsonType& j, const T(&arr)[N])
  1757. {
  1758. external_constructor<value_t::array>::construct(j, arr);
  1759. }
  1760. template<typename BasicJsonType, typename... Args>
  1761. void to_json(BasicJsonType& j, const std::pair<Args...>& p)
  1762. {
  1763. j = { p.first, p.second };
  1764. }
  1765. // for https://github.com/nlohmann/json/pull/1134
  1766. template < typename BasicJsonType, typename T,
  1767. enable_if_t<std::is_same<T, iteration_proxy_value<typename BasicJsonType::iterator>>::value, int> = 0>
  1768. void to_json(BasicJsonType& j, const T& b)
  1769. {
  1770. j = { {b.key(), b.value()} };
  1771. }
  1772. template<typename BasicJsonType, typename Tuple, std::size_t... Idx>
  1773. void to_json_tuple_impl(BasicJsonType& j, const Tuple& t, index_sequence<Idx...> /*unused*/)
  1774. {
  1775. j = { std::get<Idx>(t)... };
  1776. }
  1777. template<typename BasicJsonType, typename... Args>
  1778. void to_json(BasicJsonType& j, const std::tuple<Args...>& t)
  1779. {
  1780. to_json_tuple_impl(j, t, index_sequence_for<Args...> {});
  1781. }
  1782. struct to_json_fn
  1783. {
  1784. template<typename BasicJsonType, typename T>
  1785. auto operator()(BasicJsonType& j, T&& val) const noexcept(noexcept(to_json(j, std::forward<T>(val))))
  1786. -> decltype(to_json(j, std::forward<T>(val)), void())
  1787. {
  1788. return to_json(j, std::forward<T>(val));
  1789. }
  1790. };
  1791. } // namespace detail
  1792. /// namespace to hold default `to_json` function
  1793. namespace
  1794. {
  1795. constexpr const auto& to_json = detail::static_const<detail::to_json_fn>::value;
  1796. } // namespace
  1797. } // namespace nlohmann
  1798. // #include <nlohmann/detail/input/input_adapters.hpp>
  1799. #include <cassert> // assert
  1800. #include <cstddef> // size_t
  1801. #include <cstring> // strlen
  1802. #include <istream> // istream
  1803. #include <iterator> // begin, end, iterator_traits, random_access_iterator_tag, distance, next
  1804. #include <memory> // shared_ptr, make_shared, addressof
  1805. #include <numeric> // accumulate
  1806. #include <string> // string, char_traits
  1807. #include <type_traits> // enable_if, is_base_of, is_pointer, is_integral, remove_pointer
  1808. #include <utility> // pair, declval
  1809. #include <cstdio> //FILE *
  1810. // #include <nlohmann/detail/macro_scope.hpp>
  1811. namespace nlohmann
  1812. {
  1813. namespace detail
  1814. {
  1815. /// the supported input formats
  1816. enum class input_format_t { json, cbor, msgpack, ubjson, bson };
  1817. ////////////////////
  1818. // input adapters //
  1819. ////////////////////
  1820. /*!
  1821. @brief abstract input adapter interface
  1822. Produces a stream of std::char_traits<char>::int_type characters from a
  1823. std::istream, a buffer, or some other input type. Accepts the return of
  1824. exactly one non-EOF character for future input. The int_type characters
  1825. returned consist of all valid char values as positive values (typically
  1826. unsigned char), plus an EOF value outside that range, specified by the value
  1827. of the function std::char_traits<char>::eof(). This value is typically -1, but
  1828. could be any arbitrary value which is not a valid char value.
  1829. */
  1830. struct input_adapter_protocol
  1831. {
  1832. /// get a character [0,255] or std::char_traits<char>::eof().
  1833. virtual std::char_traits<char>::int_type get_character() = 0;
  1834. virtual ~input_adapter_protocol() = default;
  1835. };
  1836. /// a type to simplify interfaces
  1837. using input_adapter_t = std::shared_ptr<input_adapter_protocol>;
  1838. /*!
  1839. Input adapter for stdio file access. This adapter read only 1 byte and do not use any
  1840. buffer. This adapter is a very low level adapter.
  1841. */
  1842. class file_input_adapter : public input_adapter_protocol
  1843. {
  1844. public:
  1845. explicit file_input_adapter(std::FILE* f) noexcept
  1846. : m_file(f)
  1847. {}
  1848. std::char_traits<char>::int_type get_character() noexcept override
  1849. {
  1850. return std::fgetc(m_file);
  1851. }
  1852. private:
  1853. /// the file pointer to read from
  1854. std::FILE* m_file;
  1855. };
  1856. /*!
  1857. Input adapter for a (caching) istream. Ignores a UFT Byte Order Mark at
  1858. beginning of input. Does not support changing the underlying std::streambuf
  1859. in mid-input. Maintains underlying std::istream and std::streambuf to support
  1860. subsequent use of standard std::istream operations to process any input
  1861. characters following those used in parsing the JSON input. Clears the
  1862. std::istream flags; any input errors (e.g., EOF) will be detected by the first
  1863. subsequent call for input from the std::istream.
  1864. */
  1865. class input_stream_adapter : public input_adapter_protocol
  1866. {
  1867. public:
  1868. ~input_stream_adapter() override
  1869. {
  1870. // clear stream flags; we use underlying streambuf I/O, do not
  1871. // maintain ifstream flags, except eof
  1872. is.clear(is.rdstate() & std::ios::eofbit);
  1873. }
  1874. explicit input_stream_adapter(std::istream& i)
  1875. : is(i), sb(*i.rdbuf())
  1876. {}
  1877. // delete because of pointer members
  1878. input_stream_adapter(const input_stream_adapter&) = delete;
  1879. input_stream_adapter& operator=(input_stream_adapter&) = delete;
  1880. input_stream_adapter(input_stream_adapter&&) = delete;
  1881. input_stream_adapter& operator=(input_stream_adapter&&) = delete;
  1882. // std::istream/std::streambuf use std::char_traits<char>::to_int_type, to
  1883. // ensure that std::char_traits<char>::eof() and the character 0xFF do not
  1884. // end up as the same value, eg. 0xFFFFFFFF.
  1885. std::char_traits<char>::int_type get_character() override
  1886. {
  1887. auto res = sb.sbumpc();
  1888. // set eof manually, as we don't use the istream interface.
  1889. if (res == EOF)
  1890. {
  1891. is.clear(is.rdstate() | std::ios::eofbit);
  1892. }
  1893. return res;
  1894. }
  1895. private:
  1896. /// the associated input stream
  1897. std::istream& is;
  1898. std::streambuf& sb;
  1899. };
  1900. /// input adapter for buffer input
  1901. class input_buffer_adapter : public input_adapter_protocol
  1902. {
  1903. public:
  1904. input_buffer_adapter(const char* b, const std::size_t l) noexcept
  1905. : cursor(b), limit(b + l)
  1906. {}
  1907. // delete because of pointer members
  1908. input_buffer_adapter(const input_buffer_adapter&) = delete;
  1909. input_buffer_adapter& operator=(input_buffer_adapter&) = delete;
  1910. input_buffer_adapter(input_buffer_adapter&&) = delete;
  1911. input_buffer_adapter& operator=(input_buffer_adapter&&) = delete;
  1912. ~input_buffer_adapter() override = default;
  1913. std::char_traits<char>::int_type get_character() noexcept override
  1914. {
  1915. if (JSON_LIKELY(cursor < limit))
  1916. {
  1917. return std::char_traits<char>::to_int_type(*(cursor++));
  1918. }
  1919. return std::char_traits<char>::eof();
  1920. }
  1921. private:
  1922. /// pointer to the current character
  1923. const char* cursor;
  1924. /// pointer past the last character
  1925. const char* const limit;
  1926. };
  1927. template<typename WideStringType, size_t T>
  1928. struct wide_string_input_helper
  1929. {
  1930. // UTF-32
  1931. static void fill_buffer(const WideStringType& str, size_t& current_wchar, std::array<std::char_traits<char>::int_type, 4>& utf8_bytes, size_t& utf8_bytes_index, size_t& utf8_bytes_filled)
  1932. {
  1933. utf8_bytes_index = 0;
  1934. if (current_wchar == str.size())
  1935. {
  1936. utf8_bytes[0] = std::char_traits<char>::eof();
  1937. utf8_bytes_filled = 1;
  1938. }
  1939. else
  1940. {
  1941. // get the current character
  1942. const auto wc = static_cast<int>(str[current_wchar++]);
  1943. // UTF-32 to UTF-8 encoding
  1944. if (wc < 0x80)
  1945. {
  1946. utf8_bytes[0] = wc;
  1947. utf8_bytes_filled = 1;
  1948. }
  1949. else if (wc <= 0x7FF)
  1950. {
  1951. utf8_bytes[0] = 0xC0 | ((wc >> 6) & 0x1F);
  1952. utf8_bytes[1] = 0x80 | (wc & 0x3F);
  1953. utf8_bytes_filled = 2;
  1954. }
  1955. else if (wc <= 0xFFFF)
  1956. {
  1957. utf8_bytes[0] = 0xE0 | ((wc >> 12) & 0x0F);
  1958. utf8_bytes[1] = 0x80 | ((wc >> 6) & 0x3F);
  1959. utf8_bytes[2] = 0x80 | (wc & 0x3F);
  1960. utf8_bytes_filled = 3;
  1961. }
  1962. else if (wc <= 0x10FFFF)
  1963. {
  1964. utf8_bytes[0] = 0xF0 | ((wc >> 18) & 0x07);
  1965. utf8_bytes[1] = 0x80 | ((wc >> 12) & 0x3F);
  1966. utf8_bytes[2] = 0x80 | ((wc >> 6) & 0x3F);
  1967. utf8_bytes[3] = 0x80 | (wc & 0x3F);
  1968. utf8_bytes_filled = 4;
  1969. }
  1970. else
  1971. {
  1972. // unknown character
  1973. utf8_bytes[0] = wc;
  1974. utf8_bytes_filled = 1;
  1975. }
  1976. }
  1977. }
  1978. };
  1979. template<typename WideStringType>
  1980. struct wide_string_input_helper<WideStringType, 2>
  1981. {
  1982. // UTF-16
  1983. static void fill_buffer(const WideStringType& str, size_t& current_wchar, std::array<std::char_traits<char>::int_type, 4>& utf8_bytes, size_t& utf8_bytes_index, size_t& utf8_bytes_filled)
  1984. {
  1985. utf8_bytes_index = 0;
  1986. if (current_wchar == str.size())
  1987. {
  1988. utf8_bytes[0] = std::char_traits<char>::eof();
  1989. utf8_bytes_filled = 1;
  1990. }
  1991. else
  1992. {
  1993. // get the current character
  1994. const auto wc = static_cast<int>(str[current_wchar++]);
  1995. // UTF-16 to UTF-8 encoding
  1996. if (wc < 0x80)
  1997. {
  1998. utf8_bytes[0] = wc;
  1999. utf8_bytes_filled = 1;
  2000. }
  2001. else if (wc <= 0x7FF)
  2002. {
  2003. utf8_bytes[0] = 0xC0 | ((wc >> 6));
  2004. utf8_bytes[1] = 0x80 | (wc & 0x3F);
  2005. utf8_bytes_filled = 2;
  2006. }
  2007. else if (0xD800 > wc or wc >= 0xE000)
  2008. {
  2009. utf8_bytes[0] = 0xE0 | ((wc >> 12));
  2010. utf8_bytes[1] = 0x80 | ((wc >> 6) & 0x3F);
  2011. utf8_bytes[2] = 0x80 | (wc & 0x3F);
  2012. utf8_bytes_filled = 3;
  2013. }
  2014. else
  2015. {
  2016. if (current_wchar < str.size())
  2017. {
  2018. const auto wc2 = static_cast<int>(str[current_wchar++]);
  2019. const int charcode = 0x10000 + (((wc & 0x3FF) << 10) | (wc2 & 0x3FF));
  2020. utf8_bytes[0] = 0xf0 | (charcode >> 18);
  2021. utf8_bytes[1] = 0x80 | ((charcode >> 12) & 0x3F);
  2022. utf8_bytes[2] = 0x80 | ((charcode >> 6) & 0x3F);
  2023. utf8_bytes[3] = 0x80 | (charcode & 0x3F);
  2024. utf8_bytes_filled = 4;
  2025. }
  2026. else
  2027. {
  2028. // unknown character
  2029. ++current_wchar;
  2030. utf8_bytes[0] = wc;
  2031. utf8_bytes_filled = 1;
  2032. }
  2033. }
  2034. }
  2035. }
  2036. };
  2037. template<typename WideStringType>
  2038. class wide_string_input_adapter : public input_adapter_protocol
  2039. {
  2040. public:
  2041. explicit wide_string_input_adapter(const WideStringType& w) noexcept
  2042. : str(w)
  2043. {}
  2044. std::char_traits<char>::int_type get_character() noexcept override
  2045. {
  2046. // check if buffer needs to be filled
  2047. if (utf8_bytes_index == utf8_bytes_filled)
  2048. {
  2049. fill_buffer<sizeof(typename WideStringType::value_type)>();
  2050. assert(utf8_bytes_filled > 0);
  2051. assert(utf8_bytes_index == 0);
  2052. }
  2053. // use buffer
  2054. assert(utf8_bytes_filled > 0);
  2055. assert(utf8_bytes_index < utf8_bytes_filled);
  2056. return utf8_bytes[utf8_bytes_index++];
  2057. }
  2058. private:
  2059. template<size_t T>
  2060. void fill_buffer()
  2061. {
  2062. wide_string_input_helper<WideStringType, T>::fill_buffer(str, current_wchar, utf8_bytes, utf8_bytes_index, utf8_bytes_filled);
  2063. }
  2064. /// the wstring to process
  2065. const WideStringType& str;
  2066. /// index of the current wchar in str
  2067. std::size_t current_wchar = 0;
  2068. /// a buffer for UTF-8 bytes
  2069. std::array<std::char_traits<char>::int_type, 4> utf8_bytes = {{0, 0, 0, 0}};
  2070. /// index to the utf8_codes array for the next valid byte
  2071. std::size_t utf8_bytes_index = 0;
  2072. /// number of valid bytes in the utf8_codes array
  2073. std::size_t utf8_bytes_filled = 0;
  2074. };
  2075. class input_adapter
  2076. {
  2077. public:
  2078. // native support
  2079. input_adapter(std::FILE* file)
  2080. : ia(std::make_shared<file_input_adapter>(file)) {}
  2081. /// input adapter for input stream
  2082. input_adapter(std::istream& i)
  2083. : ia(std::make_shared<input_stream_adapter>(i)) {}
  2084. /// input adapter for input stream
  2085. input_adapter(std::istream&& i)
  2086. : ia(std::make_shared<input_stream_adapter>(i)) {}
  2087. input_adapter(const std::wstring& ws)
  2088. : ia(std::make_shared<wide_string_input_adapter<std::wstring>>(ws)) {}
  2089. input_adapter(const std::u16string& ws)
  2090. : ia(std::make_shared<wide_string_input_adapter<std::u16string>>(ws)) {}
  2091. input_adapter(const std::u32string& ws)
  2092. : ia(std::make_shared<wide_string_input_adapter<std::u32string>>(ws)) {}
  2093. /// input adapter for buffer
  2094. template<typename CharT,
  2095. typename std::enable_if<
  2096. std::is_pointer<CharT>::value and
  2097. std::is_integral<typename std::remove_pointer<CharT>::type>::value and
  2098. sizeof(typename std::remove_pointer<CharT>::type) == 1,
  2099. int>::type = 0>
  2100. input_adapter(CharT b, std::size_t l)
  2101. : ia(std::make_shared<input_buffer_adapter>(reinterpret_cast<const char*>(b), l)) {}
  2102. // derived support
  2103. /// input adapter for string literal
  2104. template<typename CharT,
  2105. typename std::enable_if<
  2106. std::is_pointer<CharT>::value and
  2107. std::is_integral<typename std::remove_pointer<CharT>::type>::value and
  2108. sizeof(typename std::remove_pointer<CharT>::type) == 1,
  2109. int>::type = 0>
  2110. input_adapter(CharT b)
  2111. : input_adapter(reinterpret_cast<const char*>(b),
  2112. std::strlen(reinterpret_cast<const char*>(b))) {}
  2113. /// input adapter for iterator range with contiguous storage
  2114. template<class IteratorType,
  2115. typename std::enable_if<
  2116. std::is_same<typename iterator_traits<IteratorType>::iterator_category, std::random_access_iterator_tag>::value,
  2117. int>::type = 0>
  2118. input_adapter(IteratorType first, IteratorType last)
  2119. {
  2120. #ifndef NDEBUG
  2121. // assertion to check that the iterator range is indeed contiguous,
  2122. // see http://stackoverflow.com/a/35008842/266378 for more discussion
  2123. const auto is_contiguous = std::accumulate(
  2124. first, last, std::pair<bool, int>(true, 0),
  2125. [&first](std::pair<bool, int> res, decltype(*first) val)
  2126. {
  2127. res.first &= (val == *(std::next(std::addressof(*first), res.second++)));
  2128. return res;
  2129. }).first;
  2130. assert(is_contiguous);
  2131. #endif
  2132. // assertion to check that each element is 1 byte long
  2133. static_assert(
  2134. sizeof(typename iterator_traits<IteratorType>::value_type) == 1,
  2135. "each element in the iterator range must have the size of 1 byte");
  2136. const auto len = static_cast<size_t>(std::distance(first, last));
  2137. if (JSON_LIKELY(len > 0))
  2138. {
  2139. // there is at least one element: use the address of first
  2140. ia = std::make_shared<input_buffer_adapter>(reinterpret_cast<const char*>(&(*first)), len);
  2141. }
  2142. else
  2143. {
  2144. // the address of first cannot be used: use nullptr
  2145. ia = std::make_shared<input_buffer_adapter>(nullptr, len);
  2146. }
  2147. }
  2148. /// input adapter for array
  2149. template<class T, std::size_t N>
  2150. input_adapter(T (&array)[N])
  2151. : input_adapter(std::begin(array), std::end(array)) {}
  2152. /// input adapter for contiguous container
  2153. template<class ContiguousContainer, typename
  2154. std::enable_if<not std::is_pointer<ContiguousContainer>::value and
  2155. std::is_base_of<std::random_access_iterator_tag, typename iterator_traits<decltype(std::begin(std::declval<ContiguousContainer const>()))>::iterator_category>::value,
  2156. int>::type = 0>
  2157. input_adapter(const ContiguousContainer& c)
  2158. : input_adapter(std::begin(c), std::end(c)) {}
  2159. operator input_adapter_t()
  2160. {
  2161. return ia;
  2162. }
  2163. private:
  2164. /// the actual adapter
  2165. input_adapter_t ia = nullptr;
  2166. };
  2167. } // namespace detail
  2168. } // namespace nlohmann
  2169. // #include <nlohmann/detail/input/lexer.hpp>
  2170. #include <clocale> // localeconv
  2171. #include <cstddef> // size_t
  2172. #include <cstdlib> // strtof, strtod, strtold, strtoll, strtoull
  2173. #include <cstdio> // snprintf
  2174. #include <initializer_list> // initializer_list
  2175. #include <string> // char_traits, string
  2176. #include <vector> // vector
  2177. // #include <nlohmann/detail/macro_scope.hpp>
  2178. // #include <nlohmann/detail/input/input_adapters.hpp>
  2179. // #include <nlohmann/detail/input/position_t.hpp>
  2180. namespace nlohmann
  2181. {
  2182. namespace detail
  2183. {
  2184. ///////////
  2185. // lexer //
  2186. ///////////
  2187. /*!
  2188. @brief lexical analysis
  2189. This class organizes the lexical analysis during JSON deserialization.
  2190. */
  2191. template<typename BasicJsonType>
  2192. class lexer
  2193. {
  2194. using number_integer_t = typename BasicJsonType::number_integer_t;
  2195. using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
  2196. using number_float_t = typename BasicJsonType::number_float_t;
  2197. using string_t = typename BasicJsonType::string_t;
  2198. public:
  2199. /// token types for the parser
  2200. enum class token_type
  2201. {
  2202. uninitialized, ///< indicating the scanner is uninitialized
  2203. literal_true, ///< the `true` literal
  2204. literal_false, ///< the `false` literal
  2205. literal_null, ///< the `null` literal
  2206. value_string, ///< a string -- use get_string() for actual value
  2207. value_unsigned, ///< an unsigned integer -- use get_number_unsigned() for actual value
  2208. value_integer, ///< a signed integer -- use get_number_integer() for actual value
  2209. value_float, ///< an floating point number -- use get_number_float() for actual value
  2210. begin_array, ///< the character for array begin `[`
  2211. begin_object, ///< the character for object begin `{`
  2212. end_array, ///< the character for array end `]`
  2213. end_object, ///< the character for object end `}`
  2214. name_separator, ///< the name separator `:`
  2215. value_separator, ///< the value separator `,`
  2216. parse_error, ///< indicating a parse error
  2217. end_of_input, ///< indicating the end of the input buffer
  2218. literal_or_value ///< a literal or the begin of a value (only for diagnostics)
  2219. };
  2220. /// return name of values of type token_type (only used for errors)
  2221. static const char* token_type_name(const token_type t) noexcept
  2222. {
  2223. switch (t)
  2224. {
  2225. case token_type::uninitialized:
  2226. return "<uninitialized>";
  2227. case token_type::literal_true:
  2228. return "true literal";
  2229. case token_type::literal_false:
  2230. return "false literal";
  2231. case token_type::literal_null:
  2232. return "null literal";
  2233. case token_type::value_string:
  2234. return "string literal";
  2235. case lexer::token_type::value_unsigned:
  2236. case lexer::token_type::value_integer:
  2237. case lexer::token_type::value_float:
  2238. return "number literal";
  2239. case token_type::begin_array:
  2240. return "'['";
  2241. case token_type::begin_object:
  2242. return "'{'";
  2243. case token_type::end_array:
  2244. return "']'";
  2245. case token_type::end_object:
  2246. return "'}'";
  2247. case token_type::name_separator:
  2248. return "':'";
  2249. case token_type::value_separator:
  2250. return "','";
  2251. case token_type::parse_error:
  2252. return "<parse error>";
  2253. case token_type::end_of_input:
  2254. return "end of input";
  2255. case token_type::literal_or_value:
  2256. return "'[', '{', or a literal";
  2257. // LCOV_EXCL_START
  2258. default: // catch non-enum values
  2259. return "unknown token";
  2260. // LCOV_EXCL_STOP
  2261. }
  2262. }
  2263. explicit lexer(detail::input_adapter_t&& adapter)
  2264. : ia(std::move(adapter)), decimal_point_char(get_decimal_point()) {}
  2265. // delete because of pointer members
  2266. lexer(const lexer&) = delete;
  2267. lexer(lexer&&) = delete;
  2268. lexer& operator=(lexer&) = delete;
  2269. lexer& operator=(lexer&&) = delete;
  2270. ~lexer() = default;
  2271. private:
  2272. /////////////////////
  2273. // locales
  2274. /////////////////////
  2275. /// return the locale-dependent decimal point
  2276. static char get_decimal_point() noexcept
  2277. {
  2278. const auto loc = localeconv();
  2279. assert(loc != nullptr);
  2280. return (loc->decimal_point == nullptr) ? '.' : *(loc->decimal_point);
  2281. }
  2282. /////////////////////
  2283. // scan functions
  2284. /////////////////////
  2285. /*!
  2286. @brief get codepoint from 4 hex characters following `\u`
  2287. For input "\u c1 c2 c3 c4" the codepoint is:
  2288. (c1 * 0x1000) + (c2 * 0x0100) + (c3 * 0x0010) + c4
  2289. = (c1 << 12) + (c2 << 8) + (c3 << 4) + (c4 << 0)
  2290. Furthermore, the possible characters '0'..'9', 'A'..'F', and 'a'..'f'
  2291. must be converted to the integers 0x0..0x9, 0xA..0xF, 0xA..0xF, resp. The
  2292. conversion is done by subtracting the offset (0x30, 0x37, and 0x57)
  2293. between the ASCII value of the character and the desired integer value.
  2294. @return codepoint (0x0000..0xFFFF) or -1 in case of an error (e.g. EOF or
  2295. non-hex character)
  2296. */
  2297. int get_codepoint()
  2298. {
  2299. // this function only makes sense after reading `\u`
  2300. assert(current == 'u');
  2301. int codepoint = 0;
  2302. const auto factors = { 12, 8, 4, 0 };
  2303. for (const auto factor : factors)
  2304. {
  2305. get();
  2306. if (current >= '0' and current <= '9')
  2307. {
  2308. codepoint += ((current - 0x30) << factor);
  2309. }
  2310. else if (current >= 'A' and current <= 'F')
  2311. {
  2312. codepoint += ((current - 0x37) << factor);
  2313. }
  2314. else if (current >= 'a' and current <= 'f')
  2315. {
  2316. codepoint += ((current - 0x57) << factor);
  2317. }
  2318. else
  2319. {
  2320. return -1;
  2321. }
  2322. }
  2323. assert(0x0000 <= codepoint and codepoint <= 0xFFFF);
  2324. return codepoint;
  2325. }
  2326. /*!
  2327. @brief check if the next byte(s) are inside a given range
  2328. Adds the current byte and, for each passed range, reads a new byte and
  2329. checks if it is inside the range. If a violation was detected, set up an
  2330. error message and return false. Otherwise, return true.
  2331. @param[in] ranges list of integers; interpreted as list of pairs of
  2332. inclusive lower and upper bound, respectively
  2333. @pre The passed list @a ranges must have 2, 4, or 6 elements; that is,
  2334. 1, 2, or 3 pairs. This precondition is enforced by an assertion.
  2335. @return true if and only if no range violation was detected
  2336. */
  2337. bool next_byte_in_range(std::initializer_list<int> ranges)
  2338. {
  2339. assert(ranges.size() == 2 or ranges.size() == 4 or ranges.size() == 6);
  2340. add(current);
  2341. for (auto range = ranges.begin(); range != ranges.end(); ++range)
  2342. {
  2343. get();
  2344. if (JSON_LIKELY(*range <= current and current <= *(++range)))
  2345. {
  2346. add(current);
  2347. }
  2348. else
  2349. {
  2350. error_message = "invalid string: ill-formed UTF-8 byte";
  2351. return false;
  2352. }
  2353. }
  2354. return true;
  2355. }
  2356. /*!
  2357. @brief scan a string literal
  2358. This function scans a string according to Sect. 7 of RFC 7159. While
  2359. scanning, bytes are escaped and copied into buffer token_buffer. Then the
  2360. function returns successfully, token_buffer is *not* null-terminated (as it
  2361. may contain \0 bytes), and token_buffer.size() is the number of bytes in the
  2362. string.
  2363. @return token_type::value_string if string could be successfully scanned,
  2364. token_type::parse_error otherwise
  2365. @note In case of errors, variable error_message contains a textual
  2366. description.
  2367. */
  2368. token_type scan_string()
  2369. {
  2370. // reset token_buffer (ignore opening quote)
  2371. reset();
  2372. // we entered the function by reading an open quote
  2373. assert(current == '\"');
  2374. while (true)
  2375. {
  2376. // get next character
  2377. switch (get())
  2378. {
  2379. // end of file while parsing string
  2380. case std::char_traits<char>::eof():
  2381. {
  2382. error_message = "invalid string: missing closing quote";
  2383. return token_type::parse_error;
  2384. }
  2385. // closing quote
  2386. case '\"':
  2387. {
  2388. return token_type::value_string;
  2389. }
  2390. // escapes
  2391. case '\\':
  2392. {
  2393. switch (get())
  2394. {
  2395. // quotation mark
  2396. case '\"':
  2397. add('\"');
  2398. break;
  2399. // reverse solidus
  2400. case '\\':
  2401. add('\\');
  2402. break;
  2403. // solidus
  2404. case '/':
  2405. add('/');
  2406. break;
  2407. // backspace
  2408. case 'b':
  2409. add('\b');
  2410. break;
  2411. // form feed
  2412. case 'f':
  2413. add('\f');
  2414. break;
  2415. // line feed
  2416. case 'n':
  2417. add('\n');
  2418. break;
  2419. // carriage return
  2420. case 'r':
  2421. add('\r');
  2422. break;
  2423. // tab
  2424. case 't':
  2425. add('\t');
  2426. break;
  2427. // unicode escapes
  2428. case 'u':
  2429. {
  2430. const int codepoint1 = get_codepoint();
  2431. int codepoint = codepoint1; // start with codepoint1
  2432. if (JSON_UNLIKELY(codepoint1 == -1))
  2433. {
  2434. error_message = "invalid string: '\\u' must be followed by 4 hex digits";
  2435. return token_type::parse_error;
  2436. }
  2437. // check if code point is a high surrogate
  2438. if (0xD800 <= codepoint1 and codepoint1 <= 0xDBFF)
  2439. {
  2440. // expect next \uxxxx entry
  2441. if (JSON_LIKELY(get() == '\\' and get() == 'u'))
  2442. {
  2443. const int codepoint2 = get_codepoint();
  2444. if (JSON_UNLIKELY(codepoint2 == -1))
  2445. {
  2446. error_message = "invalid string: '\\u' must be followed by 4 hex digits";
  2447. return token_type::parse_error;
  2448. }
  2449. // check if codepoint2 is a low surrogate
  2450. if (JSON_LIKELY(0xDC00 <= codepoint2 and codepoint2 <= 0xDFFF))
  2451. {
  2452. // overwrite codepoint
  2453. codepoint =
  2454. // high surrogate occupies the most significant 22 bits
  2455. (codepoint1 << 10)
  2456. // low surrogate occupies the least significant 15 bits
  2457. + codepoint2
  2458. // there is still the 0xD800, 0xDC00 and 0x10000 noise
  2459. // in the result so we have to subtract with:
  2460. // (0xD800 << 10) + DC00 - 0x10000 = 0x35FDC00
  2461. - 0x35FDC00;
  2462. }
  2463. else
  2464. {
  2465. error_message = "invalid string: surrogate U+DC00..U+DFFF must be followed by U+DC00..U+DFFF";
  2466. return token_type::parse_error;
  2467. }
  2468. }
  2469. else
  2470. {
  2471. error_message = "invalid string: surrogate U+DC00..U+DFFF must be followed by U+DC00..U+DFFF";
  2472. return token_type::parse_error;
  2473. }
  2474. }
  2475. else
  2476. {
  2477. if (JSON_UNLIKELY(0xDC00 <= codepoint1 and codepoint1 <= 0xDFFF))
  2478. {
  2479. error_message = "invalid string: surrogate U+DC00..U+DFFF must follow U+D800..U+DBFF";
  2480. return token_type::parse_error;
  2481. }
  2482. }
  2483. // result of the above calculation yields a proper codepoint
  2484. assert(0x00 <= codepoint and codepoint <= 0x10FFFF);
  2485. // translate codepoint into bytes
  2486. if (codepoint < 0x80)
  2487. {
  2488. // 1-byte characters: 0xxxxxxx (ASCII)
  2489. add(codepoint);
  2490. }
  2491. else if (codepoint <= 0x7FF)
  2492. {
  2493. // 2-byte characters: 110xxxxx 10xxxxxx
  2494. add(0xC0 | (codepoint >> 6));
  2495. add(0x80 | (codepoint & 0x3F));
  2496. }
  2497. else if (codepoint <= 0xFFFF)
  2498. {
  2499. // 3-byte characters: 1110xxxx 10xxxxxx 10xxxxxx
  2500. add(0xE0 | (codepoint >> 12));
  2501. add(0x80 | ((codepoint >> 6) & 0x3F));
  2502. add(0x80 | (codepoint & 0x3F));
  2503. }
  2504. else
  2505. {
  2506. // 4-byte characters: 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
  2507. add(0xF0 | (codepoint >> 18));
  2508. add(0x80 | ((codepoint >> 12) & 0x3F));
  2509. add(0x80 | ((codepoint >> 6) & 0x3F));
  2510. add(0x80 | (codepoint & 0x3F));
  2511. }
  2512. break;
  2513. }
  2514. // other characters after escape
  2515. default:
  2516. error_message = "invalid string: forbidden character after backslash";
  2517. return token_type::parse_error;
  2518. }
  2519. break;
  2520. }
  2521. // invalid control characters
  2522. case 0x00:
  2523. {
  2524. error_message = "invalid string: control character U+0000 (NUL) must be escaped to \\u0000";
  2525. return token_type::parse_error;
  2526. }
  2527. case 0x01:
  2528. {
  2529. error_message = "invalid string: control character U+0001 (SOH) must be escaped to \\u0001";
  2530. return token_type::parse_error;
  2531. }
  2532. case 0x02:
  2533. {
  2534. error_message = "invalid string: control character U+0002 (STX) must be escaped to \\u0002";
  2535. return token_type::parse_error;
  2536. }
  2537. case 0x03:
  2538. {
  2539. error_message = "invalid string: control character U+0003 (ETX) must be escaped to \\u0003";
  2540. return token_type::parse_error;
  2541. }
  2542. case 0x04:
  2543. {
  2544. error_message = "invalid string: control character U+0004 (EOT) must be escaped to \\u0004";
  2545. return token_type::parse_error;
  2546. }
  2547. case 0x05:
  2548. {
  2549. error_message = "invalid string: control character U+0005 (ENQ) must be escaped to \\u0005";
  2550. return token_type::parse_error;
  2551. }
  2552. case 0x06:
  2553. {
  2554. error_message = "invalid string: control character U+0006 (ACK) must be escaped to \\u0006";
  2555. return token_type::parse_error;
  2556. }
  2557. case 0x07:
  2558. {
  2559. error_message = "invalid string: control character U+0007 (BEL) must be escaped to \\u0007";
  2560. return token_type::parse_error;
  2561. }
  2562. case 0x08:
  2563. {
  2564. error_message = "invalid string: control character U+0008 (BS) must be escaped to \\u0008 or \\b";
  2565. return token_type::parse_error;
  2566. }
  2567. case 0x09:
  2568. {
  2569. error_message = "invalid string: control character U+0009 (HT) must be escaped to \\u0009 or \\t";
  2570. return token_type::parse_error;
  2571. }
  2572. case 0x0A:
  2573. {
  2574. error_message = "invalid string: control character U+000A (LF) must be escaped to \\u000A or \\n";
  2575. return token_type::parse_error;
  2576. }
  2577. case 0x0B:
  2578. {
  2579. error_message = "invalid string: control character U+000B (VT) must be escaped to \\u000B";
  2580. return token_type::parse_error;
  2581. }
  2582. case 0x0C:
  2583. {
  2584. error_message = "invalid string: control character U+000C (FF) must be escaped to \\u000C or \\f";
  2585. return token_type::parse_error;
  2586. }
  2587. case 0x0D:
  2588. {
  2589. error_message = "invalid string: control character U+000D (CR) must be escaped to \\u000D or \\r";
  2590. return token_type::parse_error;
  2591. }
  2592. case 0x0E:
  2593. {
  2594. error_message = "invalid string: control character U+000E (SO) must be escaped to \\u000E";
  2595. return token_type::parse_error;
  2596. }
  2597. case 0x0F:
  2598. {
  2599. error_message = "invalid string: control character U+000F (SI) must be escaped to \\u000F";
  2600. return token_type::parse_error;
  2601. }
  2602. case 0x10:
  2603. {
  2604. error_message = "invalid string: control character U+0010 (DLE) must be escaped to \\u0010";
  2605. return token_type::parse_error;
  2606. }
  2607. case 0x11:
  2608. {
  2609. error_message = "invalid string: control character U+0011 (DC1) must be escaped to \\u0011";
  2610. return token_type::parse_error;
  2611. }
  2612. case 0x12:
  2613. {
  2614. error_message = "invalid string: control character U+0012 (DC2) must be escaped to \\u0012";
  2615. return token_type::parse_error;
  2616. }
  2617. case 0x13:
  2618. {
  2619. error_message = "invalid string: control character U+0013 (DC3) must be escaped to \\u0013";
  2620. return token_type::parse_error;
  2621. }
  2622. case 0x14:
  2623. {
  2624. error_message = "invalid string: control character U+0014 (DC4) must be escaped to \\u0014";
  2625. return token_type::parse_error;
  2626. }
  2627. case 0x15:
  2628. {
  2629. error_message = "invalid string: control character U+0015 (NAK) must be escaped to \\u0015";
  2630. return token_type::parse_error;
  2631. }
  2632. case 0x16:
  2633. {
  2634. error_message = "invalid string: control character U+0016 (SYN) must be escaped to \\u0016";
  2635. return token_type::parse_error;
  2636. }
  2637. case 0x17:
  2638. {
  2639. error_message = "invalid string: control character U+0017 (ETB) must be escaped to \\u0017";
  2640. return token_type::parse_error;
  2641. }
  2642. case 0x18:
  2643. {
  2644. error_message = "invalid string: control character U+0018 (CAN) must be escaped to \\u0018";
  2645. return token_type::parse_error;
  2646. }
  2647. case 0x19:
  2648. {
  2649. error_message = "invalid string: control character U+0019 (EM) must be escaped to \\u0019";
  2650. return token_type::parse_error;
  2651. }
  2652. case 0x1A:
  2653. {
  2654. error_message = "invalid string: control character U+001A (SUB) must be escaped to \\u001A";
  2655. return token_type::parse_error;
  2656. }
  2657. case 0x1B:
  2658. {
  2659. error_message = "invalid string: control character U+001B (ESC) must be escaped to \\u001B";
  2660. return token_type::parse_error;
  2661. }
  2662. case 0x1C:
  2663. {
  2664. error_message = "invalid string: control character U+001C (FS) must be escaped to \\u001C";
  2665. return token_type::parse_error;
  2666. }
  2667. case 0x1D:
  2668. {
  2669. error_message = "invalid string: control character U+001D (GS) must be escaped to \\u001D";
  2670. return token_type::parse_error;
  2671. }
  2672. case 0x1E:
  2673. {
  2674. error_message = "invalid string: control character U+001E (RS) must be escaped to \\u001E";
  2675. return token_type::parse_error;
  2676. }
  2677. case 0x1F:
  2678. {
  2679. error_message = "invalid string: control character U+001F (US) must be escaped to \\u001F";
  2680. return token_type::parse_error;
  2681. }
  2682. // U+0020..U+007F (except U+0022 (quote) and U+005C (backspace))
  2683. case 0x20:
  2684. case 0x21:
  2685. case 0x23:
  2686. case 0x24:
  2687. case 0x25:
  2688. case 0x26:
  2689. case 0x27:
  2690. case 0x28:
  2691. case 0x29:
  2692. case 0x2A:
  2693. case 0x2B:
  2694. case 0x2C:
  2695. case 0x2D:
  2696. case 0x2E:
  2697. case 0x2F:
  2698. case 0x30:
  2699. case 0x31:
  2700. case 0x32:
  2701. case 0x33:
  2702. case 0x34:
  2703. case 0x35:
  2704. case 0x36:
  2705. case 0x37:
  2706. case 0x38:
  2707. case 0x39:
  2708. case 0x3A:
  2709. case 0x3B:
  2710. case 0x3C:
  2711. case 0x3D:
  2712. case 0x3E:
  2713. case 0x3F:
  2714. case 0x40:
  2715. case 0x41:
  2716. case 0x42:
  2717. case 0x43:
  2718. case 0x44:
  2719. case 0x45:
  2720. case 0x46:
  2721. case 0x47:
  2722. case 0x48:
  2723. case 0x49:
  2724. case 0x4A:
  2725. case 0x4B:
  2726. case 0x4C:
  2727. case 0x4D:
  2728. case 0x4E:
  2729. case 0x4F:
  2730. case 0x50:
  2731. case 0x51:
  2732. case 0x52:
  2733. case 0x53:
  2734. case 0x54:
  2735. case 0x55:
  2736. case 0x56:
  2737. case 0x57:
  2738. case 0x58:
  2739. case 0x59:
  2740. case 0x5A:
  2741. case 0x5B:
  2742. case 0x5D:
  2743. case 0x5E:
  2744. case 0x5F:
  2745. case 0x60:
  2746. case 0x61:
  2747. case 0x62:
  2748. case 0x63:
  2749. case 0x64:
  2750. case 0x65:
  2751. case 0x66:
  2752. case 0x67:
  2753. case 0x68:
  2754. case 0x69:
  2755. case 0x6A:
  2756. case 0x6B:
  2757. case 0x6C:
  2758. case 0x6D:
  2759. case 0x6E:
  2760. case 0x6F:
  2761. case 0x70:
  2762. case 0x71:
  2763. case 0x72:
  2764. case 0x73:
  2765. case 0x74:
  2766. case 0x75:
  2767. case 0x76:
  2768. case 0x77:
  2769. case 0x78:
  2770. case 0x79:
  2771. case 0x7A:
  2772. case 0x7B:
  2773. case 0x7C:
  2774. case 0x7D:
  2775. case 0x7E:
  2776. case 0x7F:
  2777. {
  2778. add(current);
  2779. break;
  2780. }
  2781. // U+0080..U+07FF: bytes C2..DF 80..BF
  2782. case 0xC2:
  2783. case 0xC3:
  2784. case 0xC4:
  2785. case 0xC5:
  2786. case 0xC6:
  2787. case 0xC7:
  2788. case 0xC8:
  2789. case 0xC9:
  2790. case 0xCA:
  2791. case 0xCB:
  2792. case 0xCC:
  2793. case 0xCD:
  2794. case 0xCE:
  2795. case 0xCF:
  2796. case 0xD0:
  2797. case 0xD1:
  2798. case 0xD2:
  2799. case 0xD3:
  2800. case 0xD4:
  2801. case 0xD5:
  2802. case 0xD6:
  2803. case 0xD7:
  2804. case 0xD8:
  2805. case 0xD9:
  2806. case 0xDA:
  2807. case 0xDB:
  2808. case 0xDC:
  2809. case 0xDD:
  2810. case 0xDE:
  2811. case 0xDF:
  2812. {
  2813. if (JSON_UNLIKELY(not next_byte_in_range({0x80, 0xBF})))
  2814. {
  2815. return token_type::parse_error;
  2816. }
  2817. break;
  2818. }
  2819. // U+0800..U+0FFF: bytes E0 A0..BF 80..BF
  2820. case 0xE0:
  2821. {
  2822. if (JSON_UNLIKELY(not (next_byte_in_range({0xA0, 0xBF, 0x80, 0xBF}))))
  2823. {
  2824. return token_type::parse_error;
  2825. }
  2826. break;
  2827. }
  2828. // U+1000..U+CFFF: bytes E1..EC 80..BF 80..BF
  2829. // U+E000..U+FFFF: bytes EE..EF 80..BF 80..BF
  2830. case 0xE1:
  2831. case 0xE2:
  2832. case 0xE3:
  2833. case 0xE4:
  2834. case 0xE5:
  2835. case 0xE6:
  2836. case 0xE7:
  2837. case 0xE8:
  2838. case 0xE9:
  2839. case 0xEA:
  2840. case 0xEB:
  2841. case 0xEC:
  2842. case 0xEE:
  2843. case 0xEF:
  2844. {
  2845. if (JSON_UNLIKELY(not (next_byte_in_range({0x80, 0xBF, 0x80, 0xBF}))))
  2846. {
  2847. return token_type::parse_error;
  2848. }
  2849. break;
  2850. }
  2851. // U+D000..U+D7FF: bytes ED 80..9F 80..BF
  2852. case 0xED:
  2853. {
  2854. if (JSON_UNLIKELY(not (next_byte_in_range({0x80, 0x9F, 0x80, 0xBF}))))
  2855. {
  2856. return token_type::parse_error;
  2857. }
  2858. break;
  2859. }
  2860. // U+10000..U+3FFFF F0 90..BF 80..BF 80..BF
  2861. case 0xF0:
  2862. {
  2863. if (JSON_UNLIKELY(not (next_byte_in_range({0x90, 0xBF, 0x80, 0xBF, 0x80, 0xBF}))))
  2864. {
  2865. return token_type::parse_error;
  2866. }
  2867. break;
  2868. }
  2869. // U+40000..U+FFFFF F1..F3 80..BF 80..BF 80..BF
  2870. case 0xF1:
  2871. case 0xF2:
  2872. case 0xF3:
  2873. {
  2874. if (JSON_UNLIKELY(not (next_byte_in_range({0x80, 0xBF, 0x80, 0xBF, 0x80, 0xBF}))))
  2875. {
  2876. return token_type::parse_error;
  2877. }
  2878. break;
  2879. }
  2880. // U+100000..U+10FFFF F4 80..8F 80..BF 80..BF
  2881. case 0xF4:
  2882. {
  2883. if (JSON_UNLIKELY(not (next_byte_in_range({0x80, 0x8F, 0x80, 0xBF, 0x80, 0xBF}))))
  2884. {
  2885. return token_type::parse_error;
  2886. }
  2887. break;
  2888. }
  2889. // remaining bytes (80..C1 and F5..FF) are ill-formed
  2890. default:
  2891. {
  2892. error_message = "invalid string: ill-formed UTF-8 byte";
  2893. return token_type::parse_error;
  2894. }
  2895. }
  2896. }
  2897. }
  2898. static void strtof(float& f, const char* str, char** endptr) noexcept
  2899. {
  2900. f = std::strtof(str, endptr);
  2901. }
  2902. static void strtof(double& f, const char* str, char** endptr) noexcept
  2903. {
  2904. f = std::strtod(str, endptr);
  2905. }
  2906. static void strtof(long double& f, const char* str, char** endptr) noexcept
  2907. {
  2908. f = std::strtold(str, endptr);
  2909. }
  2910. /*!
  2911. @brief scan a number literal
  2912. This function scans a string according to Sect. 6 of RFC 7159.
  2913. The function is realized with a deterministic finite state machine derived
  2914. from the grammar described in RFC 7159. Starting in state "init", the
  2915. input is read and used to determined the next state. Only state "done"
  2916. accepts the number. State "error" is a trap state to model errors. In the
  2917. table below, "anything" means any character but the ones listed before.
  2918. state | 0 | 1-9 | e E | + | - | . | anything
  2919. ---------|----------|----------|----------|---------|---------|----------|-----------
  2920. init | zero | any1 | [error] | [error] | minus | [error] | [error]
  2921. minus | zero | any1 | [error] | [error] | [error] | [error] | [error]
  2922. zero | done | done | exponent | done | done | decimal1 | done
  2923. any1 | any1 | any1 | exponent | done | done | decimal1 | done
  2924. decimal1 | decimal2 | [error] | [error] | [error] | [error] | [error] | [error]
  2925. decimal2 | decimal2 | decimal2 | exponent | done | done | done | done
  2926. exponent | any2 | any2 | [error] | sign | sign | [error] | [error]
  2927. sign | any2 | any2 | [error] | [error] | [error] | [error] | [error]
  2928. any2 | any2 | any2 | done | done | done | done | done
  2929. The state machine is realized with one label per state (prefixed with
  2930. "scan_number_") and `goto` statements between them. The state machine
  2931. contains cycles, but any cycle can be left when EOF is read. Therefore,
  2932. the function is guaranteed to terminate.
  2933. During scanning, the read bytes are stored in token_buffer. This string is
  2934. then converted to a signed integer, an unsigned integer, or a
  2935. floating-point number.
  2936. @return token_type::value_unsigned, token_type::value_integer, or
  2937. token_type::value_float if number could be successfully scanned,
  2938. token_type::parse_error otherwise
  2939. @note The scanner is independent of the current locale. Internally, the
  2940. locale's decimal point is used instead of `.` to work with the
  2941. locale-dependent converters.
  2942. */
  2943. token_type scan_number() // lgtm [cpp/use-of-goto]
  2944. {
  2945. // reset token_buffer to store the number's bytes
  2946. reset();
  2947. // the type of the parsed number; initially set to unsigned; will be
  2948. // changed if minus sign, decimal point or exponent is read
  2949. token_type number_type = token_type::value_unsigned;
  2950. // state (init): we just found out we need to scan a number
  2951. switch (current)
  2952. {
  2953. case '-':
  2954. {
  2955. add(current);
  2956. goto scan_number_minus;
  2957. }
  2958. case '0':
  2959. {
  2960. add(current);
  2961. goto scan_number_zero;
  2962. }
  2963. case '1':
  2964. case '2':
  2965. case '3':
  2966. case '4':
  2967. case '5':
  2968. case '6':
  2969. case '7':
  2970. case '8':
  2971. case '9':
  2972. {
  2973. add(current);
  2974. goto scan_number_any1;
  2975. }
  2976. // LCOV_EXCL_START
  2977. default:
  2978. {
  2979. // all other characters are rejected outside scan_number()
  2980. assert(false);
  2981. }
  2982. // LCOV_EXCL_STOP
  2983. }
  2984. scan_number_minus:
  2985. // state: we just parsed a leading minus sign
  2986. number_type = token_type::value_integer;
  2987. switch (get())
  2988. {
  2989. case '0':
  2990. {
  2991. add(current);
  2992. goto scan_number_zero;
  2993. }
  2994. case '1':
  2995. case '2':
  2996. case '3':
  2997. case '4':
  2998. case '5':
  2999. case '6':
  3000. case '7':
  3001. case '8':
  3002. case '9':
  3003. {
  3004. add(current);
  3005. goto scan_number_any1;
  3006. }
  3007. default:
  3008. {
  3009. error_message = "invalid number; expected digit after '-'";
  3010. return token_type::parse_error;
  3011. }
  3012. }
  3013. scan_number_zero:
  3014. // state: we just parse a zero (maybe with a leading minus sign)
  3015. switch (get())
  3016. {
  3017. case '.':
  3018. {
  3019. add(decimal_point_char);
  3020. goto scan_number_decimal1;
  3021. }
  3022. case 'e':
  3023. case 'E':
  3024. {
  3025. add(current);
  3026. goto scan_number_exponent;
  3027. }
  3028. default:
  3029. goto scan_number_done;
  3030. }
  3031. scan_number_any1:
  3032. // state: we just parsed a number 0-9 (maybe with a leading minus sign)
  3033. switch (get())
  3034. {
  3035. case '0':
  3036. case '1':
  3037. case '2':
  3038. case '3':
  3039. case '4':
  3040. case '5':
  3041. case '6':
  3042. case '7':
  3043. case '8':
  3044. case '9':
  3045. {
  3046. add(current);
  3047. goto scan_number_any1;
  3048. }
  3049. case '.':
  3050. {
  3051. add(decimal_point_char);
  3052. goto scan_number_decimal1;
  3053. }
  3054. case 'e':
  3055. case 'E':
  3056. {
  3057. add(current);
  3058. goto scan_number_exponent;
  3059. }
  3060. default:
  3061. goto scan_number_done;
  3062. }
  3063. scan_number_decimal1:
  3064. // state: we just parsed a decimal point
  3065. number_type = token_type::value_float;
  3066. switch (get())
  3067. {
  3068. case '0':
  3069. case '1':
  3070. case '2':
  3071. case '3':
  3072. case '4':
  3073. case '5':
  3074. case '6':
  3075. case '7':
  3076. case '8':
  3077. case '9':
  3078. {
  3079. add(current);
  3080. goto scan_number_decimal2;
  3081. }
  3082. default:
  3083. {
  3084. error_message = "invalid number; expected digit after '.'";
  3085. return token_type::parse_error;
  3086. }
  3087. }
  3088. scan_number_decimal2:
  3089. // we just parsed at least one number after a decimal point
  3090. switch (get())
  3091. {
  3092. case '0':
  3093. case '1':
  3094. case '2':
  3095. case '3':
  3096. case '4':
  3097. case '5':
  3098. case '6':
  3099. case '7':
  3100. case '8':
  3101. case '9':
  3102. {
  3103. add(current);
  3104. goto scan_number_decimal2;
  3105. }
  3106. case 'e':
  3107. case 'E':
  3108. {
  3109. add(current);
  3110. goto scan_number_exponent;
  3111. }
  3112. default:
  3113. goto scan_number_done;
  3114. }
  3115. scan_number_exponent:
  3116. // we just parsed an exponent
  3117. number_type = token_type::value_float;
  3118. switch (get())
  3119. {
  3120. case '+':
  3121. case '-':
  3122. {
  3123. add(current);
  3124. goto scan_number_sign;
  3125. }
  3126. case '0':
  3127. case '1':
  3128. case '2':
  3129. case '3':
  3130. case '4':
  3131. case '5':
  3132. case '6':
  3133. case '7':
  3134. case '8':
  3135. case '9':
  3136. {
  3137. add(current);
  3138. goto scan_number_any2;
  3139. }
  3140. default:
  3141. {
  3142. error_message =
  3143. "invalid number; expected '+', '-', or digit after exponent";
  3144. return token_type::parse_error;
  3145. }
  3146. }
  3147. scan_number_sign:
  3148. // we just parsed an exponent sign
  3149. switch (get())
  3150. {
  3151. case '0':
  3152. case '1':
  3153. case '2':
  3154. case '3':
  3155. case '4':
  3156. case '5':
  3157. case '6':
  3158. case '7':
  3159. case '8':
  3160. case '9':
  3161. {
  3162. add(current);
  3163. goto scan_number_any2;
  3164. }
  3165. default:
  3166. {
  3167. error_message = "invalid number; expected digit after exponent sign";
  3168. return token_type::parse_error;
  3169. }
  3170. }
  3171. scan_number_any2:
  3172. // we just parsed a number after the exponent or exponent sign
  3173. switch (get())
  3174. {
  3175. case '0':
  3176. case '1':
  3177. case '2':
  3178. case '3':
  3179. case '4':
  3180. case '5':
  3181. case '6':
  3182. case '7':
  3183. case '8':
  3184. case '9':
  3185. {
  3186. add(current);
  3187. goto scan_number_any2;
  3188. }
  3189. default:
  3190. goto scan_number_done;
  3191. }
  3192. scan_number_done:
  3193. // unget the character after the number (we only read it to know that
  3194. // we are done scanning a number)
  3195. unget();
  3196. char* endptr = nullptr;
  3197. errno = 0;
  3198. // try to parse integers first and fall back to floats
  3199. if (number_type == token_type::value_unsigned)
  3200. {
  3201. const auto x = std::strtoull(token_buffer.data(), &endptr, 10);
  3202. // we checked the number format before
  3203. assert(endptr == token_buffer.data() + token_buffer.size());
  3204. if (errno == 0)
  3205. {
  3206. value_unsigned = static_cast<number_unsigned_t>(x);
  3207. if (value_unsigned == x)
  3208. {
  3209. return token_type::value_unsigned;
  3210. }
  3211. }
  3212. }
  3213. else if (number_type == token_type::value_integer)
  3214. {
  3215. const auto x = std::strtoll(token_buffer.data(), &endptr, 10);
  3216. // we checked the number format before
  3217. assert(endptr == token_buffer.data() + token_buffer.size());
  3218. if (errno == 0)
  3219. {
  3220. value_integer = static_cast<number_integer_t>(x);
  3221. if (value_integer == x)
  3222. {
  3223. return token_type::value_integer;
  3224. }
  3225. }
  3226. }
  3227. // this code is reached if we parse a floating-point number or if an
  3228. // integer conversion above failed
  3229. strtof(value_float, token_buffer.data(), &endptr);
  3230. // we checked the number format before
  3231. assert(endptr == token_buffer.data() + token_buffer.size());
  3232. return token_type::value_float;
  3233. }
  3234. /*!
  3235. @param[in] literal_text the literal text to expect
  3236. @param[in] length the length of the passed literal text
  3237. @param[in] return_type the token type to return on success
  3238. */
  3239. token_type scan_literal(const char* literal_text, const std::size_t length,
  3240. token_type return_type)
  3241. {
  3242. assert(current == literal_text[0]);
  3243. for (std::size_t i = 1; i < length; ++i)
  3244. {
  3245. if (JSON_UNLIKELY(get() != literal_text[i]))
  3246. {
  3247. error_message = "invalid literal";
  3248. return token_type::parse_error;
  3249. }
  3250. }
  3251. return return_type;
  3252. }
  3253. /////////////////////
  3254. // input management
  3255. /////////////////////
  3256. /// reset token_buffer; current character is beginning of token
  3257. void reset() noexcept
  3258. {
  3259. token_buffer.clear();
  3260. token_string.clear();
  3261. token_string.push_back(std::char_traits<char>::to_char_type(current));
  3262. }
  3263. /*
  3264. @brief get next character from the input
  3265. This function provides the interface to the used input adapter. It does
  3266. not throw in case the input reached EOF, but returns a
  3267. `std::char_traits<char>::eof()` in that case. Stores the scanned characters
  3268. for use in error messages.
  3269. @return character read from the input
  3270. */
  3271. std::char_traits<char>::int_type get()
  3272. {
  3273. ++position.chars_read_total;
  3274. ++position.chars_read_current_line;
  3275. if (next_unget)
  3276. {
  3277. // just reset the next_unget variable and work with current
  3278. next_unget = false;
  3279. }
  3280. else
  3281. {
  3282. current = ia->get_character();
  3283. }
  3284. if (JSON_LIKELY(current != std::char_traits<char>::eof()))
  3285. {
  3286. token_string.push_back(std::char_traits<char>::to_char_type(current));
  3287. }
  3288. if (current == '\n')
  3289. {
  3290. ++position.lines_read;
  3291. ++position.chars_read_current_line = 0;
  3292. }
  3293. return current;
  3294. }
  3295. /*!
  3296. @brief unget current character (read it again on next get)
  3297. We implement unget by setting variable next_unget to true. The input is not
  3298. changed - we just simulate ungetting by modifying chars_read_total,
  3299. chars_read_current_line, and token_string. The next call to get() will
  3300. behave as if the unget character is read again.
  3301. */
  3302. void unget()
  3303. {
  3304. next_unget = true;
  3305. --position.chars_read_total;
  3306. // in case we "unget" a newline, we have to also decrement the lines_read
  3307. if (position.chars_read_current_line == 0)
  3308. {
  3309. if (position.lines_read > 0)
  3310. {
  3311. --position.lines_read;
  3312. }
  3313. }
  3314. else
  3315. {
  3316. --position.chars_read_current_line;
  3317. }
  3318. if (JSON_LIKELY(current != std::char_traits<char>::eof()))
  3319. {
  3320. assert(token_string.size() != 0);
  3321. token_string.pop_back();
  3322. }
  3323. }
  3324. /// add a character to token_buffer
  3325. void add(int c)
  3326. {
  3327. token_buffer.push_back(std::char_traits<char>::to_char_type(c));
  3328. }
  3329. public:
  3330. /////////////////////
  3331. // value getters
  3332. /////////////////////
  3333. /// return integer value
  3334. constexpr number_integer_t get_number_integer() const noexcept
  3335. {
  3336. return value_integer;
  3337. }
  3338. /// return unsigned integer value
  3339. constexpr number_unsigned_t get_number_unsigned() const noexcept
  3340. {
  3341. return value_unsigned;
  3342. }
  3343. /// return floating-point value
  3344. constexpr number_float_t get_number_float() const noexcept
  3345. {
  3346. return value_float;
  3347. }
  3348. /// return current string value (implicitly resets the token; useful only once)
  3349. string_t& get_string()
  3350. {
  3351. return token_buffer;
  3352. }
  3353. /////////////////////
  3354. // diagnostics
  3355. /////////////////////
  3356. /// return position of last read token
  3357. constexpr position_t get_position() const noexcept
  3358. {
  3359. return position;
  3360. }
  3361. /// return the last read token (for errors only). Will never contain EOF
  3362. /// (an arbitrary value that is not a valid char value, often -1), because
  3363. /// 255 may legitimately occur. May contain NUL, which should be escaped.
  3364. std::string get_token_string() const
  3365. {
  3366. // escape control characters
  3367. std::string result;
  3368. for (const auto c : token_string)
  3369. {
  3370. if ('\x00' <= c and c <= '\x1F')
  3371. {
  3372. // escape control characters
  3373. char cs[9];
  3374. (std::snprintf)(cs, 9, "<U+%.4X>", static_cast<unsigned char>(c));
  3375. result += cs;
  3376. }
  3377. else
  3378. {
  3379. // add character as is
  3380. result.push_back(c);
  3381. }
  3382. }
  3383. return result;
  3384. }
  3385. /// return syntax error message
  3386. constexpr const char* get_error_message() const noexcept
  3387. {
  3388. return error_message;
  3389. }
  3390. /////////////////////
  3391. // actual scanner
  3392. /////////////////////
  3393. /*!
  3394. @brief skip the UTF-8 byte order mark
  3395. @return true iff there is no BOM or the correct BOM has been skipped
  3396. */
  3397. bool skip_bom()
  3398. {
  3399. if (get() == 0xEF)
  3400. {
  3401. // check if we completely parse the BOM
  3402. return get() == 0xBB and get() == 0xBF;
  3403. }
  3404. // the first character is not the beginning of the BOM; unget it to
  3405. // process is later
  3406. unget();
  3407. return true;
  3408. }
  3409. token_type scan()
  3410. {
  3411. // initially, skip the BOM
  3412. if (position.chars_read_total == 0 and not skip_bom())
  3413. {
  3414. error_message = "invalid BOM; must be 0xEF 0xBB 0xBF if given";
  3415. return token_type::parse_error;
  3416. }
  3417. // read next character and ignore whitespace
  3418. do
  3419. {
  3420. get();
  3421. }
  3422. while (current == ' ' or current == '\t' or current == '\n' or current == '\r');
  3423. switch (current)
  3424. {
  3425. // structural characters
  3426. case '[':
  3427. return token_type::begin_array;
  3428. case ']':
  3429. return token_type::end_array;
  3430. case '{':
  3431. return token_type::begin_object;
  3432. case '}':
  3433. return token_type::end_object;
  3434. case ':':
  3435. return token_type::name_separator;
  3436. case ',':
  3437. return token_type::value_separator;
  3438. // literals
  3439. case 't':
  3440. return scan_literal("true", 4, token_type::literal_true);
  3441. case 'f':
  3442. return scan_literal("false", 5, token_type::literal_false);
  3443. case 'n':
  3444. return scan_literal("null", 4, token_type::literal_null);
  3445. // string
  3446. case '\"':
  3447. return scan_string();
  3448. // number
  3449. case '-':
  3450. case '0':
  3451. case '1':
  3452. case '2':
  3453. case '3':
  3454. case '4':
  3455. case '5':
  3456. case '6':
  3457. case '7':
  3458. case '8':
  3459. case '9':
  3460. return scan_number();
  3461. // end of input (the null byte is needed when parsing from
  3462. // string literals)
  3463. case '\0':
  3464. case std::char_traits<char>::eof():
  3465. return token_type::end_of_input;
  3466. // error
  3467. default:
  3468. error_message = "invalid literal";
  3469. return token_type::parse_error;
  3470. }
  3471. }
  3472. private:
  3473. /// input adapter
  3474. detail::input_adapter_t ia = nullptr;
  3475. /// the current character
  3476. std::char_traits<char>::int_type current = std::char_traits<char>::eof();
  3477. /// whether the next get() call should just return current
  3478. bool next_unget = false;
  3479. /// the start position of the current token
  3480. position_t position;
  3481. /// raw input token string (for error messages)
  3482. std::vector<char> token_string {};
  3483. /// buffer for variable-length tokens (numbers, strings)
  3484. string_t token_buffer {};
  3485. /// a description of occurred lexer errors
  3486. const char* error_message = "";
  3487. // number values
  3488. number_integer_t value_integer = 0;
  3489. number_unsigned_t value_unsigned = 0;
  3490. number_float_t value_float = 0;
  3491. /// the decimal point
  3492. const char decimal_point_char = '.';
  3493. };
  3494. } // namespace detail
  3495. } // namespace nlohmann
  3496. // #include <nlohmann/detail/input/parser.hpp>
  3497. #include <cassert> // assert
  3498. #include <cmath> // isfinite
  3499. #include <cstdint> // uint8_t
  3500. #include <functional> // function
  3501. #include <string> // string
  3502. #include <utility> // move
  3503. // #include <nlohmann/detail/exceptions.hpp>
  3504. // #include <nlohmann/detail/macro_scope.hpp>
  3505. // #include <nlohmann/detail/meta/is_sax.hpp>
  3506. #include <cstdint> // size_t
  3507. #include <utility> // declval
  3508. // #include <nlohmann/detail/meta/detected.hpp>
  3509. // #include <nlohmann/detail/meta/type_traits.hpp>
  3510. namespace nlohmann
  3511. {
  3512. namespace detail
  3513. {
  3514. template <typename T>
  3515. using null_function_t = decltype(std::declval<T&>().null());
  3516. template <typename T>
  3517. using boolean_function_t =
  3518. decltype(std::declval<T&>().boolean(std::declval<bool>()));
  3519. template <typename T, typename Integer>
  3520. using number_integer_function_t =
  3521. decltype(std::declval<T&>().number_integer(std::declval<Integer>()));
  3522. template <typename T, typename Unsigned>
  3523. using number_unsigned_function_t =
  3524. decltype(std::declval<T&>().number_unsigned(std::declval<Unsigned>()));
  3525. template <typename T, typename Float, typename String>
  3526. using number_float_function_t = decltype(std::declval<T&>().number_float(
  3527. std::declval<Float>(), std::declval<const String&>()));
  3528. template <typename T, typename String>
  3529. using string_function_t =
  3530. decltype(std::declval<T&>().string(std::declval<String&>()));
  3531. template <typename T>
  3532. using start_object_function_t =
  3533. decltype(std::declval<T&>().start_object(std::declval<std::size_t>()));
  3534. template <typename T, typename String>
  3535. using key_function_t =
  3536. decltype(std::declval<T&>().key(std::declval<String&>()));
  3537. template <typename T>
  3538. using end_object_function_t = decltype(std::declval<T&>().end_object());
  3539. template <typename T>
  3540. using start_array_function_t =
  3541. decltype(std::declval<T&>().start_array(std::declval<std::size_t>()));
  3542. template <typename T>
  3543. using end_array_function_t = decltype(std::declval<T&>().end_array());
  3544. template <typename T, typename Exception>
  3545. using parse_error_function_t = decltype(std::declval<T&>().parse_error(
  3546. std::declval<std::size_t>(), std::declval<const std::string&>(),
  3547. std::declval<const Exception&>()));
  3548. template <typename SAX, typename BasicJsonType>
  3549. struct is_sax
  3550. {
  3551. private:
  3552. static_assert(is_basic_json<BasicJsonType>::value,
  3553. "BasicJsonType must be of type basic_json<...>");
  3554. using number_integer_t = typename BasicJsonType::number_integer_t;
  3555. using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
  3556. using number_float_t = typename BasicJsonType::number_float_t;
  3557. using string_t = typename BasicJsonType::string_t;
  3558. using exception_t = typename BasicJsonType::exception;
  3559. public:
  3560. static constexpr bool value =
  3561. is_detected_exact<bool, null_function_t, SAX>::value &&
  3562. is_detected_exact<bool, boolean_function_t, SAX>::value &&
  3563. is_detected_exact<bool, number_integer_function_t, SAX,
  3564. number_integer_t>::value &&
  3565. is_detected_exact<bool, number_unsigned_function_t, SAX,
  3566. number_unsigned_t>::value &&
  3567. is_detected_exact<bool, number_float_function_t, SAX, number_float_t,
  3568. string_t>::value &&
  3569. is_detected_exact<bool, string_function_t, SAX, string_t>::value &&
  3570. is_detected_exact<bool, start_object_function_t, SAX>::value &&
  3571. is_detected_exact<bool, key_function_t, SAX, string_t>::value &&
  3572. is_detected_exact<bool, end_object_function_t, SAX>::value &&
  3573. is_detected_exact<bool, start_array_function_t, SAX>::value &&
  3574. is_detected_exact<bool, end_array_function_t, SAX>::value &&
  3575. is_detected_exact<bool, parse_error_function_t, SAX, exception_t>::value;
  3576. };
  3577. template <typename SAX, typename BasicJsonType>
  3578. struct is_sax_static_asserts
  3579. {
  3580. private:
  3581. static_assert(is_basic_json<BasicJsonType>::value,
  3582. "BasicJsonType must be of type basic_json<...>");
  3583. using number_integer_t = typename BasicJsonType::number_integer_t;
  3584. using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
  3585. using number_float_t = typename BasicJsonType::number_float_t;
  3586. using string_t = typename BasicJsonType::string_t;
  3587. using exception_t = typename BasicJsonType::exception;
  3588. public:
  3589. static_assert(is_detected_exact<bool, null_function_t, SAX>::value,
  3590. "Missing/invalid function: bool null()");
  3591. static_assert(is_detected_exact<bool, boolean_function_t, SAX>::value,
  3592. "Missing/invalid function: bool boolean(bool)");
  3593. static_assert(is_detected_exact<bool, boolean_function_t, SAX>::value,
  3594. "Missing/invalid function: bool boolean(bool)");
  3595. static_assert(
  3596. is_detected_exact<bool, number_integer_function_t, SAX,
  3597. number_integer_t>::value,
  3598. "Missing/invalid function: bool number_integer(number_integer_t)");
  3599. static_assert(
  3600. is_detected_exact<bool, number_unsigned_function_t, SAX,
  3601. number_unsigned_t>::value,
  3602. "Missing/invalid function: bool number_unsigned(number_unsigned_t)");
  3603. static_assert(is_detected_exact<bool, number_float_function_t, SAX,
  3604. number_float_t, string_t>::value,
  3605. "Missing/invalid function: bool number_float(number_float_t, const string_t&)");
  3606. static_assert(
  3607. is_detected_exact<bool, string_function_t, SAX, string_t>::value,
  3608. "Missing/invalid function: bool string(string_t&)");
  3609. static_assert(is_detected_exact<bool, start_object_function_t, SAX>::value,
  3610. "Missing/invalid function: bool start_object(std::size_t)");
  3611. static_assert(is_detected_exact<bool, key_function_t, SAX, string_t>::value,
  3612. "Missing/invalid function: bool key(string_t&)");
  3613. static_assert(is_detected_exact<bool, end_object_function_t, SAX>::value,
  3614. "Missing/invalid function: bool end_object()");
  3615. static_assert(is_detected_exact<bool, start_array_function_t, SAX>::value,
  3616. "Missing/invalid function: bool start_array(std::size_t)");
  3617. static_assert(is_detected_exact<bool, end_array_function_t, SAX>::value,
  3618. "Missing/invalid function: bool end_array()");
  3619. static_assert(
  3620. is_detected_exact<bool, parse_error_function_t, SAX, exception_t>::value,
  3621. "Missing/invalid function: bool parse_error(std::size_t, const "
  3622. "std::string&, const exception&)");
  3623. };
  3624. } // namespace detail
  3625. } // namespace nlohmann
  3626. // #include <nlohmann/detail/input/input_adapters.hpp>
  3627. // #include <nlohmann/detail/input/json_sax.hpp>
  3628. #include <cstddef>
  3629. #include <string>
  3630. #include <vector>
  3631. // #include <nlohmann/detail/input/parser.hpp>
  3632. // #include <nlohmann/detail/exceptions.hpp>
  3633. namespace nlohmann
  3634. {
  3635. /*!
  3636. @brief SAX interface
  3637. This class describes the SAX interface used by @ref nlohmann::json::sax_parse.
  3638. Each function is called in different situations while the input is parsed. The
  3639. boolean return value informs the parser whether to continue processing the
  3640. input.
  3641. */
  3642. template<typename BasicJsonType>
  3643. struct json_sax
  3644. {
  3645. /// type for (signed) integers
  3646. using number_integer_t = typename BasicJsonType::number_integer_t;
  3647. /// type for unsigned integers
  3648. using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
  3649. /// type for floating-point numbers
  3650. using number_float_t = typename BasicJsonType::number_float_t;
  3651. /// type for strings
  3652. using string_t = typename BasicJsonType::string_t;
  3653. /*!
  3654. @brief a null value was read
  3655. @return whether parsing should proceed
  3656. */
  3657. virtual bool null() = 0;
  3658. /*!
  3659. @brief a boolean value was read
  3660. @param[in] val boolean value
  3661. @return whether parsing should proceed
  3662. */
  3663. virtual bool boolean(bool val) = 0;
  3664. /*!
  3665. @brief an integer number was read
  3666. @param[in] val integer value
  3667. @return whether parsing should proceed
  3668. */
  3669. virtual bool number_integer(number_integer_t val) = 0;
  3670. /*!
  3671. @brief an unsigned integer number was read
  3672. @param[in] val unsigned integer value
  3673. @return whether parsing should proceed
  3674. */
  3675. virtual bool number_unsigned(number_unsigned_t val) = 0;
  3676. /*!
  3677. @brief an floating-point number was read
  3678. @param[in] val floating-point value
  3679. @param[in] s raw token value
  3680. @return whether parsing should proceed
  3681. */
  3682. virtual bool number_float(number_float_t val, const string_t& s) = 0;
  3683. /*!
  3684. @brief a string was read
  3685. @param[in] val string value
  3686. @return whether parsing should proceed
  3687. @note It is safe to move the passed string.
  3688. */
  3689. virtual bool string(string_t& val) = 0;
  3690. /*!
  3691. @brief the beginning of an object was read
  3692. @param[in] elements number of object elements or -1 if unknown
  3693. @return whether parsing should proceed
  3694. @note binary formats may report the number of elements
  3695. */
  3696. virtual bool start_object(std::size_t elements) = 0;
  3697. /*!
  3698. @brief an object key was read
  3699. @param[in] val object key
  3700. @return whether parsing should proceed
  3701. @note It is safe to move the passed string.
  3702. */
  3703. virtual bool key(string_t& val) = 0;
  3704. /*!
  3705. @brief the end of an object was read
  3706. @return whether parsing should proceed
  3707. */
  3708. virtual bool end_object() = 0;
  3709. /*!
  3710. @brief the beginning of an array was read
  3711. @param[in] elements number of array elements or -1 if unknown
  3712. @return whether parsing should proceed
  3713. @note binary formats may report the number of elements
  3714. */
  3715. virtual bool start_array(std::size_t elements) = 0;
  3716. /*!
  3717. @brief the end of an array was read
  3718. @return whether parsing should proceed
  3719. */
  3720. virtual bool end_array() = 0;
  3721. /*!
  3722. @brief a parse error occurred
  3723. @param[in] position the position in the input where the error occurs
  3724. @param[in] last_token the last read token
  3725. @param[in] ex an exception object describing the error
  3726. @return whether parsing should proceed (must return false)
  3727. */
  3728. virtual bool parse_error(std::size_t position,
  3729. const std::string& last_token,
  3730. const detail::exception& ex) = 0;
  3731. virtual ~json_sax() = default;
  3732. };
  3733. namespace detail
  3734. {
  3735. /*!
  3736. @brief SAX implementation to create a JSON value from SAX events
  3737. This class implements the @ref json_sax interface and processes the SAX events
  3738. to create a JSON value which makes it basically a DOM parser. The structure or
  3739. hierarchy of the JSON value is managed by the stack `ref_stack` which contains
  3740. a pointer to the respective array or object for each recursion depth.
  3741. After successful parsing, the value that is passed by reference to the
  3742. constructor contains the parsed value.
  3743. @tparam BasicJsonType the JSON type
  3744. */
  3745. template<typename BasicJsonType>
  3746. class json_sax_dom_parser
  3747. {
  3748. public:
  3749. using number_integer_t = typename BasicJsonType::number_integer_t;
  3750. using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
  3751. using number_float_t = typename BasicJsonType::number_float_t;
  3752. using string_t = typename BasicJsonType::string_t;
  3753. /*!
  3754. @param[in, out] r reference to a JSON value that is manipulated while
  3755. parsing
  3756. @param[in] allow_exceptions_ whether parse errors yield exceptions
  3757. */
  3758. explicit json_sax_dom_parser(BasicJsonType& r, const bool allow_exceptions_ = true)
  3759. : root(r), allow_exceptions(allow_exceptions_)
  3760. {}
  3761. bool null()
  3762. {
  3763. handle_value(nullptr);
  3764. return true;
  3765. }
  3766. bool boolean(bool val)
  3767. {
  3768. handle_value(val);
  3769. return true;
  3770. }
  3771. bool number_integer(number_integer_t val)
  3772. {
  3773. handle_value(val);
  3774. return true;
  3775. }
  3776. bool number_unsigned(number_unsigned_t val)
  3777. {
  3778. handle_value(val);
  3779. return true;
  3780. }
  3781. bool number_float(number_float_t val, const string_t& /*unused*/)
  3782. {
  3783. handle_value(val);
  3784. return true;
  3785. }
  3786. bool string(string_t& val)
  3787. {
  3788. handle_value(val);
  3789. return true;
  3790. }
  3791. bool start_object(std::size_t len)
  3792. {
  3793. ref_stack.push_back(handle_value(BasicJsonType::value_t::object));
  3794. if (JSON_UNLIKELY(len != std::size_t(-1) and len > ref_stack.back()->max_size()))
  3795. {
  3796. JSON_THROW(out_of_range::create(408,
  3797. "excessive object size: " + std::to_string(len)));
  3798. }
  3799. return true;
  3800. }
  3801. bool key(string_t& val)
  3802. {
  3803. // add null at given key and store the reference for later
  3804. object_element = &(ref_stack.back()->m_value.object->operator[](val));
  3805. return true;
  3806. }
  3807. bool end_object()
  3808. {
  3809. ref_stack.pop_back();
  3810. return true;
  3811. }
  3812. bool start_array(std::size_t len)
  3813. {
  3814. ref_stack.push_back(handle_value(BasicJsonType::value_t::array));
  3815. if (JSON_UNLIKELY(len != std::size_t(-1) and len > ref_stack.back()->max_size()))
  3816. {
  3817. JSON_THROW(out_of_range::create(408,
  3818. "excessive array size: " + std::to_string(len)));
  3819. }
  3820. return true;
  3821. }
  3822. bool end_array()
  3823. {
  3824. ref_stack.pop_back();
  3825. return true;
  3826. }
  3827. bool parse_error(std::size_t /*unused*/, const std::string& /*unused*/,
  3828. const detail::exception& ex)
  3829. {
  3830. errored = true;
  3831. if (allow_exceptions)
  3832. {
  3833. // determine the proper exception type from the id
  3834. switch ((ex.id / 100) % 100)
  3835. {
  3836. case 1:
  3837. JSON_THROW(*reinterpret_cast<const detail::parse_error*>(&ex));
  3838. case 4:
  3839. JSON_THROW(*reinterpret_cast<const detail::out_of_range*>(&ex));
  3840. // LCOV_EXCL_START
  3841. case 2:
  3842. JSON_THROW(*reinterpret_cast<const detail::invalid_iterator*>(&ex));
  3843. case 3:
  3844. JSON_THROW(*reinterpret_cast<const detail::type_error*>(&ex));
  3845. case 5:
  3846. JSON_THROW(*reinterpret_cast<const detail::other_error*>(&ex));
  3847. default:
  3848. assert(false);
  3849. // LCOV_EXCL_STOP
  3850. }
  3851. }
  3852. return false;
  3853. }
  3854. constexpr bool is_errored() const
  3855. {
  3856. return errored;
  3857. }
  3858. private:
  3859. /*!
  3860. @invariant If the ref stack is empty, then the passed value will be the new
  3861. root.
  3862. @invariant If the ref stack contains a value, then it is an array or an
  3863. object to which we can add elements
  3864. */
  3865. template<typename Value>
  3866. BasicJsonType* handle_value(Value&& v)
  3867. {
  3868. if (ref_stack.empty())
  3869. {
  3870. root = BasicJsonType(std::forward<Value>(v));
  3871. return &root;
  3872. }
  3873. assert(ref_stack.back()->is_array() or ref_stack.back()->is_object());
  3874. if (ref_stack.back()->is_array())
  3875. {
  3876. ref_stack.back()->m_value.array->emplace_back(std::forward<Value>(v));
  3877. return &(ref_stack.back()->m_value.array->back());
  3878. }
  3879. else
  3880. {
  3881. assert(object_element);
  3882. *object_element = BasicJsonType(std::forward<Value>(v));
  3883. return object_element;
  3884. }
  3885. }
  3886. /// the parsed JSON value
  3887. BasicJsonType& root;
  3888. /// stack to model hierarchy of values
  3889. std::vector<BasicJsonType*> ref_stack;
  3890. /// helper to hold the reference for the next object element
  3891. BasicJsonType* object_element = nullptr;
  3892. /// whether a syntax error occurred
  3893. bool errored = false;
  3894. /// whether to throw exceptions in case of errors
  3895. const bool allow_exceptions = true;
  3896. };
  3897. template<typename BasicJsonType>
  3898. class json_sax_dom_callback_parser
  3899. {
  3900. public:
  3901. using number_integer_t = typename BasicJsonType::number_integer_t;
  3902. using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
  3903. using number_float_t = typename BasicJsonType::number_float_t;
  3904. using string_t = typename BasicJsonType::string_t;
  3905. using parser_callback_t = typename BasicJsonType::parser_callback_t;
  3906. using parse_event_t = typename BasicJsonType::parse_event_t;
  3907. json_sax_dom_callback_parser(BasicJsonType& r,
  3908. const parser_callback_t cb,
  3909. const bool allow_exceptions_ = true)
  3910. : root(r), callback(cb), allow_exceptions(allow_exceptions_)
  3911. {
  3912. keep_stack.push_back(true);
  3913. }
  3914. bool null()
  3915. {
  3916. handle_value(nullptr);
  3917. return true;
  3918. }
  3919. bool boolean(bool val)
  3920. {
  3921. handle_value(val);
  3922. return true;
  3923. }
  3924. bool number_integer(number_integer_t val)
  3925. {
  3926. handle_value(val);
  3927. return true;
  3928. }
  3929. bool number_unsigned(number_unsigned_t val)
  3930. {
  3931. handle_value(val);
  3932. return true;
  3933. }
  3934. bool number_float(number_float_t val, const string_t& /*unused*/)
  3935. {
  3936. handle_value(val);
  3937. return true;
  3938. }
  3939. bool string(string_t& val)
  3940. {
  3941. handle_value(val);
  3942. return true;
  3943. }
  3944. bool start_object(std::size_t len)
  3945. {
  3946. // check callback for object start
  3947. const bool keep = callback(static_cast<int>(ref_stack.size()), parse_event_t::object_start, discarded);
  3948. keep_stack.push_back(keep);
  3949. auto val = handle_value(BasicJsonType::value_t::object, true);
  3950. ref_stack.push_back(val.second);
  3951. // check object limit
  3952. if (ref_stack.back())
  3953. {
  3954. if (JSON_UNLIKELY(len != std::size_t(-1) and len > ref_stack.back()->max_size()))
  3955. {
  3956. JSON_THROW(out_of_range::create(408,
  3957. "excessive object size: " + std::to_string(len)));
  3958. }
  3959. }
  3960. return true;
  3961. }
  3962. bool key(string_t& val)
  3963. {
  3964. BasicJsonType k = BasicJsonType(val);
  3965. // check callback for key
  3966. const bool keep = callback(static_cast<int>(ref_stack.size()), parse_event_t::key, k);
  3967. key_keep_stack.push_back(keep);
  3968. // add discarded value at given key and store the reference for later
  3969. if (keep and ref_stack.back())
  3970. {
  3971. object_element = &(ref_stack.back()->m_value.object->operator[](val) = discarded);
  3972. }
  3973. return true;
  3974. }
  3975. bool end_object()
  3976. {
  3977. if (ref_stack.back())
  3978. {
  3979. if (not callback(static_cast<int>(ref_stack.size()) - 1, parse_event_t::object_end, *ref_stack.back()))
  3980. {
  3981. // discard object
  3982. *ref_stack.back() = discarded;
  3983. }
  3984. }
  3985. assert(not ref_stack.empty());
  3986. assert(not keep_stack.empty());
  3987. ref_stack.pop_back();
  3988. keep_stack.pop_back();
  3989. if (not ref_stack.empty() and ref_stack.back())
  3990. {
  3991. // remove discarded value
  3992. if (ref_stack.back()->is_object())
  3993. {
  3994. for (auto it = ref_stack.back()->begin(); it != ref_stack.back()->end(); ++it)
  3995. {
  3996. if (it->is_discarded())
  3997. {
  3998. ref_stack.back()->erase(it);
  3999. break;
  4000. }
  4001. }
  4002. }
  4003. }
  4004. return true;
  4005. }
  4006. bool start_array(std::size_t len)
  4007. {
  4008. const bool keep = callback(static_cast<int>(ref_stack.size()), parse_event_t::array_start, discarded);
  4009. keep_stack.push_back(keep);
  4010. auto val = handle_value(BasicJsonType::value_t::array, true);
  4011. ref_stack.push_back(val.second);
  4012. // check array limit
  4013. if (ref_stack.back())
  4014. {
  4015. if (JSON_UNLIKELY(len != std::size_t(-1) and len > ref_stack.back()->max_size()))
  4016. {
  4017. JSON_THROW(out_of_range::create(408,
  4018. "excessive array size: " + std::to_string(len)));
  4019. }
  4020. }
  4021. return true;
  4022. }
  4023. bool end_array()
  4024. {
  4025. bool keep = true;
  4026. if (ref_stack.back())
  4027. {
  4028. keep = callback(static_cast<int>(ref_stack.size()) - 1, parse_event_t::array_end, *ref_stack.back());
  4029. if (not keep)
  4030. {
  4031. // discard array
  4032. *ref_stack.back() = discarded;
  4033. }
  4034. }
  4035. assert(not ref_stack.empty());
  4036. assert(not keep_stack.empty());
  4037. ref_stack.pop_back();
  4038. keep_stack.pop_back();
  4039. // remove discarded value
  4040. if (not keep and not ref_stack.empty())
  4041. {
  4042. if (ref_stack.back()->is_array())
  4043. {
  4044. ref_stack.back()->m_value.array->pop_back();
  4045. }
  4046. }
  4047. return true;
  4048. }
  4049. bool parse_error(std::size_t /*unused*/, const std::string& /*unused*/,
  4050. const detail::exception& ex)
  4051. {
  4052. errored = true;
  4053. if (allow_exceptions)
  4054. {
  4055. // determine the proper exception type from the id
  4056. switch ((ex.id / 100) % 100)
  4057. {
  4058. case 1:
  4059. JSON_THROW(*reinterpret_cast<const detail::parse_error*>(&ex));
  4060. case 4:
  4061. JSON_THROW(*reinterpret_cast<const detail::out_of_range*>(&ex));
  4062. // LCOV_EXCL_START
  4063. case 2:
  4064. JSON_THROW(*reinterpret_cast<const detail::invalid_iterator*>(&ex));
  4065. case 3:
  4066. JSON_THROW(*reinterpret_cast<const detail::type_error*>(&ex));
  4067. case 5:
  4068. JSON_THROW(*reinterpret_cast<const detail::other_error*>(&ex));
  4069. default:
  4070. assert(false);
  4071. // LCOV_EXCL_STOP
  4072. }
  4073. }
  4074. return false;
  4075. }
  4076. constexpr bool is_errored() const
  4077. {
  4078. return errored;
  4079. }
  4080. private:
  4081. /*!
  4082. @param[in] v value to add to the JSON value we build during parsing
  4083. @param[in] skip_callback whether we should skip calling the callback
  4084. function; this is required after start_array() and
  4085. start_object() SAX events, because otherwise we would call the
  4086. callback function with an empty array or object, respectively.
  4087. @invariant If the ref stack is empty, then the passed value will be the new
  4088. root.
  4089. @invariant If the ref stack contains a value, then it is an array or an
  4090. object to which we can add elements
  4091. @return pair of boolean (whether value should be kept) and pointer (to the
  4092. passed value in the ref_stack hierarchy; nullptr if not kept)
  4093. */
  4094. template<typename Value>
  4095. std::pair<bool, BasicJsonType*> handle_value(Value&& v, const bool skip_callback = false)
  4096. {
  4097. assert(not keep_stack.empty());
  4098. // do not handle this value if we know it would be added to a discarded
  4099. // container
  4100. if (not keep_stack.back())
  4101. {
  4102. return {false, nullptr};
  4103. }
  4104. // create value
  4105. auto value = BasicJsonType(std::forward<Value>(v));
  4106. // check callback
  4107. const bool keep = skip_callback or callback(static_cast<int>(ref_stack.size()), parse_event_t::value, value);
  4108. // do not handle this value if we just learnt it shall be discarded
  4109. if (not keep)
  4110. {
  4111. return {false, nullptr};
  4112. }
  4113. if (ref_stack.empty())
  4114. {
  4115. root = std::move(value);
  4116. return {true, &root};
  4117. }
  4118. // skip this value if we already decided to skip the parent
  4119. // (https://github.com/nlohmann/json/issues/971#issuecomment-413678360)
  4120. if (not ref_stack.back())
  4121. {
  4122. return {false, nullptr};
  4123. }
  4124. // we now only expect arrays and objects
  4125. assert(ref_stack.back()->is_array() or ref_stack.back()->is_object());
  4126. if (ref_stack.back()->is_array())
  4127. {
  4128. ref_stack.back()->m_value.array->push_back(std::move(value));
  4129. return {true, &(ref_stack.back()->m_value.array->back())};
  4130. }
  4131. else
  4132. {
  4133. // check if we should store an element for the current key
  4134. assert(not key_keep_stack.empty());
  4135. const bool store_element = key_keep_stack.back();
  4136. key_keep_stack.pop_back();
  4137. if (not store_element)
  4138. {
  4139. return {false, nullptr};
  4140. }
  4141. assert(object_element);
  4142. *object_element = std::move(value);
  4143. return {true, object_element};
  4144. }
  4145. }
  4146. /// the parsed JSON value
  4147. BasicJsonType& root;
  4148. /// stack to model hierarchy of values
  4149. std::vector<BasicJsonType*> ref_stack;
  4150. /// stack to manage which values to keep
  4151. std::vector<bool> keep_stack;
  4152. /// stack to manage which object keys to keep
  4153. std::vector<bool> key_keep_stack;
  4154. /// helper to hold the reference for the next object element
  4155. BasicJsonType* object_element = nullptr;
  4156. /// whether a syntax error occurred
  4157. bool errored = false;
  4158. /// callback function
  4159. const parser_callback_t callback = nullptr;
  4160. /// whether to throw exceptions in case of errors
  4161. const bool allow_exceptions = true;
  4162. /// a discarded value for the callback
  4163. BasicJsonType discarded = BasicJsonType::value_t::discarded;
  4164. };
  4165. template<typename BasicJsonType>
  4166. class json_sax_acceptor
  4167. {
  4168. public:
  4169. using number_integer_t = typename BasicJsonType::number_integer_t;
  4170. using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
  4171. using number_float_t = typename BasicJsonType::number_float_t;
  4172. using string_t = typename BasicJsonType::string_t;
  4173. bool null()
  4174. {
  4175. return true;
  4176. }
  4177. bool boolean(bool /*unused*/)
  4178. {
  4179. return true;
  4180. }
  4181. bool number_integer(number_integer_t /*unused*/)
  4182. {
  4183. return true;
  4184. }
  4185. bool number_unsigned(number_unsigned_t /*unused*/)
  4186. {
  4187. return true;
  4188. }
  4189. bool number_float(number_float_t /*unused*/, const string_t& /*unused*/)
  4190. {
  4191. return true;
  4192. }
  4193. bool string(string_t& /*unused*/)
  4194. {
  4195. return true;
  4196. }
  4197. bool start_object(std::size_t /*unused*/ = std::size_t(-1))
  4198. {
  4199. return true;
  4200. }
  4201. bool key(string_t& /*unused*/)
  4202. {
  4203. return true;
  4204. }
  4205. bool end_object()
  4206. {
  4207. return true;
  4208. }
  4209. bool start_array(std::size_t /*unused*/ = std::size_t(-1))
  4210. {
  4211. return true;
  4212. }
  4213. bool end_array()
  4214. {
  4215. return true;
  4216. }
  4217. bool parse_error(std::size_t /*unused*/, const std::string& /*unused*/, const detail::exception& /*unused*/)
  4218. {
  4219. return false;
  4220. }
  4221. };
  4222. } // namespace detail
  4223. } // namespace nlohmann
  4224. // #include <nlohmann/detail/input/lexer.hpp>
  4225. // #include <nlohmann/detail/value_t.hpp>
  4226. namespace nlohmann
  4227. {
  4228. namespace detail
  4229. {
  4230. ////////////
  4231. // parser //
  4232. ////////////
  4233. /*!
  4234. @brief syntax analysis
  4235. This class implements a recursive decent parser.
  4236. */
  4237. template<typename BasicJsonType>
  4238. class parser
  4239. {
  4240. using number_integer_t = typename BasicJsonType::number_integer_t;
  4241. using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
  4242. using number_float_t = typename BasicJsonType::number_float_t;
  4243. using string_t = typename BasicJsonType::string_t;
  4244. using lexer_t = lexer<BasicJsonType>;
  4245. using token_type = typename lexer_t::token_type;
  4246. public:
  4247. enum class parse_event_t : uint8_t
  4248. {
  4249. /// the parser read `{` and started to process a JSON object
  4250. object_start,
  4251. /// the parser read `}` and finished processing a JSON object
  4252. object_end,
  4253. /// the parser read `[` and started to process a JSON array
  4254. array_start,
  4255. /// the parser read `]` and finished processing a JSON array
  4256. array_end,
  4257. /// the parser read a key of a value in an object
  4258. key,
  4259. /// the parser finished reading a JSON value
  4260. value
  4261. };
  4262. using parser_callback_t =
  4263. std::function<bool(int depth, parse_event_t event, BasicJsonType& parsed)>;
  4264. /// a parser reading from an input adapter
  4265. explicit parser(detail::input_adapter_t&& adapter,
  4266. const parser_callback_t cb = nullptr,
  4267. const bool allow_exceptions_ = true)
  4268. : callback(cb), m_lexer(std::move(adapter)), allow_exceptions(allow_exceptions_)
  4269. {
  4270. // read first token
  4271. get_token();
  4272. }
  4273. /*!
  4274. @brief public parser interface
  4275. @param[in] strict whether to expect the last token to be EOF
  4276. @param[in,out] result parsed JSON value
  4277. @throw parse_error.101 in case of an unexpected token
  4278. @throw parse_error.102 if to_unicode fails or surrogate error
  4279. @throw parse_error.103 if to_unicode fails
  4280. */
  4281. void parse(const bool strict, BasicJsonType& result)
  4282. {
  4283. if (callback)
  4284. {
  4285. json_sax_dom_callback_parser<BasicJsonType> sdp(result, callback, allow_exceptions);
  4286. sax_parse_internal(&sdp);
  4287. result.assert_invariant();
  4288. // in strict mode, input must be completely read
  4289. if (strict and (get_token() != token_type::end_of_input))
  4290. {
  4291. sdp.parse_error(m_lexer.get_position(),
  4292. m_lexer.get_token_string(),
  4293. parse_error::create(101, m_lexer.get_position(),
  4294. exception_message(token_type::end_of_input, "value")));
  4295. }
  4296. // in case of an error, return discarded value
  4297. if (sdp.is_errored())
  4298. {
  4299. result = value_t::discarded;
  4300. return;
  4301. }
  4302. // set top-level value to null if it was discarded by the callback
  4303. // function
  4304. if (result.is_discarded())
  4305. {
  4306. result = nullptr;
  4307. }
  4308. }
  4309. else
  4310. {
  4311. json_sax_dom_parser<BasicJsonType> sdp(result, allow_exceptions);
  4312. sax_parse_internal(&sdp);
  4313. result.assert_invariant();
  4314. // in strict mode, input must be completely read
  4315. if (strict and (get_token() != token_type::end_of_input))
  4316. {
  4317. sdp.parse_error(m_lexer.get_position(),
  4318. m_lexer.get_token_string(),
  4319. parse_error::create(101, m_lexer.get_position(),
  4320. exception_message(token_type::end_of_input, "value")));
  4321. }
  4322. // in case of an error, return discarded value
  4323. if (sdp.is_errored())
  4324. {
  4325. result = value_t::discarded;
  4326. return;
  4327. }
  4328. }
  4329. }
  4330. /*!
  4331. @brief public accept interface
  4332. @param[in] strict whether to expect the last token to be EOF
  4333. @return whether the input is a proper JSON text
  4334. */
  4335. bool accept(const bool strict = true)
  4336. {
  4337. json_sax_acceptor<BasicJsonType> sax_acceptor;
  4338. return sax_parse(&sax_acceptor, strict);
  4339. }
  4340. template <typename SAX>
  4341. bool sax_parse(SAX* sax, const bool strict = true)
  4342. {
  4343. (void)detail::is_sax_static_asserts<SAX, BasicJsonType> {};
  4344. const bool result = sax_parse_internal(sax);
  4345. // strict mode: next byte must be EOF
  4346. if (result and strict and (get_token() != token_type::end_of_input))
  4347. {
  4348. return sax->parse_error(m_lexer.get_position(),
  4349. m_lexer.get_token_string(),
  4350. parse_error::create(101, m_lexer.get_position(),
  4351. exception_message(token_type::end_of_input, "value")));
  4352. }
  4353. return result;
  4354. }
  4355. private:
  4356. template <typename SAX>
  4357. bool sax_parse_internal(SAX* sax)
  4358. {
  4359. // stack to remember the hierarchy of structured values we are parsing
  4360. // true = array; false = object
  4361. std::vector<bool> states;
  4362. // value to avoid a goto (see comment where set to true)
  4363. bool skip_to_state_evaluation = false;
  4364. while (true)
  4365. {
  4366. if (not skip_to_state_evaluation)
  4367. {
  4368. // invariant: get_token() was called before each iteration
  4369. switch (last_token)
  4370. {
  4371. case token_type::begin_object:
  4372. {
  4373. if (JSON_UNLIKELY(not sax->start_object(std::size_t(-1))))
  4374. {
  4375. return false;
  4376. }
  4377. // closing } -> we are done
  4378. if (get_token() == token_type::end_object)
  4379. {
  4380. if (JSON_UNLIKELY(not sax->end_object()))
  4381. {
  4382. return false;
  4383. }
  4384. break;
  4385. }
  4386. // parse key
  4387. if (JSON_UNLIKELY(last_token != token_type::value_string))
  4388. {
  4389. return sax->parse_error(m_lexer.get_position(),
  4390. m_lexer.get_token_string(),
  4391. parse_error::create(101, m_lexer.get_position(),
  4392. exception_message(token_type::value_string, "object key")));
  4393. }
  4394. if (JSON_UNLIKELY(not sax->key(m_lexer.get_string())))
  4395. {
  4396. return false;
  4397. }
  4398. // parse separator (:)
  4399. if (JSON_UNLIKELY(get_token() != token_type::name_separator))
  4400. {
  4401. return sax->parse_error(m_lexer.get_position(),
  4402. m_lexer.get_token_string(),
  4403. parse_error::create(101, m_lexer.get_position(),
  4404. exception_message(token_type::name_separator, "object separator")));
  4405. }
  4406. // remember we are now inside an object
  4407. states.push_back(false);
  4408. // parse values
  4409. get_token();
  4410. continue;
  4411. }
  4412. case token_type::begin_array:
  4413. {
  4414. if (JSON_UNLIKELY(not sax->start_array(std::size_t(-1))))
  4415. {
  4416. return false;
  4417. }
  4418. // closing ] -> we are done
  4419. if (get_token() == token_type::end_array)
  4420. {
  4421. if (JSON_UNLIKELY(not sax->end_array()))
  4422. {
  4423. return false;
  4424. }
  4425. break;
  4426. }
  4427. // remember we are now inside an array
  4428. states.push_back(true);
  4429. // parse values (no need to call get_token)
  4430. continue;
  4431. }
  4432. case token_type::value_float:
  4433. {
  4434. const auto res = m_lexer.get_number_float();
  4435. if (JSON_UNLIKELY(not std::isfinite(res)))
  4436. {
  4437. return sax->parse_error(m_lexer.get_position(),
  4438. m_lexer.get_token_string(),
  4439. out_of_range::create(406, "number overflow parsing '" + m_lexer.get_token_string() + "'"));
  4440. }
  4441. else
  4442. {
  4443. if (JSON_UNLIKELY(not sax->number_float(res, m_lexer.get_string())))
  4444. {
  4445. return false;
  4446. }
  4447. break;
  4448. }
  4449. }
  4450. case token_type::literal_false:
  4451. {
  4452. if (JSON_UNLIKELY(not sax->boolean(false)))
  4453. {
  4454. return false;
  4455. }
  4456. break;
  4457. }
  4458. case token_type::literal_null:
  4459. {
  4460. if (JSON_UNLIKELY(not sax->null()))
  4461. {
  4462. return false;
  4463. }
  4464. break;
  4465. }
  4466. case token_type::literal_true:
  4467. {
  4468. if (JSON_UNLIKELY(not sax->boolean(true)))
  4469. {
  4470. return false;
  4471. }
  4472. break;
  4473. }
  4474. case token_type::value_integer:
  4475. {
  4476. if (JSON_UNLIKELY(not sax->number_integer(m_lexer.get_number_integer())))
  4477. {
  4478. return false;
  4479. }
  4480. break;
  4481. }
  4482. case token_type::value_string:
  4483. {
  4484. if (JSON_UNLIKELY(not sax->string(m_lexer.get_string())))
  4485. {
  4486. return false;
  4487. }
  4488. break;
  4489. }
  4490. case token_type::value_unsigned:
  4491. {
  4492. if (JSON_UNLIKELY(not sax->number_unsigned(m_lexer.get_number_unsigned())))
  4493. {
  4494. return false;
  4495. }
  4496. break;
  4497. }
  4498. case token_type::parse_error:
  4499. {
  4500. // using "uninitialized" to avoid "expected" message
  4501. return sax->parse_error(m_lexer.get_position(),
  4502. m_lexer.get_token_string(),
  4503. parse_error::create(101, m_lexer.get_position(),
  4504. exception_message(token_type::uninitialized, "value")));
  4505. }
  4506. default: // the last token was unexpected
  4507. {
  4508. return sax->parse_error(m_lexer.get_position(),
  4509. m_lexer.get_token_string(),
  4510. parse_error::create(101, m_lexer.get_position(),
  4511. exception_message(token_type::literal_or_value, "value")));
  4512. }
  4513. }
  4514. }
  4515. else
  4516. {
  4517. skip_to_state_evaluation = false;
  4518. }
  4519. // we reached this line after we successfully parsed a value
  4520. if (states.empty())
  4521. {
  4522. // empty stack: we reached the end of the hierarchy: done
  4523. return true;
  4524. }
  4525. else
  4526. {
  4527. if (states.back()) // array
  4528. {
  4529. // comma -> next value
  4530. if (get_token() == token_type::value_separator)
  4531. {
  4532. // parse a new value
  4533. get_token();
  4534. continue;
  4535. }
  4536. // closing ]
  4537. if (JSON_LIKELY(last_token == token_type::end_array))
  4538. {
  4539. if (JSON_UNLIKELY(not sax->end_array()))
  4540. {
  4541. return false;
  4542. }
  4543. // We are done with this array. Before we can parse a
  4544. // new value, we need to evaluate the new state first.
  4545. // By setting skip_to_state_evaluation to false, we
  4546. // are effectively jumping to the beginning of this if.
  4547. assert(not states.empty());
  4548. states.pop_back();
  4549. skip_to_state_evaluation = true;
  4550. continue;
  4551. }
  4552. else
  4553. {
  4554. return sax->parse_error(m_lexer.get_position(),
  4555. m_lexer.get_token_string(),
  4556. parse_error::create(101, m_lexer.get_position(),
  4557. exception_message(token_type::end_array, "array")));
  4558. }
  4559. }
  4560. else // object
  4561. {
  4562. // comma -> next value
  4563. if (get_token() == token_type::value_separator)
  4564. {
  4565. // parse key
  4566. if (JSON_UNLIKELY(get_token() != token_type::value_string))
  4567. {
  4568. return sax->parse_error(m_lexer.get_position(),
  4569. m_lexer.get_token_string(),
  4570. parse_error::create(101, m_lexer.get_position(),
  4571. exception_message(token_type::value_string, "object key")));
  4572. }
  4573. else
  4574. {
  4575. if (JSON_UNLIKELY(not sax->key(m_lexer.get_string())))
  4576. {
  4577. return false;
  4578. }
  4579. }
  4580. // parse separator (:)
  4581. if (JSON_UNLIKELY(get_token() != token_type::name_separator))
  4582. {
  4583. return sax->parse_error(m_lexer.get_position(),
  4584. m_lexer.get_token_string(),
  4585. parse_error::create(101, m_lexer.get_position(),
  4586. exception_message(token_type::name_separator, "object separator")));
  4587. }
  4588. // parse values
  4589. get_token();
  4590. continue;
  4591. }
  4592. // closing }
  4593. if (JSON_LIKELY(last_token == token_type::end_object))
  4594. {
  4595. if (JSON_UNLIKELY(not sax->end_object()))
  4596. {
  4597. return false;
  4598. }
  4599. // We are done with this object. Before we can parse a
  4600. // new value, we need to evaluate the new state first.
  4601. // By setting skip_to_state_evaluation to false, we
  4602. // are effectively jumping to the beginning of this if.
  4603. assert(not states.empty());
  4604. states.pop_back();
  4605. skip_to_state_evaluation = true;
  4606. continue;
  4607. }
  4608. else
  4609. {
  4610. return sax->parse_error(m_lexer.get_position(),
  4611. m_lexer.get_token_string(),
  4612. parse_error::create(101, m_lexer.get_position(),
  4613. exception_message(token_type::end_object, "object")));
  4614. }
  4615. }
  4616. }
  4617. }
  4618. }
  4619. /// get next token from lexer
  4620. token_type get_token()
  4621. {
  4622. return (last_token = m_lexer.scan());
  4623. }
  4624. std::string exception_message(const token_type expected, const std::string& context)
  4625. {
  4626. std::string error_msg = "syntax error ";
  4627. if (not context.empty())
  4628. {
  4629. error_msg += "while parsing " + context + " ";
  4630. }
  4631. error_msg += "- ";
  4632. if (last_token == token_type::parse_error)
  4633. {
  4634. error_msg += std::string(m_lexer.get_error_message()) + "; last read: '" +
  4635. m_lexer.get_token_string() + "'";
  4636. }
  4637. else
  4638. {
  4639. error_msg += "unexpected " + std::string(lexer_t::token_type_name(last_token));
  4640. }
  4641. if (expected != token_type::uninitialized)
  4642. {
  4643. error_msg += "; expected " + std::string(lexer_t::token_type_name(expected));
  4644. }
  4645. return error_msg;
  4646. }
  4647. private:
  4648. /// callback function
  4649. const parser_callback_t callback = nullptr;
  4650. /// the type of the last read token
  4651. token_type last_token = token_type::uninitialized;
  4652. /// the lexer
  4653. lexer_t m_lexer;
  4654. /// whether to throw exceptions in case of errors
  4655. const bool allow_exceptions = true;
  4656. };
  4657. } // namespace detail
  4658. } // namespace nlohmann
  4659. // #include <nlohmann/detail/iterators/primitive_iterator.hpp>
  4660. #include <cstddef> // ptrdiff_t
  4661. #include <limits> // numeric_limits
  4662. namespace nlohmann
  4663. {
  4664. namespace detail
  4665. {
  4666. /*
  4667. @brief an iterator for primitive JSON types
  4668. This class models an iterator for primitive JSON types (boolean, number,
  4669. string). It's only purpose is to allow the iterator/const_iterator classes
  4670. to "iterate" over primitive values. Internally, the iterator is modeled by
  4671. a `difference_type` variable. Value begin_value (`0`) models the begin,
  4672. end_value (`1`) models past the end.
  4673. */
  4674. class primitive_iterator_t
  4675. {
  4676. private:
  4677. using difference_type = std::ptrdiff_t;
  4678. static constexpr difference_type begin_value = 0;
  4679. static constexpr difference_type end_value = begin_value + 1;
  4680. /// iterator as signed integer type
  4681. difference_type m_it = (std::numeric_limits<std::ptrdiff_t>::min)();
  4682. public:
  4683. constexpr difference_type get_value() const noexcept
  4684. {
  4685. return m_it;
  4686. }
  4687. /// set iterator to a defined beginning
  4688. void set_begin() noexcept
  4689. {
  4690. m_it = begin_value;
  4691. }
  4692. /// set iterator to a defined past the end
  4693. void set_end() noexcept
  4694. {
  4695. m_it = end_value;
  4696. }
  4697. /// return whether the iterator can be dereferenced
  4698. constexpr bool is_begin() const noexcept
  4699. {
  4700. return m_it == begin_value;
  4701. }
  4702. /// return whether the iterator is at end
  4703. constexpr bool is_end() const noexcept
  4704. {
  4705. return m_it == end_value;
  4706. }
  4707. friend constexpr bool operator==(primitive_iterator_t lhs, primitive_iterator_t rhs) noexcept
  4708. {
  4709. return lhs.m_it == rhs.m_it;
  4710. }
  4711. friend constexpr bool operator<(primitive_iterator_t lhs, primitive_iterator_t rhs) noexcept
  4712. {
  4713. return lhs.m_it < rhs.m_it;
  4714. }
  4715. primitive_iterator_t operator+(difference_type n) noexcept
  4716. {
  4717. auto result = *this;
  4718. result += n;
  4719. return result;
  4720. }
  4721. friend constexpr difference_type operator-(primitive_iterator_t lhs, primitive_iterator_t rhs) noexcept
  4722. {
  4723. return lhs.m_it - rhs.m_it;
  4724. }
  4725. primitive_iterator_t& operator++() noexcept
  4726. {
  4727. ++m_it;
  4728. return *this;
  4729. }
  4730. primitive_iterator_t const operator++(int) noexcept
  4731. {
  4732. auto result = *this;
  4733. ++m_it;
  4734. return result;
  4735. }
  4736. primitive_iterator_t& operator--() noexcept
  4737. {
  4738. --m_it;
  4739. return *this;
  4740. }
  4741. primitive_iterator_t const operator--(int) noexcept
  4742. {
  4743. auto result = *this;
  4744. --m_it;
  4745. return result;
  4746. }
  4747. primitive_iterator_t& operator+=(difference_type n) noexcept
  4748. {
  4749. m_it += n;
  4750. return *this;
  4751. }
  4752. primitive_iterator_t& operator-=(difference_type n) noexcept
  4753. {
  4754. m_it -= n;
  4755. return *this;
  4756. }
  4757. };
  4758. } // namespace detail
  4759. } // namespace nlohmann
  4760. // #include <nlohmann/detail/iterators/internal_iterator.hpp>
  4761. // #include <nlohmann/detail/iterators/primitive_iterator.hpp>
  4762. namespace nlohmann
  4763. {
  4764. namespace detail
  4765. {
  4766. /*!
  4767. @brief an iterator value
  4768. @note This structure could easily be a union, but MSVC currently does not allow
  4769. unions members with complex constructors, see https://github.com/nlohmann/json/pull/105.
  4770. */
  4771. template<typename BasicJsonType> struct internal_iterator
  4772. {
  4773. /// iterator for JSON objects
  4774. typename BasicJsonType::object_t::iterator object_iterator {};
  4775. /// iterator for JSON arrays
  4776. typename BasicJsonType::array_t::iterator array_iterator {};
  4777. /// generic iterator for all other types
  4778. primitive_iterator_t primitive_iterator {};
  4779. };
  4780. } // namespace detail
  4781. } // namespace nlohmann
  4782. // #include <nlohmann/detail/iterators/iter_impl.hpp>
  4783. #include <ciso646> // not
  4784. #include <iterator> // iterator, random_access_iterator_tag, bidirectional_iterator_tag, advance, next
  4785. #include <type_traits> // conditional, is_const, remove_const
  4786. // #include <nlohmann/detail/exceptions.hpp>
  4787. // #include <nlohmann/detail/iterators/internal_iterator.hpp>
  4788. // #include <nlohmann/detail/iterators/primitive_iterator.hpp>
  4789. // #include <nlohmann/detail/macro_scope.hpp>
  4790. // #include <nlohmann/detail/meta/cpp_future.hpp>
  4791. // #include <nlohmann/detail/value_t.hpp>
  4792. namespace nlohmann
  4793. {
  4794. namespace detail
  4795. {
  4796. // forward declare, to be able to friend it later on
  4797. template<typename IteratorType> class iteration_proxy;
  4798. template<typename IteratorType> class iteration_proxy_value;
  4799. /*!
  4800. @brief a template for a bidirectional iterator for the @ref basic_json class
  4801. This class implements a both iterators (iterator and const_iterator) for the
  4802. @ref basic_json class.
  4803. @note An iterator is called *initialized* when a pointer to a JSON value has
  4804. been set (e.g., by a constructor or a copy assignment). If the iterator is
  4805. default-constructed, it is *uninitialized* and most methods are undefined.
  4806. **The library uses assertions to detect calls on uninitialized iterators.**
  4807. @requirement The class satisfies the following concept requirements:
  4808. -
  4809. [BidirectionalIterator](https://en.cppreference.com/w/cpp/named_req/BidirectionalIterator):
  4810. The iterator that can be moved can be moved in both directions (i.e.
  4811. incremented and decremented).
  4812. @since version 1.0.0, simplified in version 2.0.9, change to bidirectional
  4813. iterators in version 3.0.0 (see https://github.com/nlohmann/json/issues/593)
  4814. */
  4815. template<typename BasicJsonType>
  4816. class iter_impl
  4817. {
  4818. /// allow basic_json to access private members
  4819. friend iter_impl<typename std::conditional<std::is_const<BasicJsonType>::value, typename std::remove_const<BasicJsonType>::type, const BasicJsonType>::type>;
  4820. friend BasicJsonType;
  4821. friend iteration_proxy<iter_impl>;
  4822. friend iteration_proxy_value<iter_impl>;
  4823. using object_t = typename BasicJsonType::object_t;
  4824. using array_t = typename BasicJsonType::array_t;
  4825. // make sure BasicJsonType is basic_json or const basic_json
  4826. static_assert(is_basic_json<typename std::remove_const<BasicJsonType>::type>::value,
  4827. "iter_impl only accepts (const) basic_json");
  4828. public:
  4829. /// The std::iterator class template (used as a base class to provide typedefs) is deprecated in C++17.
  4830. /// The C++ Standard has never required user-defined iterators to derive from std::iterator.
  4831. /// A user-defined iterator should provide publicly accessible typedefs named
  4832. /// iterator_category, value_type, difference_type, pointer, and reference.
  4833. /// Note that value_type is required to be non-const, even for constant iterators.
  4834. using iterator_category = std::bidirectional_iterator_tag;
  4835. /// the type of the values when the iterator is dereferenced
  4836. using value_type = typename BasicJsonType::value_type;
  4837. /// a type to represent differences between iterators
  4838. using difference_type = typename BasicJsonType::difference_type;
  4839. /// defines a pointer to the type iterated over (value_type)
  4840. using pointer = typename std::conditional<std::is_const<BasicJsonType>::value,
  4841. typename BasicJsonType::const_pointer,
  4842. typename BasicJsonType::pointer>::type;
  4843. /// defines a reference to the type iterated over (value_type)
  4844. using reference =
  4845. typename std::conditional<std::is_const<BasicJsonType>::value,
  4846. typename BasicJsonType::const_reference,
  4847. typename BasicJsonType::reference>::type;
  4848. /// default constructor
  4849. iter_impl() = default;
  4850. /*!
  4851. @brief constructor for a given JSON instance
  4852. @param[in] object pointer to a JSON object for this iterator
  4853. @pre object != nullptr
  4854. @post The iterator is initialized; i.e. `m_object != nullptr`.
  4855. */
  4856. explicit iter_impl(pointer object) noexcept : m_object(object)
  4857. {
  4858. assert(m_object != nullptr);
  4859. switch (m_object->m_type)
  4860. {
  4861. case value_t::object:
  4862. {
  4863. m_it.object_iterator = typename object_t::iterator();
  4864. break;
  4865. }
  4866. case value_t::array:
  4867. {
  4868. m_it.array_iterator = typename array_t::iterator();
  4869. break;
  4870. }
  4871. default:
  4872. {
  4873. m_it.primitive_iterator = primitive_iterator_t();
  4874. break;
  4875. }
  4876. }
  4877. }
  4878. /*!
  4879. @note The conventional copy constructor and copy assignment are implicitly
  4880. defined. Combined with the following converting constructor and
  4881. assignment, they support: (1) copy from iterator to iterator, (2)
  4882. copy from const iterator to const iterator, and (3) conversion from
  4883. iterator to const iterator. However conversion from const iterator
  4884. to iterator is not defined.
  4885. */
  4886. /*!
  4887. @brief converting constructor
  4888. @param[in] other non-const iterator to copy from
  4889. @note It is not checked whether @a other is initialized.
  4890. */
  4891. iter_impl(const iter_impl<typename std::remove_const<BasicJsonType>::type>& other) noexcept
  4892. : m_object(other.m_object), m_it(other.m_it) {}
  4893. /*!
  4894. @brief converting assignment
  4895. @param[in,out] other non-const iterator to copy from
  4896. @return const/non-const iterator
  4897. @note It is not checked whether @a other is initialized.
  4898. */
  4899. iter_impl& operator=(const iter_impl<typename std::remove_const<BasicJsonType>::type>& other) noexcept
  4900. {
  4901. m_object = other.m_object;
  4902. m_it = other.m_it;
  4903. return *this;
  4904. }
  4905. private:
  4906. /*!
  4907. @brief set the iterator to the first value
  4908. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  4909. */
  4910. void set_begin() noexcept
  4911. {
  4912. assert(m_object != nullptr);
  4913. switch (m_object->m_type)
  4914. {
  4915. case value_t::object:
  4916. {
  4917. m_it.object_iterator = m_object->m_value.object->begin();
  4918. break;
  4919. }
  4920. case value_t::array:
  4921. {
  4922. m_it.array_iterator = m_object->m_value.array->begin();
  4923. break;
  4924. }
  4925. case value_t::null:
  4926. {
  4927. // set to end so begin()==end() is true: null is empty
  4928. m_it.primitive_iterator.set_end();
  4929. break;
  4930. }
  4931. default:
  4932. {
  4933. m_it.primitive_iterator.set_begin();
  4934. break;
  4935. }
  4936. }
  4937. }
  4938. /*!
  4939. @brief set the iterator past the last value
  4940. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  4941. */
  4942. void set_end() noexcept
  4943. {
  4944. assert(m_object != nullptr);
  4945. switch (m_object->m_type)
  4946. {
  4947. case value_t::object:
  4948. {
  4949. m_it.object_iterator = m_object->m_value.object->end();
  4950. break;
  4951. }
  4952. case value_t::array:
  4953. {
  4954. m_it.array_iterator = m_object->m_value.array->end();
  4955. break;
  4956. }
  4957. default:
  4958. {
  4959. m_it.primitive_iterator.set_end();
  4960. break;
  4961. }
  4962. }
  4963. }
  4964. public:
  4965. /*!
  4966. @brief return a reference to the value pointed to by the iterator
  4967. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  4968. */
  4969. reference operator*() const
  4970. {
  4971. assert(m_object != nullptr);
  4972. switch (m_object->m_type)
  4973. {
  4974. case value_t::object:
  4975. {
  4976. assert(m_it.object_iterator != m_object->m_value.object->end());
  4977. return m_it.object_iterator->second;
  4978. }
  4979. case value_t::array:
  4980. {
  4981. assert(m_it.array_iterator != m_object->m_value.array->end());
  4982. return *m_it.array_iterator;
  4983. }
  4984. case value_t::null:
  4985. JSON_THROW(invalid_iterator::create(214, "cannot get value"));
  4986. default:
  4987. {
  4988. if (JSON_LIKELY(m_it.primitive_iterator.is_begin()))
  4989. {
  4990. return *m_object;
  4991. }
  4992. JSON_THROW(invalid_iterator::create(214, "cannot get value"));
  4993. }
  4994. }
  4995. }
  4996. /*!
  4997. @brief dereference the iterator
  4998. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  4999. */
  5000. pointer operator->() const
  5001. {
  5002. assert(m_object != nullptr);
  5003. switch (m_object->m_type)
  5004. {
  5005. case value_t::object:
  5006. {
  5007. assert(m_it.object_iterator != m_object->m_value.object->end());
  5008. return &(m_it.object_iterator->second);
  5009. }
  5010. case value_t::array:
  5011. {
  5012. assert(m_it.array_iterator != m_object->m_value.array->end());
  5013. return &*m_it.array_iterator;
  5014. }
  5015. default:
  5016. {
  5017. if (JSON_LIKELY(m_it.primitive_iterator.is_begin()))
  5018. {
  5019. return m_object;
  5020. }
  5021. JSON_THROW(invalid_iterator::create(214, "cannot get value"));
  5022. }
  5023. }
  5024. }
  5025. /*!
  5026. @brief post-increment (it++)
  5027. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  5028. */
  5029. iter_impl const operator++(int)
  5030. {
  5031. auto result = *this;
  5032. ++(*this);
  5033. return result;
  5034. }
  5035. /*!
  5036. @brief pre-increment (++it)
  5037. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  5038. */
  5039. iter_impl& operator++()
  5040. {
  5041. assert(m_object != nullptr);
  5042. switch (m_object->m_type)
  5043. {
  5044. case value_t::object:
  5045. {
  5046. std::advance(m_it.object_iterator, 1);
  5047. break;
  5048. }
  5049. case value_t::array:
  5050. {
  5051. std::advance(m_it.array_iterator, 1);
  5052. break;
  5053. }
  5054. default:
  5055. {
  5056. ++m_it.primitive_iterator;
  5057. break;
  5058. }
  5059. }
  5060. return *this;
  5061. }
  5062. /*!
  5063. @brief post-decrement (it--)
  5064. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  5065. */
  5066. iter_impl const operator--(int)
  5067. {
  5068. auto result = *this;
  5069. --(*this);
  5070. return result;
  5071. }
  5072. /*!
  5073. @brief pre-decrement (--it)
  5074. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  5075. */
  5076. iter_impl& operator--()
  5077. {
  5078. assert(m_object != nullptr);
  5079. switch (m_object->m_type)
  5080. {
  5081. case value_t::object:
  5082. {
  5083. std::advance(m_it.object_iterator, -1);
  5084. break;
  5085. }
  5086. case value_t::array:
  5087. {
  5088. std::advance(m_it.array_iterator, -1);
  5089. break;
  5090. }
  5091. default:
  5092. {
  5093. --m_it.primitive_iterator;
  5094. break;
  5095. }
  5096. }
  5097. return *this;
  5098. }
  5099. /*!
  5100. @brief comparison: equal
  5101. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  5102. */
  5103. bool operator==(const iter_impl& other) const
  5104. {
  5105. // if objects are not the same, the comparison is undefined
  5106. if (JSON_UNLIKELY(m_object != other.m_object))
  5107. {
  5108. JSON_THROW(invalid_iterator::create(212, "cannot compare iterators of different containers"));
  5109. }
  5110. assert(m_object != nullptr);
  5111. switch (m_object->m_type)
  5112. {
  5113. case value_t::object:
  5114. return (m_it.object_iterator == other.m_it.object_iterator);
  5115. case value_t::array:
  5116. return (m_it.array_iterator == other.m_it.array_iterator);
  5117. default:
  5118. return (m_it.primitive_iterator == other.m_it.primitive_iterator);
  5119. }
  5120. }
  5121. /*!
  5122. @brief comparison: not equal
  5123. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  5124. */
  5125. bool operator!=(const iter_impl& other) const
  5126. {
  5127. return not operator==(other);
  5128. }
  5129. /*!
  5130. @brief comparison: smaller
  5131. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  5132. */
  5133. bool operator<(const iter_impl& other) const
  5134. {
  5135. // if objects are not the same, the comparison is undefined
  5136. if (JSON_UNLIKELY(m_object != other.m_object))
  5137. {
  5138. JSON_THROW(invalid_iterator::create(212, "cannot compare iterators of different containers"));
  5139. }
  5140. assert(m_object != nullptr);
  5141. switch (m_object->m_type)
  5142. {
  5143. case value_t::object:
  5144. JSON_THROW(invalid_iterator::create(213, "cannot compare order of object iterators"));
  5145. case value_t::array:
  5146. return (m_it.array_iterator < other.m_it.array_iterator);
  5147. default:
  5148. return (m_it.primitive_iterator < other.m_it.primitive_iterator);
  5149. }
  5150. }
  5151. /*!
  5152. @brief comparison: less than or equal
  5153. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  5154. */
  5155. bool operator<=(const iter_impl& other) const
  5156. {
  5157. return not other.operator < (*this);
  5158. }
  5159. /*!
  5160. @brief comparison: greater than
  5161. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  5162. */
  5163. bool operator>(const iter_impl& other) const
  5164. {
  5165. return not operator<=(other);
  5166. }
  5167. /*!
  5168. @brief comparison: greater than or equal
  5169. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  5170. */
  5171. bool operator>=(const iter_impl& other) const
  5172. {
  5173. return not operator<(other);
  5174. }
  5175. /*!
  5176. @brief add to iterator
  5177. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  5178. */
  5179. iter_impl& operator+=(difference_type i)
  5180. {
  5181. assert(m_object != nullptr);
  5182. switch (m_object->m_type)
  5183. {
  5184. case value_t::object:
  5185. JSON_THROW(invalid_iterator::create(209, "cannot use offsets with object iterators"));
  5186. case value_t::array:
  5187. {
  5188. std::advance(m_it.array_iterator, i);
  5189. break;
  5190. }
  5191. default:
  5192. {
  5193. m_it.primitive_iterator += i;
  5194. break;
  5195. }
  5196. }
  5197. return *this;
  5198. }
  5199. /*!
  5200. @brief subtract from iterator
  5201. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  5202. */
  5203. iter_impl& operator-=(difference_type i)
  5204. {
  5205. return operator+=(-i);
  5206. }
  5207. /*!
  5208. @brief add to iterator
  5209. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  5210. */
  5211. iter_impl operator+(difference_type i) const
  5212. {
  5213. auto result = *this;
  5214. result += i;
  5215. return result;
  5216. }
  5217. /*!
  5218. @brief addition of distance and iterator
  5219. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  5220. */
  5221. friend iter_impl operator+(difference_type i, const iter_impl& it)
  5222. {
  5223. auto result = it;
  5224. result += i;
  5225. return result;
  5226. }
  5227. /*!
  5228. @brief subtract from iterator
  5229. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  5230. */
  5231. iter_impl operator-(difference_type i) const
  5232. {
  5233. auto result = *this;
  5234. result -= i;
  5235. return result;
  5236. }
  5237. /*!
  5238. @brief return difference
  5239. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  5240. */
  5241. difference_type operator-(const iter_impl& other) const
  5242. {
  5243. assert(m_object != nullptr);
  5244. switch (m_object->m_type)
  5245. {
  5246. case value_t::object:
  5247. JSON_THROW(invalid_iterator::create(209, "cannot use offsets with object iterators"));
  5248. case value_t::array:
  5249. return m_it.array_iterator - other.m_it.array_iterator;
  5250. default:
  5251. return m_it.primitive_iterator - other.m_it.primitive_iterator;
  5252. }
  5253. }
  5254. /*!
  5255. @brief access to successor
  5256. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  5257. */
  5258. reference operator[](difference_type n) const
  5259. {
  5260. assert(m_object != nullptr);
  5261. switch (m_object->m_type)
  5262. {
  5263. case value_t::object:
  5264. JSON_THROW(invalid_iterator::create(208, "cannot use operator[] for object iterators"));
  5265. case value_t::array:
  5266. return *std::next(m_it.array_iterator, n);
  5267. case value_t::null:
  5268. JSON_THROW(invalid_iterator::create(214, "cannot get value"));
  5269. default:
  5270. {
  5271. if (JSON_LIKELY(m_it.primitive_iterator.get_value() == -n))
  5272. {
  5273. return *m_object;
  5274. }
  5275. JSON_THROW(invalid_iterator::create(214, "cannot get value"));
  5276. }
  5277. }
  5278. }
  5279. /*!
  5280. @brief return the key of an object iterator
  5281. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  5282. */
  5283. const typename object_t::key_type& key() const
  5284. {
  5285. assert(m_object != nullptr);
  5286. if (JSON_LIKELY(m_object->is_object()))
  5287. {
  5288. return m_it.object_iterator->first;
  5289. }
  5290. JSON_THROW(invalid_iterator::create(207, "cannot use key() for non-object iterators"));
  5291. }
  5292. /*!
  5293. @brief return the value of an iterator
  5294. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  5295. */
  5296. reference value() const
  5297. {
  5298. return operator*();
  5299. }
  5300. private:
  5301. /// associated JSON instance
  5302. pointer m_object = nullptr;
  5303. /// the actual iterator of the associated instance
  5304. internal_iterator<typename std::remove_const<BasicJsonType>::type> m_it;
  5305. };
  5306. } // namespace detail
  5307. } // namespace nlohmann
  5308. // #include <nlohmann/detail/iterators/iteration_proxy.hpp>
  5309. // #include <nlohmann/detail/iterators/json_reverse_iterator.hpp>
  5310. #include <cstddef> // ptrdiff_t
  5311. #include <iterator> // reverse_iterator
  5312. #include <utility> // declval
  5313. namespace nlohmann
  5314. {
  5315. namespace detail
  5316. {
  5317. //////////////////////
  5318. // reverse_iterator //
  5319. //////////////////////
  5320. /*!
  5321. @brief a template for a reverse iterator class
  5322. @tparam Base the base iterator type to reverse. Valid types are @ref
  5323. iterator (to create @ref reverse_iterator) and @ref const_iterator (to
  5324. create @ref const_reverse_iterator).
  5325. @requirement The class satisfies the following concept requirements:
  5326. -
  5327. [BidirectionalIterator](https://en.cppreference.com/w/cpp/named_req/BidirectionalIterator):
  5328. The iterator that can be moved can be moved in both directions (i.e.
  5329. incremented and decremented).
  5330. - [OutputIterator](https://en.cppreference.com/w/cpp/named_req/OutputIterator):
  5331. It is possible to write to the pointed-to element (only if @a Base is
  5332. @ref iterator).
  5333. @since version 1.0.0
  5334. */
  5335. template<typename Base>
  5336. class json_reverse_iterator : public std::reverse_iterator<Base>
  5337. {
  5338. public:
  5339. using difference_type = std::ptrdiff_t;
  5340. /// shortcut to the reverse iterator adapter
  5341. using base_iterator = std::reverse_iterator<Base>;
  5342. /// the reference type for the pointed-to element
  5343. using reference = typename Base::reference;
  5344. /// create reverse iterator from iterator
  5345. explicit json_reverse_iterator(const typename base_iterator::iterator_type& it) noexcept
  5346. : base_iterator(it) {}
  5347. /// create reverse iterator from base class
  5348. explicit json_reverse_iterator(const base_iterator& it) noexcept : base_iterator(it) {}
  5349. /// post-increment (it++)
  5350. json_reverse_iterator const operator++(int)
  5351. {
  5352. return static_cast<json_reverse_iterator>(base_iterator::operator++(1));
  5353. }
  5354. /// pre-increment (++it)
  5355. json_reverse_iterator& operator++()
  5356. {
  5357. return static_cast<json_reverse_iterator&>(base_iterator::operator++());
  5358. }
  5359. /// post-decrement (it--)
  5360. json_reverse_iterator const operator--(int)
  5361. {
  5362. return static_cast<json_reverse_iterator>(base_iterator::operator--(1));
  5363. }
  5364. /// pre-decrement (--it)
  5365. json_reverse_iterator& operator--()
  5366. {
  5367. return static_cast<json_reverse_iterator&>(base_iterator::operator--());
  5368. }
  5369. /// add to iterator
  5370. json_reverse_iterator& operator+=(difference_type i)
  5371. {
  5372. return static_cast<json_reverse_iterator&>(base_iterator::operator+=(i));
  5373. }
  5374. /// add to iterator
  5375. json_reverse_iterator operator+(difference_type i) const
  5376. {
  5377. return static_cast<json_reverse_iterator>(base_iterator::operator+(i));
  5378. }
  5379. /// subtract from iterator
  5380. json_reverse_iterator operator-(difference_type i) const
  5381. {
  5382. return static_cast<json_reverse_iterator>(base_iterator::operator-(i));
  5383. }
  5384. /// return difference
  5385. difference_type operator-(const json_reverse_iterator& other) const
  5386. {
  5387. return base_iterator(*this) - base_iterator(other);
  5388. }
  5389. /// access to successor
  5390. reference operator[](difference_type n) const
  5391. {
  5392. return *(this->operator+(n));
  5393. }
  5394. /// return the key of an object iterator
  5395. auto key() const -> decltype(std::declval<Base>().key())
  5396. {
  5397. auto it = --this->base();
  5398. return it.key();
  5399. }
  5400. /// return the value of an iterator
  5401. reference value() const
  5402. {
  5403. auto it = --this->base();
  5404. return it.operator * ();
  5405. }
  5406. };
  5407. } // namespace detail
  5408. } // namespace nlohmann
  5409. // #include <nlohmann/detail/output/output_adapters.hpp>
  5410. #include <algorithm> // copy
  5411. #include <cstddef> // size_t
  5412. #include <ios> // streamsize
  5413. #include <iterator> // back_inserter
  5414. #include <memory> // shared_ptr, make_shared
  5415. #include <ostream> // basic_ostream
  5416. #include <string> // basic_string
  5417. #include <vector> // vector
  5418. namespace nlohmann
  5419. {
  5420. namespace detail
  5421. {
  5422. /// abstract output adapter interface
  5423. template<typename CharType> struct output_adapter_protocol
  5424. {
  5425. virtual void write_character(CharType c) = 0;
  5426. virtual void write_characters(const CharType* s, std::size_t length) = 0;
  5427. virtual ~output_adapter_protocol() = default;
  5428. };
  5429. /// a type to simplify interfaces
  5430. template<typename CharType>
  5431. using output_adapter_t = std::shared_ptr<output_adapter_protocol<CharType>>;
  5432. /// output adapter for byte vectors
  5433. template<typename CharType>
  5434. class output_vector_adapter : public output_adapter_protocol<CharType>
  5435. {
  5436. public:
  5437. explicit output_vector_adapter(std::vector<CharType>& vec) noexcept
  5438. : v(vec)
  5439. {}
  5440. void write_character(CharType c) override
  5441. {
  5442. v.push_back(c);
  5443. }
  5444. void write_characters(const CharType* s, std::size_t length) override
  5445. {
  5446. std::copy(s, s + length, std::back_inserter(v));
  5447. }
  5448. private:
  5449. std::vector<CharType>& v;
  5450. };
  5451. /// output adapter for output streams
  5452. template<typename CharType>
  5453. class output_stream_adapter : public output_adapter_protocol<CharType>
  5454. {
  5455. public:
  5456. explicit output_stream_adapter(std::basic_ostream<CharType>& s) noexcept
  5457. : stream(s)
  5458. {}
  5459. void write_character(CharType c) override
  5460. {
  5461. stream.put(c);
  5462. }
  5463. void write_characters(const CharType* s, std::size_t length) override
  5464. {
  5465. stream.write(s, static_cast<std::streamsize>(length));
  5466. }
  5467. private:
  5468. std::basic_ostream<CharType>& stream;
  5469. };
  5470. /// output adapter for basic_string
  5471. template<typename CharType, typename StringType = std::basic_string<CharType>>
  5472. class output_string_adapter : public output_adapter_protocol<CharType>
  5473. {
  5474. public:
  5475. explicit output_string_adapter(StringType& s) noexcept
  5476. : str(s)
  5477. {}
  5478. void write_character(CharType c) override
  5479. {
  5480. str.push_back(c);
  5481. }
  5482. void write_characters(const CharType* s, std::size_t length) override
  5483. {
  5484. str.append(s, length);
  5485. }
  5486. private:
  5487. StringType& str;
  5488. };
  5489. template<typename CharType, typename StringType = std::basic_string<CharType>>
  5490. class output_adapter
  5491. {
  5492. public:
  5493. output_adapter(std::vector<CharType>& vec)
  5494. : oa(std::make_shared<output_vector_adapter<CharType>>(vec)) {}
  5495. output_adapter(std::basic_ostream<CharType>& s)
  5496. : oa(std::make_shared<output_stream_adapter<CharType>>(s)) {}
  5497. output_adapter(StringType& s)
  5498. : oa(std::make_shared<output_string_adapter<CharType, StringType>>(s)) {}
  5499. operator output_adapter_t<CharType>()
  5500. {
  5501. return oa;
  5502. }
  5503. private:
  5504. output_adapter_t<CharType> oa = nullptr;
  5505. };
  5506. } // namespace detail
  5507. } // namespace nlohmann
  5508. // #include <nlohmann/detail/input/binary_reader.hpp>
  5509. #include <algorithm> // generate_n
  5510. #include <array> // array
  5511. #include <cassert> // assert
  5512. #include <cmath> // ldexp
  5513. #include <cstddef> // size_t
  5514. #include <cstdint> // uint8_t, uint16_t, uint32_t, uint64_t
  5515. #include <cstdio> // snprintf
  5516. #include <cstring> // memcpy
  5517. #include <iterator> // back_inserter
  5518. #include <limits> // numeric_limits
  5519. #include <string> // char_traits, string
  5520. #include <utility> // make_pair, move
  5521. // #include <nlohmann/detail/input/input_adapters.hpp>
  5522. // #include <nlohmann/detail/input/json_sax.hpp>
  5523. // #include <nlohmann/detail/exceptions.hpp>
  5524. // #include <nlohmann/detail/macro_scope.hpp>
  5525. // #include <nlohmann/detail/meta/is_sax.hpp>
  5526. // #include <nlohmann/detail/value_t.hpp>
  5527. namespace nlohmann
  5528. {
  5529. namespace detail
  5530. {
  5531. ///////////////////
  5532. // binary reader //
  5533. ///////////////////
  5534. /*!
  5535. @brief deserialization of CBOR, MessagePack, and UBJSON values
  5536. */
  5537. template<typename BasicJsonType, typename SAX = json_sax_dom_parser<BasicJsonType>>
  5538. class binary_reader
  5539. {
  5540. using number_integer_t = typename BasicJsonType::number_integer_t;
  5541. using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
  5542. using number_float_t = typename BasicJsonType::number_float_t;
  5543. using string_t = typename BasicJsonType::string_t;
  5544. using json_sax_t = SAX;
  5545. public:
  5546. /*!
  5547. @brief create a binary reader
  5548. @param[in] adapter input adapter to read from
  5549. */
  5550. explicit binary_reader(input_adapter_t adapter) : ia(std::move(adapter))
  5551. {
  5552. (void)detail::is_sax_static_asserts<SAX, BasicJsonType> {};
  5553. assert(ia);
  5554. }
  5555. /*!
  5556. @param[in] format the binary format to parse
  5557. @param[in] sax_ a SAX event processor
  5558. @param[in] strict whether to expect the input to be consumed completed
  5559. @return
  5560. */
  5561. bool sax_parse(const input_format_t format,
  5562. json_sax_t* sax_,
  5563. const bool strict = true)
  5564. {
  5565. sax = sax_;
  5566. bool result = false;
  5567. switch (format)
  5568. {
  5569. case input_format_t::bson:
  5570. result = parse_bson_internal();
  5571. break;
  5572. case input_format_t::cbor:
  5573. result = parse_cbor_internal();
  5574. break;
  5575. case input_format_t::msgpack:
  5576. result = parse_msgpack_internal();
  5577. break;
  5578. case input_format_t::ubjson:
  5579. result = parse_ubjson_internal();
  5580. break;
  5581. // LCOV_EXCL_START
  5582. default:
  5583. assert(false);
  5584. // LCOV_EXCL_STOP
  5585. }
  5586. // strict mode: next byte must be EOF
  5587. if (result and strict)
  5588. {
  5589. if (format == input_format_t::ubjson)
  5590. {
  5591. get_ignore_noop();
  5592. }
  5593. else
  5594. {
  5595. get();
  5596. }
  5597. if (JSON_UNLIKELY(current != std::char_traits<char>::eof()))
  5598. {
  5599. return sax->parse_error(chars_read, get_token_string(),
  5600. parse_error::create(110, chars_read, exception_message(format, "expected end of input; last byte: 0x" + get_token_string(), "value")));
  5601. }
  5602. }
  5603. return result;
  5604. }
  5605. /*!
  5606. @brief determine system byte order
  5607. @return true if and only if system's byte order is little endian
  5608. @note from http://stackoverflow.com/a/1001328/266378
  5609. */
  5610. static constexpr bool little_endianess(int num = 1) noexcept
  5611. {
  5612. return (*reinterpret_cast<char*>(&num) == 1);
  5613. }
  5614. private:
  5615. //////////
  5616. // BSON //
  5617. //////////
  5618. /*!
  5619. @brief Reads in a BSON-object and passes it to the SAX-parser.
  5620. @return whether a valid BSON-value was passed to the SAX parser
  5621. */
  5622. bool parse_bson_internal()
  5623. {
  5624. std::int32_t document_size;
  5625. get_number<std::int32_t, true>(input_format_t::bson, document_size);
  5626. if (JSON_UNLIKELY(not sax->start_object(std::size_t(-1))))
  5627. {
  5628. return false;
  5629. }
  5630. if (JSON_UNLIKELY(not parse_bson_element_list(/*is_array*/false)))
  5631. {
  5632. return false;
  5633. }
  5634. return sax->end_object();
  5635. }
  5636. /*!
  5637. @brief Parses a C-style string from the BSON input.
  5638. @param[in, out] result A reference to the string variable where the read
  5639. string is to be stored.
  5640. @return `true` if the \x00-byte indicating the end of the string was
  5641. encountered before the EOF; false` indicates an unexpected EOF.
  5642. */
  5643. bool get_bson_cstr(string_t& result)
  5644. {
  5645. auto out = std::back_inserter(result);
  5646. while (true)
  5647. {
  5648. get();
  5649. if (JSON_UNLIKELY(not unexpect_eof(input_format_t::bson, "cstring")))
  5650. {
  5651. return false;
  5652. }
  5653. if (current == 0x00)
  5654. {
  5655. return true;
  5656. }
  5657. *out++ = static_cast<char>(current);
  5658. }
  5659. return true;
  5660. }
  5661. /*!
  5662. @brief Parses a zero-terminated string of length @a len from the BSON
  5663. input.
  5664. @param[in] len The length (including the zero-byte at the end) of the
  5665. string to be read.
  5666. @param[in, out] result A reference to the string variable where the read
  5667. string is to be stored.
  5668. @tparam NumberType The type of the length @a len
  5669. @pre len >= 1
  5670. @return `true` if the string was successfully parsed
  5671. */
  5672. template<typename NumberType>
  5673. bool get_bson_string(const NumberType len, string_t& result)
  5674. {
  5675. if (JSON_UNLIKELY(len < 1))
  5676. {
  5677. auto last_token = get_token_string();
  5678. return sax->parse_error(chars_read, last_token, parse_error::create(112, chars_read, exception_message(input_format_t::bson, "string length must be at least 1, is " + std::to_string(len), "string")));
  5679. }
  5680. return get_string(input_format_t::bson, len - static_cast<NumberType>(1), result) and get() != std::char_traits<char>::eof();
  5681. }
  5682. /*!
  5683. @brief Read a BSON document element of the given @a element_type.
  5684. @param[in] element_type The BSON element type, c.f. http://bsonspec.org/spec.html
  5685. @param[in] element_type_parse_position The position in the input stream,
  5686. where the `element_type` was read.
  5687. @warning Not all BSON element types are supported yet. An unsupported
  5688. @a element_type will give rise to a parse_error.114:
  5689. Unsupported BSON record type 0x...
  5690. @return whether a valid BSON-object/array was passed to the SAX parser
  5691. */
  5692. bool parse_bson_element_internal(const int element_type,
  5693. const std::size_t element_type_parse_position)
  5694. {
  5695. switch (element_type)
  5696. {
  5697. case 0x01: // double
  5698. {
  5699. double number;
  5700. return get_number<double, true>(input_format_t::bson, number) and sax->number_float(static_cast<number_float_t>(number), "");
  5701. }
  5702. case 0x02: // string
  5703. {
  5704. std::int32_t len;
  5705. string_t value;
  5706. return get_number<std::int32_t, true>(input_format_t::bson, len) and get_bson_string(len, value) and sax->string(value);
  5707. }
  5708. case 0x03: // object
  5709. {
  5710. return parse_bson_internal();
  5711. }
  5712. case 0x04: // array
  5713. {
  5714. return parse_bson_array();
  5715. }
  5716. case 0x08: // boolean
  5717. {
  5718. return sax->boolean(get() != 0);
  5719. }
  5720. case 0x0A: // null
  5721. {
  5722. return sax->null();
  5723. }
  5724. case 0x10: // int32
  5725. {
  5726. std::int32_t value;
  5727. return get_number<std::int32_t, true>(input_format_t::bson, value) and sax->number_integer(value);
  5728. }
  5729. case 0x12: // int64
  5730. {
  5731. std::int64_t value;
  5732. return get_number<std::int64_t, true>(input_format_t::bson, value) and sax->number_integer(value);
  5733. }
  5734. default: // anything else not supported (yet)
  5735. {
  5736. char cr[3];
  5737. (std::snprintf)(cr, sizeof(cr), "%.2hhX", static_cast<unsigned char>(element_type));
  5738. return sax->parse_error(element_type_parse_position, std::string(cr), parse_error::create(114, element_type_parse_position, "Unsupported BSON record type 0x" + std::string(cr)));
  5739. }
  5740. }
  5741. }
  5742. /*!
  5743. @brief Read a BSON element list (as specified in the BSON-spec)
  5744. The same binary layout is used for objects and arrays, hence it must be
  5745. indicated with the argument @a is_array which one is expected
  5746. (true --> array, false --> object).
  5747. @param[in] is_array Determines if the element list being read is to be
  5748. treated as an object (@a is_array == false), or as an
  5749. array (@a is_array == true).
  5750. @return whether a valid BSON-object/array was passed to the SAX parser
  5751. */
  5752. bool parse_bson_element_list(const bool is_array)
  5753. {
  5754. string_t key;
  5755. while (int element_type = get())
  5756. {
  5757. if (JSON_UNLIKELY(not unexpect_eof(input_format_t::bson, "element list")))
  5758. {
  5759. return false;
  5760. }
  5761. const std::size_t element_type_parse_position = chars_read;
  5762. if (JSON_UNLIKELY(not get_bson_cstr(key)))
  5763. {
  5764. return false;
  5765. }
  5766. if (not is_array)
  5767. {
  5768. if (not sax->key(key))
  5769. {
  5770. return false;
  5771. }
  5772. }
  5773. if (JSON_UNLIKELY(not parse_bson_element_internal(element_type, element_type_parse_position)))
  5774. {
  5775. return false;
  5776. }
  5777. // get_bson_cstr only appends
  5778. key.clear();
  5779. }
  5780. return true;
  5781. }
  5782. /*!
  5783. @brief Reads an array from the BSON input and passes it to the SAX-parser.
  5784. @return whether a valid BSON-array was passed to the SAX parser
  5785. */
  5786. bool parse_bson_array()
  5787. {
  5788. std::int32_t document_size;
  5789. get_number<std::int32_t, true>(input_format_t::bson, document_size);
  5790. if (JSON_UNLIKELY(not sax->start_array(std::size_t(-1))))
  5791. {
  5792. return false;
  5793. }
  5794. if (JSON_UNLIKELY(not parse_bson_element_list(/*is_array*/true)))
  5795. {
  5796. return false;
  5797. }
  5798. return sax->end_array();
  5799. }
  5800. //////////
  5801. // CBOR //
  5802. //////////
  5803. /*!
  5804. @param[in] get_char whether a new character should be retrieved from the
  5805. input (true, default) or whether the last read
  5806. character should be considered instead
  5807. @return whether a valid CBOR value was passed to the SAX parser
  5808. */
  5809. bool parse_cbor_internal(const bool get_char = true)
  5810. {
  5811. switch (get_char ? get() : current)
  5812. {
  5813. // EOF
  5814. case std::char_traits<char>::eof():
  5815. return unexpect_eof(input_format_t::cbor, "value");
  5816. // Integer 0x00..0x17 (0..23)
  5817. case 0x00:
  5818. case 0x01:
  5819. case 0x02:
  5820. case 0x03:
  5821. case 0x04:
  5822. case 0x05:
  5823. case 0x06:
  5824. case 0x07:
  5825. case 0x08:
  5826. case 0x09:
  5827. case 0x0A:
  5828. case 0x0B:
  5829. case 0x0C:
  5830. case 0x0D:
  5831. case 0x0E:
  5832. case 0x0F:
  5833. case 0x10:
  5834. case 0x11:
  5835. case 0x12:
  5836. case 0x13:
  5837. case 0x14:
  5838. case 0x15:
  5839. case 0x16:
  5840. case 0x17:
  5841. return sax->number_unsigned(static_cast<number_unsigned_t>(current));
  5842. case 0x18: // Unsigned integer (one-byte uint8_t follows)
  5843. {
  5844. uint8_t number;
  5845. return get_number(input_format_t::cbor, number) and sax->number_unsigned(number);
  5846. }
  5847. case 0x19: // Unsigned integer (two-byte uint16_t follows)
  5848. {
  5849. uint16_t number;
  5850. return get_number(input_format_t::cbor, number) and sax->number_unsigned(number);
  5851. }
  5852. case 0x1A: // Unsigned integer (four-byte uint32_t follows)
  5853. {
  5854. uint32_t number;
  5855. return get_number(input_format_t::cbor, number) and sax->number_unsigned(number);
  5856. }
  5857. case 0x1B: // Unsigned integer (eight-byte uint64_t follows)
  5858. {
  5859. uint64_t number;
  5860. return get_number(input_format_t::cbor, number) and sax->number_unsigned(number);
  5861. }
  5862. // Negative integer -1-0x00..-1-0x17 (-1..-24)
  5863. case 0x20:
  5864. case 0x21:
  5865. case 0x22:
  5866. case 0x23:
  5867. case 0x24:
  5868. case 0x25:
  5869. case 0x26:
  5870. case 0x27:
  5871. case 0x28:
  5872. case 0x29:
  5873. case 0x2A:
  5874. case 0x2B:
  5875. case 0x2C:
  5876. case 0x2D:
  5877. case 0x2E:
  5878. case 0x2F:
  5879. case 0x30:
  5880. case 0x31:
  5881. case 0x32:
  5882. case 0x33:
  5883. case 0x34:
  5884. case 0x35:
  5885. case 0x36:
  5886. case 0x37:
  5887. return sax->number_integer(static_cast<int8_t>(0x20 - 1 - current));
  5888. case 0x38: // Negative integer (one-byte uint8_t follows)
  5889. {
  5890. uint8_t number;
  5891. return get_number(input_format_t::cbor, number) and sax->number_integer(static_cast<number_integer_t>(-1) - number);
  5892. }
  5893. case 0x39: // Negative integer -1-n (two-byte uint16_t follows)
  5894. {
  5895. uint16_t number;
  5896. return get_number(input_format_t::cbor, number) and sax->number_integer(static_cast<number_integer_t>(-1) - number);
  5897. }
  5898. case 0x3A: // Negative integer -1-n (four-byte uint32_t follows)
  5899. {
  5900. uint32_t number;
  5901. return get_number(input_format_t::cbor, number) and sax->number_integer(static_cast<number_integer_t>(-1) - number);
  5902. }
  5903. case 0x3B: // Negative integer -1-n (eight-byte uint64_t follows)
  5904. {
  5905. uint64_t number;
  5906. return get_number(input_format_t::cbor, number) and sax->number_integer(static_cast<number_integer_t>(-1)
  5907. - static_cast<number_integer_t>(number));
  5908. }
  5909. // UTF-8 string (0x00..0x17 bytes follow)
  5910. case 0x60:
  5911. case 0x61:
  5912. case 0x62:
  5913. case 0x63:
  5914. case 0x64:
  5915. case 0x65:
  5916. case 0x66:
  5917. case 0x67:
  5918. case 0x68:
  5919. case 0x69:
  5920. case 0x6A:
  5921. case 0x6B:
  5922. case 0x6C:
  5923. case 0x6D:
  5924. case 0x6E:
  5925. case 0x6F:
  5926. case 0x70:
  5927. case 0x71:
  5928. case 0x72:
  5929. case 0x73:
  5930. case 0x74:
  5931. case 0x75:
  5932. case 0x76:
  5933. case 0x77:
  5934. case 0x78: // UTF-8 string (one-byte uint8_t for n follows)
  5935. case 0x79: // UTF-8 string (two-byte uint16_t for n follow)
  5936. case 0x7A: // UTF-8 string (four-byte uint32_t for n follow)
  5937. case 0x7B: // UTF-8 string (eight-byte uint64_t for n follow)
  5938. case 0x7F: // UTF-8 string (indefinite length)
  5939. {
  5940. string_t s;
  5941. return get_cbor_string(s) and sax->string(s);
  5942. }
  5943. // array (0x00..0x17 data items follow)
  5944. case 0x80:
  5945. case 0x81:
  5946. case 0x82:
  5947. case 0x83:
  5948. case 0x84:
  5949. case 0x85:
  5950. case 0x86:
  5951. case 0x87:
  5952. case 0x88:
  5953. case 0x89:
  5954. case 0x8A:
  5955. case 0x8B:
  5956. case 0x8C:
  5957. case 0x8D:
  5958. case 0x8E:
  5959. case 0x8F:
  5960. case 0x90:
  5961. case 0x91:
  5962. case 0x92:
  5963. case 0x93:
  5964. case 0x94:
  5965. case 0x95:
  5966. case 0x96:
  5967. case 0x97:
  5968. return get_cbor_array(static_cast<std::size_t>(current & 0x1F));
  5969. case 0x98: // array (one-byte uint8_t for n follows)
  5970. {
  5971. uint8_t len;
  5972. return get_number(input_format_t::cbor, len) and get_cbor_array(static_cast<std::size_t>(len));
  5973. }
  5974. case 0x99: // array (two-byte uint16_t for n follow)
  5975. {
  5976. uint16_t len;
  5977. return get_number(input_format_t::cbor, len) and get_cbor_array(static_cast<std::size_t>(len));
  5978. }
  5979. case 0x9A: // array (four-byte uint32_t for n follow)
  5980. {
  5981. uint32_t len;
  5982. return get_number(input_format_t::cbor, len) and get_cbor_array(static_cast<std::size_t>(len));
  5983. }
  5984. case 0x9B: // array (eight-byte uint64_t for n follow)
  5985. {
  5986. uint64_t len;
  5987. return get_number(input_format_t::cbor, len) and get_cbor_array(static_cast<std::size_t>(len));
  5988. }
  5989. case 0x9F: // array (indefinite length)
  5990. return get_cbor_array(std::size_t(-1));
  5991. // map (0x00..0x17 pairs of data items follow)
  5992. case 0xA0:
  5993. case 0xA1:
  5994. case 0xA2:
  5995. case 0xA3:
  5996. case 0xA4:
  5997. case 0xA5:
  5998. case 0xA6:
  5999. case 0xA7:
  6000. case 0xA8:
  6001. case 0xA9:
  6002. case 0xAA:
  6003. case 0xAB:
  6004. case 0xAC:
  6005. case 0xAD:
  6006. case 0xAE:
  6007. case 0xAF:
  6008. case 0xB0:
  6009. case 0xB1:
  6010. case 0xB2:
  6011. case 0xB3:
  6012. case 0xB4:
  6013. case 0xB5:
  6014. case 0xB6:
  6015. case 0xB7:
  6016. return get_cbor_object(static_cast<std::size_t>(current & 0x1F));
  6017. case 0xB8: // map (one-byte uint8_t for n follows)
  6018. {
  6019. uint8_t len;
  6020. return get_number(input_format_t::cbor, len) and get_cbor_object(static_cast<std::size_t>(len));
  6021. }
  6022. case 0xB9: // map (two-byte uint16_t for n follow)
  6023. {
  6024. uint16_t len;
  6025. return get_number(input_format_t::cbor, len) and get_cbor_object(static_cast<std::size_t>(len));
  6026. }
  6027. case 0xBA: // map (four-byte uint32_t for n follow)
  6028. {
  6029. uint32_t len;
  6030. return get_number(input_format_t::cbor, len) and get_cbor_object(static_cast<std::size_t>(len));
  6031. }
  6032. case 0xBB: // map (eight-byte uint64_t for n follow)
  6033. {
  6034. uint64_t len;
  6035. return get_number(input_format_t::cbor, len) and get_cbor_object(static_cast<std::size_t>(len));
  6036. }
  6037. case 0xBF: // map (indefinite length)
  6038. return get_cbor_object(std::size_t(-1));
  6039. case 0xF4: // false
  6040. return sax->boolean(false);
  6041. case 0xF5: // true
  6042. return sax->boolean(true);
  6043. case 0xF6: // null
  6044. return sax->null();
  6045. case 0xF9: // Half-Precision Float (two-byte IEEE 754)
  6046. {
  6047. const int byte1_raw = get();
  6048. if (JSON_UNLIKELY(not unexpect_eof(input_format_t::cbor, "number")))
  6049. {
  6050. return false;
  6051. }
  6052. const int byte2_raw = get();
  6053. if (JSON_UNLIKELY(not unexpect_eof(input_format_t::cbor, "number")))
  6054. {
  6055. return false;
  6056. }
  6057. const auto byte1 = static_cast<unsigned char>(byte1_raw);
  6058. const auto byte2 = static_cast<unsigned char>(byte2_raw);
  6059. // code from RFC 7049, Appendix D, Figure 3:
  6060. // As half-precision floating-point numbers were only added
  6061. // to IEEE 754 in 2008, today's programming platforms often
  6062. // still only have limited support for them. It is very
  6063. // easy to include at least decoding support for them even
  6064. // without such support. An example of a small decoder for
  6065. // half-precision floating-point numbers in the C language
  6066. // is shown in Fig. 3.
  6067. const int half = (byte1 << 8) + byte2;
  6068. const double val = [&half]
  6069. {
  6070. const int exp = (half >> 10) & 0x1F;
  6071. const int mant = half & 0x3FF;
  6072. assert(0 <= exp and exp <= 32);
  6073. assert(0 <= mant and mant <= 1024);
  6074. switch (exp)
  6075. {
  6076. case 0:
  6077. return std::ldexp(mant, -24);
  6078. case 31:
  6079. return (mant == 0)
  6080. ? std::numeric_limits<double>::infinity()
  6081. : std::numeric_limits<double>::quiet_NaN();
  6082. default:
  6083. return std::ldexp(mant + 1024, exp - 25);
  6084. }
  6085. }();
  6086. return sax->number_float((half & 0x8000) != 0
  6087. ? static_cast<number_float_t>(-val)
  6088. : static_cast<number_float_t>(val), "");
  6089. }
  6090. case 0xFA: // Single-Precision Float (four-byte IEEE 754)
  6091. {
  6092. float number;
  6093. return get_number(input_format_t::cbor, number) and sax->number_float(static_cast<number_float_t>(number), "");
  6094. }
  6095. case 0xFB: // Double-Precision Float (eight-byte IEEE 754)
  6096. {
  6097. double number;
  6098. return get_number(input_format_t::cbor, number) and sax->number_float(static_cast<number_float_t>(number), "");
  6099. }
  6100. default: // anything else (0xFF is handled inside the other types)
  6101. {
  6102. auto last_token = get_token_string();
  6103. return sax->parse_error(chars_read, last_token, parse_error::create(112, chars_read, exception_message(input_format_t::cbor, "invalid byte: 0x" + last_token, "value")));
  6104. }
  6105. }
  6106. }
  6107. /*!
  6108. @brief reads a CBOR string
  6109. This function first reads starting bytes to determine the expected
  6110. string length and then copies this number of bytes into a string.
  6111. Additionally, CBOR's strings with indefinite lengths are supported.
  6112. @param[out] result created string
  6113. @return whether string creation completed
  6114. */
  6115. bool get_cbor_string(string_t& result)
  6116. {
  6117. if (JSON_UNLIKELY(not unexpect_eof(input_format_t::cbor, "string")))
  6118. {
  6119. return false;
  6120. }
  6121. switch (current)
  6122. {
  6123. // UTF-8 string (0x00..0x17 bytes follow)
  6124. case 0x60:
  6125. case 0x61:
  6126. case 0x62:
  6127. case 0x63:
  6128. case 0x64:
  6129. case 0x65:
  6130. case 0x66:
  6131. case 0x67:
  6132. case 0x68:
  6133. case 0x69:
  6134. case 0x6A:
  6135. case 0x6B:
  6136. case 0x6C:
  6137. case 0x6D:
  6138. case 0x6E:
  6139. case 0x6F:
  6140. case 0x70:
  6141. case 0x71:
  6142. case 0x72:
  6143. case 0x73:
  6144. case 0x74:
  6145. case 0x75:
  6146. case 0x76:
  6147. case 0x77:
  6148. {
  6149. return get_string(input_format_t::cbor, current & 0x1F, result);
  6150. }
  6151. case 0x78: // UTF-8 string (one-byte uint8_t for n follows)
  6152. {
  6153. uint8_t len;
  6154. return get_number(input_format_t::cbor, len) and get_string(input_format_t::cbor, len, result);
  6155. }
  6156. case 0x79: // UTF-8 string (two-byte uint16_t for n follow)
  6157. {
  6158. uint16_t len;
  6159. return get_number(input_format_t::cbor, len) and get_string(input_format_t::cbor, len, result);
  6160. }
  6161. case 0x7A: // UTF-8 string (four-byte uint32_t for n follow)
  6162. {
  6163. uint32_t len;
  6164. return get_number(input_format_t::cbor, len) and get_string(input_format_t::cbor, len, result);
  6165. }
  6166. case 0x7B: // UTF-8 string (eight-byte uint64_t for n follow)
  6167. {
  6168. uint64_t len;
  6169. return get_number(input_format_t::cbor, len) and get_string(input_format_t::cbor, len, result);
  6170. }
  6171. case 0x7F: // UTF-8 string (indefinite length)
  6172. {
  6173. while (get() != 0xFF)
  6174. {
  6175. string_t chunk;
  6176. if (not get_cbor_string(chunk))
  6177. {
  6178. return false;
  6179. }
  6180. result.append(chunk);
  6181. }
  6182. return true;
  6183. }
  6184. default:
  6185. {
  6186. auto last_token = get_token_string();
  6187. return sax->parse_error(chars_read, last_token, parse_error::create(113, chars_read, exception_message(input_format_t::cbor, "expected length specification (0x60-0x7B) or indefinite string type (0x7F); last byte: 0x" + last_token, "string")));
  6188. }
  6189. }
  6190. }
  6191. /*!
  6192. @param[in] len the length of the array or std::size_t(-1) for an
  6193. array of indefinite size
  6194. @return whether array creation completed
  6195. */
  6196. bool get_cbor_array(const std::size_t len)
  6197. {
  6198. if (JSON_UNLIKELY(not sax->start_array(len)))
  6199. {
  6200. return false;
  6201. }
  6202. if (len != std::size_t(-1))
  6203. {
  6204. for (std::size_t i = 0; i < len; ++i)
  6205. {
  6206. if (JSON_UNLIKELY(not parse_cbor_internal()))
  6207. {
  6208. return false;
  6209. }
  6210. }
  6211. }
  6212. else
  6213. {
  6214. while (get() != 0xFF)
  6215. {
  6216. if (JSON_UNLIKELY(not parse_cbor_internal(false)))
  6217. {
  6218. return false;
  6219. }
  6220. }
  6221. }
  6222. return sax->end_array();
  6223. }
  6224. /*!
  6225. @param[in] len the length of the object or std::size_t(-1) for an
  6226. object of indefinite size
  6227. @return whether object creation completed
  6228. */
  6229. bool get_cbor_object(const std::size_t len)
  6230. {
  6231. if (not JSON_UNLIKELY(sax->start_object(len)))
  6232. {
  6233. return false;
  6234. }
  6235. string_t key;
  6236. if (len != std::size_t(-1))
  6237. {
  6238. for (std::size_t i = 0; i < len; ++i)
  6239. {
  6240. get();
  6241. if (JSON_UNLIKELY(not get_cbor_string(key) or not sax->key(key)))
  6242. {
  6243. return false;
  6244. }
  6245. if (JSON_UNLIKELY(not parse_cbor_internal()))
  6246. {
  6247. return false;
  6248. }
  6249. key.clear();
  6250. }
  6251. }
  6252. else
  6253. {
  6254. while (get() != 0xFF)
  6255. {
  6256. if (JSON_UNLIKELY(not get_cbor_string(key) or not sax->key(key)))
  6257. {
  6258. return false;
  6259. }
  6260. if (JSON_UNLIKELY(not parse_cbor_internal()))
  6261. {
  6262. return false;
  6263. }
  6264. key.clear();
  6265. }
  6266. }
  6267. return sax->end_object();
  6268. }
  6269. /////////////
  6270. // MsgPack //
  6271. /////////////
  6272. /*!
  6273. @return whether a valid MessagePack value was passed to the SAX parser
  6274. */
  6275. bool parse_msgpack_internal()
  6276. {
  6277. switch (get())
  6278. {
  6279. // EOF
  6280. case std::char_traits<char>::eof():
  6281. return unexpect_eof(input_format_t::msgpack, "value");
  6282. // positive fixint
  6283. case 0x00:
  6284. case 0x01:
  6285. case 0x02:
  6286. case 0x03:
  6287. case 0x04:
  6288. case 0x05:
  6289. case 0x06:
  6290. case 0x07:
  6291. case 0x08:
  6292. case 0x09:
  6293. case 0x0A:
  6294. case 0x0B:
  6295. case 0x0C:
  6296. case 0x0D:
  6297. case 0x0E:
  6298. case 0x0F:
  6299. case 0x10:
  6300. case 0x11:
  6301. case 0x12:
  6302. case 0x13:
  6303. case 0x14:
  6304. case 0x15:
  6305. case 0x16:
  6306. case 0x17:
  6307. case 0x18:
  6308. case 0x19:
  6309. case 0x1A:
  6310. case 0x1B:
  6311. case 0x1C:
  6312. case 0x1D:
  6313. case 0x1E:
  6314. case 0x1F:
  6315. case 0x20:
  6316. case 0x21:
  6317. case 0x22:
  6318. case 0x23:
  6319. case 0x24:
  6320. case 0x25:
  6321. case 0x26:
  6322. case 0x27:
  6323. case 0x28:
  6324. case 0x29:
  6325. case 0x2A:
  6326. case 0x2B:
  6327. case 0x2C:
  6328. case 0x2D:
  6329. case 0x2E:
  6330. case 0x2F:
  6331. case 0x30:
  6332. case 0x31:
  6333. case 0x32:
  6334. case 0x33:
  6335. case 0x34:
  6336. case 0x35:
  6337. case 0x36:
  6338. case 0x37:
  6339. case 0x38:
  6340. case 0x39:
  6341. case 0x3A:
  6342. case 0x3B:
  6343. case 0x3C:
  6344. case 0x3D:
  6345. case 0x3E:
  6346. case 0x3F:
  6347. case 0x40:
  6348. case 0x41:
  6349. case 0x42:
  6350. case 0x43:
  6351. case 0x44:
  6352. case 0x45:
  6353. case 0x46:
  6354. case 0x47:
  6355. case 0x48:
  6356. case 0x49:
  6357. case 0x4A:
  6358. case 0x4B:
  6359. case 0x4C:
  6360. case 0x4D:
  6361. case 0x4E:
  6362. case 0x4F:
  6363. case 0x50:
  6364. case 0x51:
  6365. case 0x52:
  6366. case 0x53:
  6367. case 0x54:
  6368. case 0x55:
  6369. case 0x56:
  6370. case 0x57:
  6371. case 0x58:
  6372. case 0x59:
  6373. case 0x5A:
  6374. case 0x5B:
  6375. case 0x5C:
  6376. case 0x5D:
  6377. case 0x5E:
  6378. case 0x5F:
  6379. case 0x60:
  6380. case 0x61:
  6381. case 0x62:
  6382. case 0x63:
  6383. case 0x64:
  6384. case 0x65:
  6385. case 0x66:
  6386. case 0x67:
  6387. case 0x68:
  6388. case 0x69:
  6389. case 0x6A:
  6390. case 0x6B:
  6391. case 0x6C:
  6392. case 0x6D:
  6393. case 0x6E:
  6394. case 0x6F:
  6395. case 0x70:
  6396. case 0x71:
  6397. case 0x72:
  6398. case 0x73:
  6399. case 0x74:
  6400. case 0x75:
  6401. case 0x76:
  6402. case 0x77:
  6403. case 0x78:
  6404. case 0x79:
  6405. case 0x7A:
  6406. case 0x7B:
  6407. case 0x7C:
  6408. case 0x7D:
  6409. case 0x7E:
  6410. case 0x7F:
  6411. return sax->number_unsigned(static_cast<number_unsigned_t>(current));
  6412. // fixmap
  6413. case 0x80:
  6414. case 0x81:
  6415. case 0x82:
  6416. case 0x83:
  6417. case 0x84:
  6418. case 0x85:
  6419. case 0x86:
  6420. case 0x87:
  6421. case 0x88:
  6422. case 0x89:
  6423. case 0x8A:
  6424. case 0x8B:
  6425. case 0x8C:
  6426. case 0x8D:
  6427. case 0x8E:
  6428. case 0x8F:
  6429. return get_msgpack_object(static_cast<std::size_t>(current & 0x0F));
  6430. // fixarray
  6431. case 0x90:
  6432. case 0x91:
  6433. case 0x92:
  6434. case 0x93:
  6435. case 0x94:
  6436. case 0x95:
  6437. case 0x96:
  6438. case 0x97:
  6439. case 0x98:
  6440. case 0x99:
  6441. case 0x9A:
  6442. case 0x9B:
  6443. case 0x9C:
  6444. case 0x9D:
  6445. case 0x9E:
  6446. case 0x9F:
  6447. return get_msgpack_array(static_cast<std::size_t>(current & 0x0F));
  6448. // fixstr
  6449. case 0xA0:
  6450. case 0xA1:
  6451. case 0xA2:
  6452. case 0xA3:
  6453. case 0xA4:
  6454. case 0xA5:
  6455. case 0xA6:
  6456. case 0xA7:
  6457. case 0xA8:
  6458. case 0xA9:
  6459. case 0xAA:
  6460. case 0xAB:
  6461. case 0xAC:
  6462. case 0xAD:
  6463. case 0xAE:
  6464. case 0xAF:
  6465. case 0xB0:
  6466. case 0xB1:
  6467. case 0xB2:
  6468. case 0xB3:
  6469. case 0xB4:
  6470. case 0xB5:
  6471. case 0xB6:
  6472. case 0xB7:
  6473. case 0xB8:
  6474. case 0xB9:
  6475. case 0xBA:
  6476. case 0xBB:
  6477. case 0xBC:
  6478. case 0xBD:
  6479. case 0xBE:
  6480. case 0xBF:
  6481. {
  6482. string_t s;
  6483. return get_msgpack_string(s) and sax->string(s);
  6484. }
  6485. case 0xC0: // nil
  6486. return sax->null();
  6487. case 0xC2: // false
  6488. return sax->boolean(false);
  6489. case 0xC3: // true
  6490. return sax->boolean(true);
  6491. case 0xCA: // float 32
  6492. {
  6493. float number;
  6494. return get_number(input_format_t::msgpack, number) and sax->number_float(static_cast<number_float_t>(number), "");
  6495. }
  6496. case 0xCB: // float 64
  6497. {
  6498. double number;
  6499. return get_number(input_format_t::msgpack, number) and sax->number_float(static_cast<number_float_t>(number), "");
  6500. }
  6501. case 0xCC: // uint 8
  6502. {
  6503. uint8_t number;
  6504. return get_number(input_format_t::msgpack, number) and sax->number_unsigned(number);
  6505. }
  6506. case 0xCD: // uint 16
  6507. {
  6508. uint16_t number;
  6509. return get_number(input_format_t::msgpack, number) and sax->number_unsigned(number);
  6510. }
  6511. case 0xCE: // uint 32
  6512. {
  6513. uint32_t number;
  6514. return get_number(input_format_t::msgpack, number) and sax->number_unsigned(number);
  6515. }
  6516. case 0xCF: // uint 64
  6517. {
  6518. uint64_t number;
  6519. return get_number(input_format_t::msgpack, number) and sax->number_unsigned(number);
  6520. }
  6521. case 0xD0: // int 8
  6522. {
  6523. int8_t number;
  6524. return get_number(input_format_t::msgpack, number) and sax->number_integer(number);
  6525. }
  6526. case 0xD1: // int 16
  6527. {
  6528. int16_t number;
  6529. return get_number(input_format_t::msgpack, number) and sax->number_integer(number);
  6530. }
  6531. case 0xD2: // int 32
  6532. {
  6533. int32_t number;
  6534. return get_number(input_format_t::msgpack, number) and sax->number_integer(number);
  6535. }
  6536. case 0xD3: // int 64
  6537. {
  6538. int64_t number;
  6539. return get_number(input_format_t::msgpack, number) and sax->number_integer(number);
  6540. }
  6541. case 0xD9: // str 8
  6542. case 0xDA: // str 16
  6543. case 0xDB: // str 32
  6544. {
  6545. string_t s;
  6546. return get_msgpack_string(s) and sax->string(s);
  6547. }
  6548. case 0xDC: // array 16
  6549. {
  6550. uint16_t len;
  6551. return get_number(input_format_t::msgpack, len) and get_msgpack_array(static_cast<std::size_t>(len));
  6552. }
  6553. case 0xDD: // array 32
  6554. {
  6555. uint32_t len;
  6556. return get_number(input_format_t::msgpack, len) and get_msgpack_array(static_cast<std::size_t>(len));
  6557. }
  6558. case 0xDE: // map 16
  6559. {
  6560. uint16_t len;
  6561. return get_number(input_format_t::msgpack, len) and get_msgpack_object(static_cast<std::size_t>(len));
  6562. }
  6563. case 0xDF: // map 32
  6564. {
  6565. uint32_t len;
  6566. return get_number(input_format_t::msgpack, len) and get_msgpack_object(static_cast<std::size_t>(len));
  6567. }
  6568. // negative fixint
  6569. case 0xE0:
  6570. case 0xE1:
  6571. case 0xE2:
  6572. case 0xE3:
  6573. case 0xE4:
  6574. case 0xE5:
  6575. case 0xE6:
  6576. case 0xE7:
  6577. case 0xE8:
  6578. case 0xE9:
  6579. case 0xEA:
  6580. case 0xEB:
  6581. case 0xEC:
  6582. case 0xED:
  6583. case 0xEE:
  6584. case 0xEF:
  6585. case 0xF0:
  6586. case 0xF1:
  6587. case 0xF2:
  6588. case 0xF3:
  6589. case 0xF4:
  6590. case 0xF5:
  6591. case 0xF6:
  6592. case 0xF7:
  6593. case 0xF8:
  6594. case 0xF9:
  6595. case 0xFA:
  6596. case 0xFB:
  6597. case 0xFC:
  6598. case 0xFD:
  6599. case 0xFE:
  6600. case 0xFF:
  6601. return sax->number_integer(static_cast<int8_t>(current));
  6602. default: // anything else
  6603. {
  6604. auto last_token = get_token_string();
  6605. return sax->parse_error(chars_read, last_token, parse_error::create(112, chars_read, exception_message(input_format_t::msgpack, "invalid byte: 0x" + last_token, "value")));
  6606. }
  6607. }
  6608. }
  6609. /*!
  6610. @brief reads a MessagePack string
  6611. This function first reads starting bytes to determine the expected
  6612. string length and then copies this number of bytes into a string.
  6613. @param[out] result created string
  6614. @return whether string creation completed
  6615. */
  6616. bool get_msgpack_string(string_t& result)
  6617. {
  6618. if (JSON_UNLIKELY(not unexpect_eof(input_format_t::msgpack, "string")))
  6619. {
  6620. return false;
  6621. }
  6622. switch (current)
  6623. {
  6624. // fixstr
  6625. case 0xA0:
  6626. case 0xA1:
  6627. case 0xA2:
  6628. case 0xA3:
  6629. case 0xA4:
  6630. case 0xA5:
  6631. case 0xA6:
  6632. case 0xA7:
  6633. case 0xA8:
  6634. case 0xA9:
  6635. case 0xAA:
  6636. case 0xAB:
  6637. case 0xAC:
  6638. case 0xAD:
  6639. case 0xAE:
  6640. case 0xAF:
  6641. case 0xB0:
  6642. case 0xB1:
  6643. case 0xB2:
  6644. case 0xB3:
  6645. case 0xB4:
  6646. case 0xB5:
  6647. case 0xB6:
  6648. case 0xB7:
  6649. case 0xB8:
  6650. case 0xB9:
  6651. case 0xBA:
  6652. case 0xBB:
  6653. case 0xBC:
  6654. case 0xBD:
  6655. case 0xBE:
  6656. case 0xBF:
  6657. {
  6658. return get_string(input_format_t::msgpack, current & 0x1F, result);
  6659. }
  6660. case 0xD9: // str 8
  6661. {
  6662. uint8_t len;
  6663. return get_number(input_format_t::msgpack, len) and get_string(input_format_t::msgpack, len, result);
  6664. }
  6665. case 0xDA: // str 16
  6666. {
  6667. uint16_t len;
  6668. return get_number(input_format_t::msgpack, len) and get_string(input_format_t::msgpack, len, result);
  6669. }
  6670. case 0xDB: // str 32
  6671. {
  6672. uint32_t len;
  6673. return get_number(input_format_t::msgpack, len) and get_string(input_format_t::msgpack, len, result);
  6674. }
  6675. default:
  6676. {
  6677. auto last_token = get_token_string();
  6678. return sax->parse_error(chars_read, last_token, parse_error::create(113, chars_read, exception_message(input_format_t::msgpack, "expected length specification (0xA0-0xBF, 0xD9-0xDB); last byte: 0x" + last_token, "string")));
  6679. }
  6680. }
  6681. }
  6682. /*!
  6683. @param[in] len the length of the array
  6684. @return whether array creation completed
  6685. */
  6686. bool get_msgpack_array(const std::size_t len)
  6687. {
  6688. if (JSON_UNLIKELY(not sax->start_array(len)))
  6689. {
  6690. return false;
  6691. }
  6692. for (std::size_t i = 0; i < len; ++i)
  6693. {
  6694. if (JSON_UNLIKELY(not parse_msgpack_internal()))
  6695. {
  6696. return false;
  6697. }
  6698. }
  6699. return sax->end_array();
  6700. }
  6701. /*!
  6702. @param[in] len the length of the object
  6703. @return whether object creation completed
  6704. */
  6705. bool get_msgpack_object(const std::size_t len)
  6706. {
  6707. if (JSON_UNLIKELY(not sax->start_object(len)))
  6708. {
  6709. return false;
  6710. }
  6711. string_t key;
  6712. for (std::size_t i = 0; i < len; ++i)
  6713. {
  6714. get();
  6715. if (JSON_UNLIKELY(not get_msgpack_string(key) or not sax->key(key)))
  6716. {
  6717. return false;
  6718. }
  6719. if (JSON_UNLIKELY(not parse_msgpack_internal()))
  6720. {
  6721. return false;
  6722. }
  6723. key.clear();
  6724. }
  6725. return sax->end_object();
  6726. }
  6727. ////////////
  6728. // UBJSON //
  6729. ////////////
  6730. /*!
  6731. @param[in] get_char whether a new character should be retrieved from the
  6732. input (true, default) or whether the last read
  6733. character should be considered instead
  6734. @return whether a valid UBJSON value was passed to the SAX parser
  6735. */
  6736. bool parse_ubjson_internal(const bool get_char = true)
  6737. {
  6738. return get_ubjson_value(get_char ? get_ignore_noop() : current);
  6739. }
  6740. /*!
  6741. @brief reads a UBJSON string
  6742. This function is either called after reading the 'S' byte explicitly
  6743. indicating a string, or in case of an object key where the 'S' byte can be
  6744. left out.
  6745. @param[out] result created string
  6746. @param[in] get_char whether a new character should be retrieved from the
  6747. input (true, default) or whether the last read
  6748. character should be considered instead
  6749. @return whether string creation completed
  6750. */
  6751. bool get_ubjson_string(string_t& result, const bool get_char = true)
  6752. {
  6753. if (get_char)
  6754. {
  6755. get(); // TODO: may we ignore N here?
  6756. }
  6757. if (JSON_UNLIKELY(not unexpect_eof(input_format_t::ubjson, "value")))
  6758. {
  6759. return false;
  6760. }
  6761. switch (current)
  6762. {
  6763. case 'U':
  6764. {
  6765. uint8_t len;
  6766. return get_number(input_format_t::ubjson, len) and get_string(input_format_t::ubjson, len, result);
  6767. }
  6768. case 'i':
  6769. {
  6770. int8_t len;
  6771. return get_number(input_format_t::ubjson, len) and get_string(input_format_t::ubjson, len, result);
  6772. }
  6773. case 'I':
  6774. {
  6775. int16_t len;
  6776. return get_number(input_format_t::ubjson, len) and get_string(input_format_t::ubjson, len, result);
  6777. }
  6778. case 'l':
  6779. {
  6780. int32_t len;
  6781. return get_number(input_format_t::ubjson, len) and get_string(input_format_t::ubjson, len, result);
  6782. }
  6783. case 'L':
  6784. {
  6785. int64_t len;
  6786. return get_number(input_format_t::ubjson, len) and get_string(input_format_t::ubjson, len, result);
  6787. }
  6788. default:
  6789. auto last_token = get_token_string();
  6790. return sax->parse_error(chars_read, last_token, parse_error::create(113, chars_read, exception_message(input_format_t::ubjson, "expected length type specification (U, i, I, l, L); last byte: 0x" + last_token, "string")));
  6791. }
  6792. }
  6793. /*!
  6794. @param[out] result determined size
  6795. @return whether size determination completed
  6796. */
  6797. bool get_ubjson_size_value(std::size_t& result)
  6798. {
  6799. switch (get_ignore_noop())
  6800. {
  6801. case 'U':
  6802. {
  6803. uint8_t number;
  6804. if (JSON_UNLIKELY(not get_number(input_format_t::ubjson, number)))
  6805. {
  6806. return false;
  6807. }
  6808. result = static_cast<std::size_t>(number);
  6809. return true;
  6810. }
  6811. case 'i':
  6812. {
  6813. int8_t number;
  6814. if (JSON_UNLIKELY(not get_number(input_format_t::ubjson, number)))
  6815. {
  6816. return false;
  6817. }
  6818. result = static_cast<std::size_t>(number);
  6819. return true;
  6820. }
  6821. case 'I':
  6822. {
  6823. int16_t number;
  6824. if (JSON_UNLIKELY(not get_number(input_format_t::ubjson, number)))
  6825. {
  6826. return false;
  6827. }
  6828. result = static_cast<std::size_t>(number);
  6829. return true;
  6830. }
  6831. case 'l':
  6832. {
  6833. int32_t number;
  6834. if (JSON_UNLIKELY(not get_number(input_format_t::ubjson, number)))
  6835. {
  6836. return false;
  6837. }
  6838. result = static_cast<std::size_t>(number);
  6839. return true;
  6840. }
  6841. case 'L':
  6842. {
  6843. int64_t number;
  6844. if (JSON_UNLIKELY(not get_number(input_format_t::ubjson, number)))
  6845. {
  6846. return false;
  6847. }
  6848. result = static_cast<std::size_t>(number);
  6849. return true;
  6850. }
  6851. default:
  6852. {
  6853. auto last_token = get_token_string();
  6854. return sax->parse_error(chars_read, last_token, parse_error::create(113, chars_read, exception_message(input_format_t::ubjson, "expected length type specification (U, i, I, l, L) after '#'; last byte: 0x" + last_token, "size")));
  6855. }
  6856. }
  6857. }
  6858. /*!
  6859. @brief determine the type and size for a container
  6860. In the optimized UBJSON format, a type and a size can be provided to allow
  6861. for a more compact representation.
  6862. @param[out] result pair of the size and the type
  6863. @return whether pair creation completed
  6864. */
  6865. bool get_ubjson_size_type(std::pair<std::size_t, int>& result)
  6866. {
  6867. result.first = string_t::npos; // size
  6868. result.second = 0; // type
  6869. get_ignore_noop();
  6870. if (current == '$')
  6871. {
  6872. result.second = get(); // must not ignore 'N', because 'N' maybe the type
  6873. if (JSON_UNLIKELY(not unexpect_eof(input_format_t::ubjson, "type")))
  6874. {
  6875. return false;
  6876. }
  6877. get_ignore_noop();
  6878. if (JSON_UNLIKELY(current != '#'))
  6879. {
  6880. if (JSON_UNLIKELY(not unexpect_eof(input_format_t::ubjson, "value")))
  6881. {
  6882. return false;
  6883. }
  6884. auto last_token = get_token_string();
  6885. return sax->parse_error(chars_read, last_token, parse_error::create(112, chars_read, exception_message(input_format_t::ubjson, "expected '#' after type information; last byte: 0x" + last_token, "size")));
  6886. }
  6887. return get_ubjson_size_value(result.first);
  6888. }
  6889. else if (current == '#')
  6890. {
  6891. return get_ubjson_size_value(result.first);
  6892. }
  6893. return true;
  6894. }
  6895. /*!
  6896. @param prefix the previously read or set type prefix
  6897. @return whether value creation completed
  6898. */
  6899. bool get_ubjson_value(const int prefix)
  6900. {
  6901. switch (prefix)
  6902. {
  6903. case std::char_traits<char>::eof(): // EOF
  6904. return unexpect_eof(input_format_t::ubjson, "value");
  6905. case 'T': // true
  6906. return sax->boolean(true);
  6907. case 'F': // false
  6908. return sax->boolean(false);
  6909. case 'Z': // null
  6910. return sax->null();
  6911. case 'U':
  6912. {
  6913. uint8_t number;
  6914. return get_number(input_format_t::ubjson, number) and sax->number_unsigned(number);
  6915. }
  6916. case 'i':
  6917. {
  6918. int8_t number;
  6919. return get_number(input_format_t::ubjson, number) and sax->number_integer(number);
  6920. }
  6921. case 'I':
  6922. {
  6923. int16_t number;
  6924. return get_number(input_format_t::ubjson, number) and sax->number_integer(number);
  6925. }
  6926. case 'l':
  6927. {
  6928. int32_t number;
  6929. return get_number(input_format_t::ubjson, number) and sax->number_integer(number);
  6930. }
  6931. case 'L':
  6932. {
  6933. int64_t number;
  6934. return get_number(input_format_t::ubjson, number) and sax->number_integer(number);
  6935. }
  6936. case 'd':
  6937. {
  6938. float number;
  6939. return get_number(input_format_t::ubjson, number) and sax->number_float(static_cast<number_float_t>(number), "");
  6940. }
  6941. case 'D':
  6942. {
  6943. double number;
  6944. return get_number(input_format_t::ubjson, number) and sax->number_float(static_cast<number_float_t>(number), "");
  6945. }
  6946. case 'C': // char
  6947. {
  6948. get();
  6949. if (JSON_UNLIKELY(not unexpect_eof(input_format_t::ubjson, "char")))
  6950. {
  6951. return false;
  6952. }
  6953. if (JSON_UNLIKELY(current > 127))
  6954. {
  6955. auto last_token = get_token_string();
  6956. return sax->parse_error(chars_read, last_token, parse_error::create(113, chars_read, exception_message(input_format_t::ubjson, "byte after 'C' must be in range 0x00..0x7F; last byte: 0x" + last_token, "char")));
  6957. }
  6958. string_t s(1, static_cast<char>(current));
  6959. return sax->string(s);
  6960. }
  6961. case 'S': // string
  6962. {
  6963. string_t s;
  6964. return get_ubjson_string(s) and sax->string(s);
  6965. }
  6966. case '[': // array
  6967. return get_ubjson_array();
  6968. case '{': // object
  6969. return get_ubjson_object();
  6970. default: // anything else
  6971. {
  6972. auto last_token = get_token_string();
  6973. return sax->parse_error(chars_read, last_token, parse_error::create(112, chars_read, exception_message(input_format_t::ubjson, "invalid byte: 0x" + last_token, "value")));
  6974. }
  6975. }
  6976. }
  6977. /*!
  6978. @return whether array creation completed
  6979. */
  6980. bool get_ubjson_array()
  6981. {
  6982. std::pair<std::size_t, int> size_and_type;
  6983. if (JSON_UNLIKELY(not get_ubjson_size_type(size_and_type)))
  6984. {
  6985. return false;
  6986. }
  6987. if (size_and_type.first != string_t::npos)
  6988. {
  6989. if (JSON_UNLIKELY(not sax->start_array(size_and_type.first)))
  6990. {
  6991. return false;
  6992. }
  6993. if (size_and_type.second != 0)
  6994. {
  6995. if (size_and_type.second != 'N')
  6996. {
  6997. for (std::size_t i = 0; i < size_and_type.first; ++i)
  6998. {
  6999. if (JSON_UNLIKELY(not get_ubjson_value(size_and_type.second)))
  7000. {
  7001. return false;
  7002. }
  7003. }
  7004. }
  7005. }
  7006. else
  7007. {
  7008. for (std::size_t i = 0; i < size_and_type.first; ++i)
  7009. {
  7010. if (JSON_UNLIKELY(not parse_ubjson_internal()))
  7011. {
  7012. return false;
  7013. }
  7014. }
  7015. }
  7016. }
  7017. else
  7018. {
  7019. if (JSON_UNLIKELY(not sax->start_array(std::size_t(-1))))
  7020. {
  7021. return false;
  7022. }
  7023. while (current != ']')
  7024. {
  7025. if (JSON_UNLIKELY(not parse_ubjson_internal(false)))
  7026. {
  7027. return false;
  7028. }
  7029. get_ignore_noop();
  7030. }
  7031. }
  7032. return sax->end_array();
  7033. }
  7034. /*!
  7035. @return whether object creation completed
  7036. */
  7037. bool get_ubjson_object()
  7038. {
  7039. std::pair<std::size_t, int> size_and_type;
  7040. if (JSON_UNLIKELY(not get_ubjson_size_type(size_and_type)))
  7041. {
  7042. return false;
  7043. }
  7044. string_t key;
  7045. if (size_and_type.first != string_t::npos)
  7046. {
  7047. if (JSON_UNLIKELY(not sax->start_object(size_and_type.first)))
  7048. {
  7049. return false;
  7050. }
  7051. if (size_and_type.second != 0)
  7052. {
  7053. for (std::size_t i = 0; i < size_and_type.first; ++i)
  7054. {
  7055. if (JSON_UNLIKELY(not get_ubjson_string(key) or not sax->key(key)))
  7056. {
  7057. return false;
  7058. }
  7059. if (JSON_UNLIKELY(not get_ubjson_value(size_and_type.second)))
  7060. {
  7061. return false;
  7062. }
  7063. key.clear();
  7064. }
  7065. }
  7066. else
  7067. {
  7068. for (std::size_t i = 0; i < size_and_type.first; ++i)
  7069. {
  7070. if (JSON_UNLIKELY(not get_ubjson_string(key) or not sax->key(key)))
  7071. {
  7072. return false;
  7073. }
  7074. if (JSON_UNLIKELY(not parse_ubjson_internal()))
  7075. {
  7076. return false;
  7077. }
  7078. key.clear();
  7079. }
  7080. }
  7081. }
  7082. else
  7083. {
  7084. if (JSON_UNLIKELY(not sax->start_object(std::size_t(-1))))
  7085. {
  7086. return false;
  7087. }
  7088. while (current != '}')
  7089. {
  7090. if (JSON_UNLIKELY(not get_ubjson_string(key, false) or not sax->key(key)))
  7091. {
  7092. return false;
  7093. }
  7094. if (JSON_UNLIKELY(not parse_ubjson_internal()))
  7095. {
  7096. return false;
  7097. }
  7098. get_ignore_noop();
  7099. key.clear();
  7100. }
  7101. }
  7102. return sax->end_object();
  7103. }
  7104. ///////////////////////
  7105. // Utility functions //
  7106. ///////////////////////
  7107. /*!
  7108. @brief get next character from the input
  7109. This function provides the interface to the used input adapter. It does
  7110. not throw in case the input reached EOF, but returns a -'ve valued
  7111. `std::char_traits<char>::eof()` in that case.
  7112. @return character read from the input
  7113. */
  7114. int get()
  7115. {
  7116. ++chars_read;
  7117. return (current = ia->get_character());
  7118. }
  7119. /*!
  7120. @return character read from the input after ignoring all 'N' entries
  7121. */
  7122. int get_ignore_noop()
  7123. {
  7124. do
  7125. {
  7126. get();
  7127. }
  7128. while (current == 'N');
  7129. return current;
  7130. }
  7131. /*
  7132. @brief read a number from the input
  7133. @tparam NumberType the type of the number
  7134. @param[in] format the current format (for diagnostics)
  7135. @param[out] result number of type @a NumberType
  7136. @return whether conversion completed
  7137. @note This function needs to respect the system's endianess, because
  7138. bytes in CBOR, MessagePack, and UBJSON are stored in network order
  7139. (big endian) and therefore need reordering on little endian systems.
  7140. */
  7141. template<typename NumberType, bool InputIsLittleEndian = false>
  7142. bool get_number(const input_format_t format, NumberType& result)
  7143. {
  7144. // step 1: read input into array with system's byte order
  7145. std::array<uint8_t, sizeof(NumberType)> vec;
  7146. for (std::size_t i = 0; i < sizeof(NumberType); ++i)
  7147. {
  7148. get();
  7149. if (JSON_UNLIKELY(not unexpect_eof(format, "number")))
  7150. {
  7151. return false;
  7152. }
  7153. // reverse byte order prior to conversion if necessary
  7154. if (is_little_endian && !InputIsLittleEndian)
  7155. {
  7156. vec[sizeof(NumberType) - i - 1] = static_cast<uint8_t>(current);
  7157. }
  7158. else
  7159. {
  7160. vec[i] = static_cast<uint8_t>(current); // LCOV_EXCL_LINE
  7161. }
  7162. }
  7163. // step 2: convert array into number of type T and return
  7164. std::memcpy(&result, vec.data(), sizeof(NumberType));
  7165. return true;
  7166. }
  7167. /*!
  7168. @brief create a string by reading characters from the input
  7169. @tparam NumberType the type of the number
  7170. @param[in] format the current format (for diagnostics)
  7171. @param[in] len number of characters to read
  7172. @param[out] result string created by reading @a len bytes
  7173. @return whether string creation completed
  7174. @note We can not reserve @a len bytes for the result, because @a len
  7175. may be too large. Usually, @ref unexpect_eof() detects the end of
  7176. the input before we run out of string memory.
  7177. */
  7178. template<typename NumberType>
  7179. bool get_string(const input_format_t format,
  7180. const NumberType len,
  7181. string_t& result)
  7182. {
  7183. bool success = true;
  7184. std::generate_n(std::back_inserter(result), len, [this, &success, &format]()
  7185. {
  7186. get();
  7187. if (JSON_UNLIKELY(not unexpect_eof(format, "string")))
  7188. {
  7189. success = false;
  7190. }
  7191. return static_cast<char>(current);
  7192. });
  7193. return success;
  7194. }
  7195. /*!
  7196. @param[in] format the current format (for diagnostics)
  7197. @param[in] context further context information (for diagnostics)
  7198. @return whether the last read character is not EOF
  7199. */
  7200. bool unexpect_eof(const input_format_t format, const char* context) const
  7201. {
  7202. if (JSON_UNLIKELY(current == std::char_traits<char>::eof()))
  7203. {
  7204. return sax->parse_error(chars_read, "<end of file>",
  7205. parse_error::create(110, chars_read, exception_message(format, "unexpected end of input", context)));
  7206. }
  7207. return true;
  7208. }
  7209. /*!
  7210. @return a string representation of the last read byte
  7211. */
  7212. std::string get_token_string() const
  7213. {
  7214. char cr[3];
  7215. (std::snprintf)(cr, 3, "%.2hhX", static_cast<unsigned char>(current));
  7216. return std::string{cr};
  7217. }
  7218. /*!
  7219. @param[in] format the current format
  7220. @param[in] detail a detailed error message
  7221. @param[in] context further contect information
  7222. @return a message string to use in the parse_error exceptions
  7223. */
  7224. std::string exception_message(const input_format_t format,
  7225. const std::string& detail,
  7226. const std::string& context) const
  7227. {
  7228. std::string error_msg = "syntax error while parsing ";
  7229. switch (format)
  7230. {
  7231. case input_format_t::cbor:
  7232. error_msg += "CBOR";
  7233. break;
  7234. case input_format_t::msgpack:
  7235. error_msg += "MessagePack";
  7236. break;
  7237. case input_format_t::ubjson:
  7238. error_msg += "UBJSON";
  7239. break;
  7240. case input_format_t::bson:
  7241. error_msg += "BSON";
  7242. break;
  7243. // LCOV_EXCL_START
  7244. default:
  7245. assert(false);
  7246. // LCOV_EXCL_STOP
  7247. }
  7248. return error_msg + " " + context + ": " + detail;
  7249. }
  7250. private:
  7251. /// input adapter
  7252. input_adapter_t ia = nullptr;
  7253. /// the current character
  7254. int current = std::char_traits<char>::eof();
  7255. /// the number of characters read
  7256. std::size_t chars_read = 0;
  7257. /// whether we can assume little endianess
  7258. const bool is_little_endian = little_endianess();
  7259. /// the SAX parser
  7260. json_sax_t* sax = nullptr;
  7261. };
  7262. } // namespace detail
  7263. } // namespace nlohmann
  7264. // #include <nlohmann/detail/output/binary_writer.hpp>
  7265. #include <algorithm> // reverse
  7266. #include <array> // array
  7267. #include <cstdint> // uint8_t, uint16_t, uint32_t, uint64_t
  7268. #include <cstring> // memcpy
  7269. #include <limits> // numeric_limits
  7270. // #include <nlohmann/detail/input/binary_reader.hpp>
  7271. // #include <nlohmann/detail/output/output_adapters.hpp>
  7272. namespace nlohmann
  7273. {
  7274. namespace detail
  7275. {
  7276. ///////////////////
  7277. // binary writer //
  7278. ///////////////////
  7279. /*!
  7280. @brief serialization to CBOR and MessagePack values
  7281. */
  7282. template<typename BasicJsonType, typename CharType>
  7283. class binary_writer
  7284. {
  7285. using string_t = typename BasicJsonType::string_t;
  7286. public:
  7287. /*!
  7288. @brief create a binary writer
  7289. @param[in] adapter output adapter to write to
  7290. */
  7291. explicit binary_writer(output_adapter_t<CharType> adapter) : oa(adapter)
  7292. {
  7293. assert(oa);
  7294. }
  7295. /*!
  7296. @param[in] j JSON value to serialize
  7297. @pre j.type() == value_t::object
  7298. */
  7299. void write_bson(const BasicJsonType& j)
  7300. {
  7301. switch (j.type())
  7302. {
  7303. case value_t::object:
  7304. {
  7305. write_bson_object(*j.m_value.object);
  7306. break;
  7307. }
  7308. default:
  7309. {
  7310. JSON_THROW(type_error::create(317, "to serialize to BSON, top-level type must be object, but is " + std::string(j.type_name())));
  7311. }
  7312. }
  7313. }
  7314. /*!
  7315. @param[in] j JSON value to serialize
  7316. */
  7317. void write_cbor(const BasicJsonType& j)
  7318. {
  7319. switch (j.type())
  7320. {
  7321. case value_t::null:
  7322. {
  7323. oa->write_character(to_char_type(0xF6));
  7324. break;
  7325. }
  7326. case value_t::boolean:
  7327. {
  7328. oa->write_character(j.m_value.boolean
  7329. ? to_char_type(0xF5)
  7330. : to_char_type(0xF4));
  7331. break;
  7332. }
  7333. case value_t::number_integer:
  7334. {
  7335. if (j.m_value.number_integer >= 0)
  7336. {
  7337. // CBOR does not differentiate between positive signed
  7338. // integers and unsigned integers. Therefore, we used the
  7339. // code from the value_t::number_unsigned case here.
  7340. if (j.m_value.number_integer <= 0x17)
  7341. {
  7342. write_number(static_cast<uint8_t>(j.m_value.number_integer));
  7343. }
  7344. else if (j.m_value.number_integer <= (std::numeric_limits<uint8_t>::max)())
  7345. {
  7346. oa->write_character(to_char_type(0x18));
  7347. write_number(static_cast<uint8_t>(j.m_value.number_integer));
  7348. }
  7349. else if (j.m_value.number_integer <= (std::numeric_limits<uint16_t>::max)())
  7350. {
  7351. oa->write_character(to_char_type(0x19));
  7352. write_number(static_cast<uint16_t>(j.m_value.number_integer));
  7353. }
  7354. else if (j.m_value.number_integer <= (std::numeric_limits<uint32_t>::max)())
  7355. {
  7356. oa->write_character(to_char_type(0x1A));
  7357. write_number(static_cast<uint32_t>(j.m_value.number_integer));
  7358. }
  7359. else
  7360. {
  7361. oa->write_character(to_char_type(0x1B));
  7362. write_number(static_cast<uint64_t>(j.m_value.number_integer));
  7363. }
  7364. }
  7365. else
  7366. {
  7367. // The conversions below encode the sign in the first
  7368. // byte, and the value is converted to a positive number.
  7369. const auto positive_number = -1 - j.m_value.number_integer;
  7370. if (j.m_value.number_integer >= -24)
  7371. {
  7372. write_number(static_cast<uint8_t>(0x20 + positive_number));
  7373. }
  7374. else if (positive_number <= (std::numeric_limits<uint8_t>::max)())
  7375. {
  7376. oa->write_character(to_char_type(0x38));
  7377. write_number(static_cast<uint8_t>(positive_number));
  7378. }
  7379. else if (positive_number <= (std::numeric_limits<uint16_t>::max)())
  7380. {
  7381. oa->write_character(to_char_type(0x39));
  7382. write_number(static_cast<uint16_t>(positive_number));
  7383. }
  7384. else if (positive_number <= (std::numeric_limits<uint32_t>::max)())
  7385. {
  7386. oa->write_character(to_char_type(0x3A));
  7387. write_number(static_cast<uint32_t>(positive_number));
  7388. }
  7389. else
  7390. {
  7391. oa->write_character(to_char_type(0x3B));
  7392. write_number(static_cast<uint64_t>(positive_number));
  7393. }
  7394. }
  7395. break;
  7396. }
  7397. case value_t::number_unsigned:
  7398. {
  7399. if (j.m_value.number_unsigned <= 0x17)
  7400. {
  7401. write_number(static_cast<uint8_t>(j.m_value.number_unsigned));
  7402. }
  7403. else if (j.m_value.number_unsigned <= (std::numeric_limits<uint8_t>::max)())
  7404. {
  7405. oa->write_character(to_char_type(0x18));
  7406. write_number(static_cast<uint8_t>(j.m_value.number_unsigned));
  7407. }
  7408. else if (j.m_value.number_unsigned <= (std::numeric_limits<uint16_t>::max)())
  7409. {
  7410. oa->write_character(to_char_type(0x19));
  7411. write_number(static_cast<uint16_t>(j.m_value.number_unsigned));
  7412. }
  7413. else if (j.m_value.number_unsigned <= (std::numeric_limits<uint32_t>::max)())
  7414. {
  7415. oa->write_character(to_char_type(0x1A));
  7416. write_number(static_cast<uint32_t>(j.m_value.number_unsigned));
  7417. }
  7418. else
  7419. {
  7420. oa->write_character(to_char_type(0x1B));
  7421. write_number(static_cast<uint64_t>(j.m_value.number_unsigned));
  7422. }
  7423. break;
  7424. }
  7425. case value_t::number_float:
  7426. {
  7427. oa->write_character(get_cbor_float_prefix(j.m_value.number_float));
  7428. write_number(j.m_value.number_float);
  7429. break;
  7430. }
  7431. case value_t::string:
  7432. {
  7433. // step 1: write control byte and the string length
  7434. const auto N = j.m_value.string->size();
  7435. if (N <= 0x17)
  7436. {
  7437. write_number(static_cast<uint8_t>(0x60 + N));
  7438. }
  7439. else if (N <= (std::numeric_limits<uint8_t>::max)())
  7440. {
  7441. oa->write_character(to_char_type(0x78));
  7442. write_number(static_cast<uint8_t>(N));
  7443. }
  7444. else if (N <= (std::numeric_limits<uint16_t>::max)())
  7445. {
  7446. oa->write_character(to_char_type(0x79));
  7447. write_number(static_cast<uint16_t>(N));
  7448. }
  7449. else if (N <= (std::numeric_limits<uint32_t>::max)())
  7450. {
  7451. oa->write_character(to_char_type(0x7A));
  7452. write_number(static_cast<uint32_t>(N));
  7453. }
  7454. // LCOV_EXCL_START
  7455. else if (N <= (std::numeric_limits<uint64_t>::max)())
  7456. {
  7457. oa->write_character(to_char_type(0x7B));
  7458. write_number(static_cast<uint64_t>(N));
  7459. }
  7460. // LCOV_EXCL_STOP
  7461. // step 2: write the string
  7462. oa->write_characters(
  7463. reinterpret_cast<const CharType*>(j.m_value.string->c_str()),
  7464. j.m_value.string->size());
  7465. break;
  7466. }
  7467. case value_t::array:
  7468. {
  7469. // step 1: write control byte and the array size
  7470. const auto N = j.m_value.array->size();
  7471. if (N <= 0x17)
  7472. {
  7473. write_number(static_cast<uint8_t>(0x80 + N));
  7474. }
  7475. else if (N <= (std::numeric_limits<uint8_t>::max)())
  7476. {
  7477. oa->write_character(to_char_type(0x98));
  7478. write_number(static_cast<uint8_t>(N));
  7479. }
  7480. else if (N <= (std::numeric_limits<uint16_t>::max)())
  7481. {
  7482. oa->write_character(to_char_type(0x99));
  7483. write_number(static_cast<uint16_t>(N));
  7484. }
  7485. else if (N <= (std::numeric_limits<uint32_t>::max)())
  7486. {
  7487. oa->write_character(to_char_type(0x9A));
  7488. write_number(static_cast<uint32_t>(N));
  7489. }
  7490. // LCOV_EXCL_START
  7491. else if (N <= (std::numeric_limits<uint64_t>::max)())
  7492. {
  7493. oa->write_character(to_char_type(0x9B));
  7494. write_number(static_cast<uint64_t>(N));
  7495. }
  7496. // LCOV_EXCL_STOP
  7497. // step 2: write each element
  7498. for (const auto& el : *j.m_value.array)
  7499. {
  7500. write_cbor(el);
  7501. }
  7502. break;
  7503. }
  7504. case value_t::object:
  7505. {
  7506. // step 1: write control byte and the object size
  7507. const auto N = j.m_value.object->size();
  7508. if (N <= 0x17)
  7509. {
  7510. write_number(static_cast<uint8_t>(0xA0 + N));
  7511. }
  7512. else if (N <= (std::numeric_limits<uint8_t>::max)())
  7513. {
  7514. oa->write_character(to_char_type(0xB8));
  7515. write_number(static_cast<uint8_t>(N));
  7516. }
  7517. else if (N <= (std::numeric_limits<uint16_t>::max)())
  7518. {
  7519. oa->write_character(to_char_type(0xB9));
  7520. write_number(static_cast<uint16_t>(N));
  7521. }
  7522. else if (N <= (std::numeric_limits<uint32_t>::max)())
  7523. {
  7524. oa->write_character(to_char_type(0xBA));
  7525. write_number(static_cast<uint32_t>(N));
  7526. }
  7527. // LCOV_EXCL_START
  7528. else if (N <= (std::numeric_limits<uint64_t>::max)())
  7529. {
  7530. oa->write_character(to_char_type(0xBB));
  7531. write_number(static_cast<uint64_t>(N));
  7532. }
  7533. // LCOV_EXCL_STOP
  7534. // step 2: write each element
  7535. for (const auto& el : *j.m_value.object)
  7536. {
  7537. write_cbor(el.first);
  7538. write_cbor(el.second);
  7539. }
  7540. break;
  7541. }
  7542. default:
  7543. break;
  7544. }
  7545. }
  7546. /*!
  7547. @param[in] j JSON value to serialize
  7548. */
  7549. void write_msgpack(const BasicJsonType& j)
  7550. {
  7551. switch (j.type())
  7552. {
  7553. case value_t::null: // nil
  7554. {
  7555. oa->write_character(to_char_type(0xC0));
  7556. break;
  7557. }
  7558. case value_t::boolean: // true and false
  7559. {
  7560. oa->write_character(j.m_value.boolean
  7561. ? to_char_type(0xC3)
  7562. : to_char_type(0xC2));
  7563. break;
  7564. }
  7565. case value_t::number_integer:
  7566. {
  7567. if (j.m_value.number_integer >= 0)
  7568. {
  7569. // MessagePack does not differentiate between positive
  7570. // signed integers and unsigned integers. Therefore, we used
  7571. // the code from the value_t::number_unsigned case here.
  7572. if (j.m_value.number_unsigned < 128)
  7573. {
  7574. // positive fixnum
  7575. write_number(static_cast<uint8_t>(j.m_value.number_integer));
  7576. }
  7577. else if (j.m_value.number_unsigned <= (std::numeric_limits<uint8_t>::max)())
  7578. {
  7579. // uint 8
  7580. oa->write_character(to_char_type(0xCC));
  7581. write_number(static_cast<uint8_t>(j.m_value.number_integer));
  7582. }
  7583. else if (j.m_value.number_unsigned <= (std::numeric_limits<uint16_t>::max)())
  7584. {
  7585. // uint 16
  7586. oa->write_character(to_char_type(0xCD));
  7587. write_number(static_cast<uint16_t>(j.m_value.number_integer));
  7588. }
  7589. else if (j.m_value.number_unsigned <= (std::numeric_limits<uint32_t>::max)())
  7590. {
  7591. // uint 32
  7592. oa->write_character(to_char_type(0xCE));
  7593. write_number(static_cast<uint32_t>(j.m_value.number_integer));
  7594. }
  7595. else if (j.m_value.number_unsigned <= (std::numeric_limits<uint64_t>::max)())
  7596. {
  7597. // uint 64
  7598. oa->write_character(to_char_type(0xCF));
  7599. write_number(static_cast<uint64_t>(j.m_value.number_integer));
  7600. }
  7601. }
  7602. else
  7603. {
  7604. if (j.m_value.number_integer >= -32)
  7605. {
  7606. // negative fixnum
  7607. write_number(static_cast<int8_t>(j.m_value.number_integer));
  7608. }
  7609. else if (j.m_value.number_integer >= (std::numeric_limits<int8_t>::min)() and
  7610. j.m_value.number_integer <= (std::numeric_limits<int8_t>::max)())
  7611. {
  7612. // int 8
  7613. oa->write_character(to_char_type(0xD0));
  7614. write_number(static_cast<int8_t>(j.m_value.number_integer));
  7615. }
  7616. else if (j.m_value.number_integer >= (std::numeric_limits<int16_t>::min)() and
  7617. j.m_value.number_integer <= (std::numeric_limits<int16_t>::max)())
  7618. {
  7619. // int 16
  7620. oa->write_character(to_char_type(0xD1));
  7621. write_number(static_cast<int16_t>(j.m_value.number_integer));
  7622. }
  7623. else if (j.m_value.number_integer >= (std::numeric_limits<int32_t>::min)() and
  7624. j.m_value.number_integer <= (std::numeric_limits<int32_t>::max)())
  7625. {
  7626. // int 32
  7627. oa->write_character(to_char_type(0xD2));
  7628. write_number(static_cast<int32_t>(j.m_value.number_integer));
  7629. }
  7630. else if (j.m_value.number_integer >= (std::numeric_limits<int64_t>::min)() and
  7631. j.m_value.number_integer <= (std::numeric_limits<int64_t>::max)())
  7632. {
  7633. // int 64
  7634. oa->write_character(to_char_type(0xD3));
  7635. write_number(static_cast<int64_t>(j.m_value.number_integer));
  7636. }
  7637. }
  7638. break;
  7639. }
  7640. case value_t::number_unsigned:
  7641. {
  7642. if (j.m_value.number_unsigned < 128)
  7643. {
  7644. // positive fixnum
  7645. write_number(static_cast<uint8_t>(j.m_value.number_integer));
  7646. }
  7647. else if (j.m_value.number_unsigned <= (std::numeric_limits<uint8_t>::max)())
  7648. {
  7649. // uint 8
  7650. oa->write_character(to_char_type(0xCC));
  7651. write_number(static_cast<uint8_t>(j.m_value.number_integer));
  7652. }
  7653. else if (j.m_value.number_unsigned <= (std::numeric_limits<uint16_t>::max)())
  7654. {
  7655. // uint 16
  7656. oa->write_character(to_char_type(0xCD));
  7657. write_number(static_cast<uint16_t>(j.m_value.number_integer));
  7658. }
  7659. else if (j.m_value.number_unsigned <= (std::numeric_limits<uint32_t>::max)())
  7660. {
  7661. // uint 32
  7662. oa->write_character(to_char_type(0xCE));
  7663. write_number(static_cast<uint32_t>(j.m_value.number_integer));
  7664. }
  7665. else if (j.m_value.number_unsigned <= (std::numeric_limits<uint64_t>::max)())
  7666. {
  7667. // uint 64
  7668. oa->write_character(to_char_type(0xCF));
  7669. write_number(static_cast<uint64_t>(j.m_value.number_integer));
  7670. }
  7671. break;
  7672. }
  7673. case value_t::number_float:
  7674. {
  7675. oa->write_character(get_msgpack_float_prefix(j.m_value.number_float));
  7676. write_number(j.m_value.number_float);
  7677. break;
  7678. }
  7679. case value_t::string:
  7680. {
  7681. // step 1: write control byte and the string length
  7682. const auto N = j.m_value.string->size();
  7683. if (N <= 31)
  7684. {
  7685. // fixstr
  7686. write_number(static_cast<uint8_t>(0xA0 | N));
  7687. }
  7688. else if (N <= (std::numeric_limits<uint8_t>::max)())
  7689. {
  7690. // str 8
  7691. oa->write_character(to_char_type(0xD9));
  7692. write_number(static_cast<uint8_t>(N));
  7693. }
  7694. else if (N <= (std::numeric_limits<uint16_t>::max)())
  7695. {
  7696. // str 16
  7697. oa->write_character(to_char_type(0xDA));
  7698. write_number(static_cast<uint16_t>(N));
  7699. }
  7700. else if (N <= (std::numeric_limits<uint32_t>::max)())
  7701. {
  7702. // str 32
  7703. oa->write_character(to_char_type(0xDB));
  7704. write_number(static_cast<uint32_t>(N));
  7705. }
  7706. // step 2: write the string
  7707. oa->write_characters(
  7708. reinterpret_cast<const CharType*>(j.m_value.string->c_str()),
  7709. j.m_value.string->size());
  7710. break;
  7711. }
  7712. case value_t::array:
  7713. {
  7714. // step 1: write control byte and the array size
  7715. const auto N = j.m_value.array->size();
  7716. if (N <= 15)
  7717. {
  7718. // fixarray
  7719. write_number(static_cast<uint8_t>(0x90 | N));
  7720. }
  7721. else if (N <= (std::numeric_limits<uint16_t>::max)())
  7722. {
  7723. // array 16
  7724. oa->write_character(to_char_type(0xDC));
  7725. write_number(static_cast<uint16_t>(N));
  7726. }
  7727. else if (N <= (std::numeric_limits<uint32_t>::max)())
  7728. {
  7729. // array 32
  7730. oa->write_character(to_char_type(0xDD));
  7731. write_number(static_cast<uint32_t>(N));
  7732. }
  7733. // step 2: write each element
  7734. for (const auto& el : *j.m_value.array)
  7735. {
  7736. write_msgpack(el);
  7737. }
  7738. break;
  7739. }
  7740. case value_t::object:
  7741. {
  7742. // step 1: write control byte and the object size
  7743. const auto N = j.m_value.object->size();
  7744. if (N <= 15)
  7745. {
  7746. // fixmap
  7747. write_number(static_cast<uint8_t>(0x80 | (N & 0xF)));
  7748. }
  7749. else if (N <= (std::numeric_limits<uint16_t>::max)())
  7750. {
  7751. // map 16
  7752. oa->write_character(to_char_type(0xDE));
  7753. write_number(static_cast<uint16_t>(N));
  7754. }
  7755. else if (N <= (std::numeric_limits<uint32_t>::max)())
  7756. {
  7757. // map 32
  7758. oa->write_character(to_char_type(0xDF));
  7759. write_number(static_cast<uint32_t>(N));
  7760. }
  7761. // step 2: write each element
  7762. for (const auto& el : *j.m_value.object)
  7763. {
  7764. write_msgpack(el.first);
  7765. write_msgpack(el.second);
  7766. }
  7767. break;
  7768. }
  7769. default:
  7770. break;
  7771. }
  7772. }
  7773. /*!
  7774. @param[in] j JSON value to serialize
  7775. @param[in] use_count whether to use '#' prefixes (optimized format)
  7776. @param[in] use_type whether to use '$' prefixes (optimized format)
  7777. @param[in] add_prefix whether prefixes need to be used for this value
  7778. */
  7779. void write_ubjson(const BasicJsonType& j, const bool use_count,
  7780. const bool use_type, const bool add_prefix = true)
  7781. {
  7782. switch (j.type())
  7783. {
  7784. case value_t::null:
  7785. {
  7786. if (add_prefix)
  7787. {
  7788. oa->write_character(to_char_type('Z'));
  7789. }
  7790. break;
  7791. }
  7792. case value_t::boolean:
  7793. {
  7794. if (add_prefix)
  7795. {
  7796. oa->write_character(j.m_value.boolean
  7797. ? to_char_type('T')
  7798. : to_char_type('F'));
  7799. }
  7800. break;
  7801. }
  7802. case value_t::number_integer:
  7803. {
  7804. write_number_with_ubjson_prefix(j.m_value.number_integer, add_prefix);
  7805. break;
  7806. }
  7807. case value_t::number_unsigned:
  7808. {
  7809. write_number_with_ubjson_prefix(j.m_value.number_unsigned, add_prefix);
  7810. break;
  7811. }
  7812. case value_t::number_float:
  7813. {
  7814. write_number_with_ubjson_prefix(j.m_value.number_float, add_prefix);
  7815. break;
  7816. }
  7817. case value_t::string:
  7818. {
  7819. if (add_prefix)
  7820. {
  7821. oa->write_character(to_char_type('S'));
  7822. }
  7823. write_number_with_ubjson_prefix(j.m_value.string->size(), true);
  7824. oa->write_characters(
  7825. reinterpret_cast<const CharType*>(j.m_value.string->c_str()),
  7826. j.m_value.string->size());
  7827. break;
  7828. }
  7829. case value_t::array:
  7830. {
  7831. if (add_prefix)
  7832. {
  7833. oa->write_character(to_char_type('['));
  7834. }
  7835. bool prefix_required = true;
  7836. if (use_type and not j.m_value.array->empty())
  7837. {
  7838. assert(use_count);
  7839. const CharType first_prefix = ubjson_prefix(j.front());
  7840. const bool same_prefix = std::all_of(j.begin() + 1, j.end(),
  7841. [this, first_prefix](const BasicJsonType & v)
  7842. {
  7843. return ubjson_prefix(v) == first_prefix;
  7844. });
  7845. if (same_prefix)
  7846. {
  7847. prefix_required = false;
  7848. oa->write_character(to_char_type('$'));
  7849. oa->write_character(first_prefix);
  7850. }
  7851. }
  7852. if (use_count)
  7853. {
  7854. oa->write_character(to_char_type('#'));
  7855. write_number_with_ubjson_prefix(j.m_value.array->size(), true);
  7856. }
  7857. for (const auto& el : *j.m_value.array)
  7858. {
  7859. write_ubjson(el, use_count, use_type, prefix_required);
  7860. }
  7861. if (not use_count)
  7862. {
  7863. oa->write_character(to_char_type(']'));
  7864. }
  7865. break;
  7866. }
  7867. case value_t::object:
  7868. {
  7869. if (add_prefix)
  7870. {
  7871. oa->write_character(to_char_type('{'));
  7872. }
  7873. bool prefix_required = true;
  7874. if (use_type and not j.m_value.object->empty())
  7875. {
  7876. assert(use_count);
  7877. const CharType first_prefix = ubjson_prefix(j.front());
  7878. const bool same_prefix = std::all_of(j.begin(), j.end(),
  7879. [this, first_prefix](const BasicJsonType & v)
  7880. {
  7881. return ubjson_prefix(v) == first_prefix;
  7882. });
  7883. if (same_prefix)
  7884. {
  7885. prefix_required = false;
  7886. oa->write_character(to_char_type('$'));
  7887. oa->write_character(first_prefix);
  7888. }
  7889. }
  7890. if (use_count)
  7891. {
  7892. oa->write_character(to_char_type('#'));
  7893. write_number_with_ubjson_prefix(j.m_value.object->size(), true);
  7894. }
  7895. for (const auto& el : *j.m_value.object)
  7896. {
  7897. write_number_with_ubjson_prefix(el.first.size(), true);
  7898. oa->write_characters(
  7899. reinterpret_cast<const CharType*>(el.first.c_str()),
  7900. el.first.size());
  7901. write_ubjson(el.second, use_count, use_type, prefix_required);
  7902. }
  7903. if (not use_count)
  7904. {
  7905. oa->write_character(to_char_type('}'));
  7906. }
  7907. break;
  7908. }
  7909. default:
  7910. break;
  7911. }
  7912. }
  7913. private:
  7914. //////////
  7915. // BSON //
  7916. //////////
  7917. /*!
  7918. @return The size of a BSON document entry header, including the id marker
  7919. and the entry name size (and its null-terminator).
  7920. */
  7921. static std::size_t calc_bson_entry_header_size(const string_t& name)
  7922. {
  7923. const auto it = name.find(static_cast<typename string_t::value_type>(0));
  7924. if (JSON_UNLIKELY(it != BasicJsonType::string_t::npos))
  7925. {
  7926. JSON_THROW(out_of_range::create(409,
  7927. "BSON key cannot contain code point U+0000 (at byte " + std::to_string(it) + ")"));
  7928. }
  7929. return /*id*/ 1ul + name.size() + /*zero-terminator*/1u;
  7930. }
  7931. /*!
  7932. @brief Writes the given @a element_type and @a name to the output adapter
  7933. */
  7934. void write_bson_entry_header(const string_t& name,
  7935. const std::uint8_t element_type)
  7936. {
  7937. oa->write_character(to_char_type(element_type)); // boolean
  7938. oa->write_characters(
  7939. reinterpret_cast<const CharType*>(name.c_str()),
  7940. name.size() + 1u);
  7941. }
  7942. /*!
  7943. @brief Writes a BSON element with key @a name and boolean value @a value
  7944. */
  7945. void write_bson_boolean(const string_t& name,
  7946. const bool value)
  7947. {
  7948. write_bson_entry_header(name, 0x08);
  7949. oa->write_character(value ? to_char_type(0x01) : to_char_type(0x00));
  7950. }
  7951. /*!
  7952. @brief Writes a BSON element with key @a name and double value @a value
  7953. */
  7954. void write_bson_double(const string_t& name,
  7955. const double value)
  7956. {
  7957. write_bson_entry_header(name, 0x01);
  7958. write_number<double, true>(value);
  7959. }
  7960. /*!
  7961. @return The size of the BSON-encoded string in @a value
  7962. */
  7963. static std::size_t calc_bson_string_size(const string_t& value)
  7964. {
  7965. return sizeof(std::int32_t) + value.size() + 1ul;
  7966. }
  7967. /*!
  7968. @brief Writes a BSON element with key @a name and string value @a value
  7969. */
  7970. void write_bson_string(const string_t& name,
  7971. const string_t& value)
  7972. {
  7973. write_bson_entry_header(name, 0x02);
  7974. write_number<std::int32_t, true>(static_cast<std::int32_t>(value.size() + 1ul));
  7975. oa->write_characters(
  7976. reinterpret_cast<const CharType*>(value.c_str()),
  7977. value.size() + 1);
  7978. }
  7979. /*!
  7980. @brief Writes a BSON element with key @a name and null value
  7981. */
  7982. void write_bson_null(const string_t& name)
  7983. {
  7984. write_bson_entry_header(name, 0x0A);
  7985. }
  7986. /*!
  7987. @return The size of the BSON-encoded integer @a value
  7988. */
  7989. static std::size_t calc_bson_integer_size(const std::int64_t value)
  7990. {
  7991. if ((std::numeric_limits<std::int32_t>::min)() <= value and value <= (std::numeric_limits<std::int32_t>::max)())
  7992. {
  7993. return sizeof(std::int32_t);
  7994. }
  7995. else
  7996. {
  7997. return sizeof(std::int64_t);
  7998. }
  7999. }
  8000. /*!
  8001. @brief Writes a BSON element with key @a name and integer @a value
  8002. */
  8003. void write_bson_integer(const string_t& name,
  8004. const std::int64_t value)
  8005. {
  8006. if ((std::numeric_limits<std::int32_t>::min)() <= value and value <= (std::numeric_limits<std::int32_t>::max)())
  8007. {
  8008. write_bson_entry_header(name, 0x10); // int32
  8009. write_number<std::int32_t, true>(static_cast<std::int32_t>(value));
  8010. }
  8011. else
  8012. {
  8013. write_bson_entry_header(name, 0x12); // int64
  8014. write_number<std::int64_t, true>(static_cast<std::int64_t>(value));
  8015. }
  8016. }
  8017. /*!
  8018. @return The size of the BSON-encoded unsigned integer in @a j
  8019. */
  8020. static constexpr std::size_t calc_bson_unsigned_size(const std::uint64_t value) noexcept
  8021. {
  8022. return (value <= static_cast<std::uint64_t>((std::numeric_limits<std::int32_t>::max)()))
  8023. ? sizeof(std::int32_t)
  8024. : sizeof(std::int64_t);
  8025. }
  8026. /*!
  8027. @brief Writes a BSON element with key @a name and unsigned @a value
  8028. */
  8029. void write_bson_unsigned(const string_t& name,
  8030. const std::uint64_t value)
  8031. {
  8032. if (value <= static_cast<std::uint64_t>((std::numeric_limits<std::int32_t>::max)()))
  8033. {
  8034. write_bson_entry_header(name, 0x10 /* int32 */);
  8035. write_number<std::int32_t, true>(static_cast<std::int32_t>(value));
  8036. }
  8037. else if (value <= static_cast<std::uint64_t>((std::numeric_limits<std::int64_t>::max)()))
  8038. {
  8039. write_bson_entry_header(name, 0x12 /* int64 */);
  8040. write_number<std::int64_t, true>(static_cast<std::int64_t>(value));
  8041. }
  8042. else
  8043. {
  8044. JSON_THROW(out_of_range::create(407, "integer number " + std::to_string(value) + " cannot be represented by BSON as it does not fit int64"));
  8045. }
  8046. }
  8047. /*!
  8048. @brief Writes a BSON element with key @a name and object @a value
  8049. */
  8050. void write_bson_object_entry(const string_t& name,
  8051. const typename BasicJsonType::object_t& value)
  8052. {
  8053. write_bson_entry_header(name, 0x03); // object
  8054. write_bson_object(value);
  8055. }
  8056. /*!
  8057. @return The size of the BSON-encoded array @a value
  8058. */
  8059. static std::size_t calc_bson_array_size(const typename BasicJsonType::array_t& value)
  8060. {
  8061. std::size_t embedded_document_size = 0ul;
  8062. std::size_t array_index = 0ul;
  8063. for (const auto& el : value)
  8064. {
  8065. embedded_document_size += calc_bson_element_size(std::to_string(array_index++), el);
  8066. }
  8067. return sizeof(std::int32_t) + embedded_document_size + 1ul;
  8068. }
  8069. /*!
  8070. @brief Writes a BSON element with key @a name and array @a value
  8071. */
  8072. void write_bson_array(const string_t& name,
  8073. const typename BasicJsonType::array_t& value)
  8074. {
  8075. write_bson_entry_header(name, 0x04); // array
  8076. write_number<std::int32_t, true>(static_cast<std::int32_t>(calc_bson_array_size(value)));
  8077. std::size_t array_index = 0ul;
  8078. for (const auto& el : value)
  8079. {
  8080. write_bson_element(std::to_string(array_index++), el);
  8081. }
  8082. oa->write_character(to_char_type(0x00));
  8083. }
  8084. /*!
  8085. @brief Calculates the size necessary to serialize the JSON value @a j with its @a name
  8086. @return The calculated size for the BSON document entry for @a j with the given @a name.
  8087. */
  8088. static std::size_t calc_bson_element_size(const string_t& name,
  8089. const BasicJsonType& j)
  8090. {
  8091. const auto header_size = calc_bson_entry_header_size(name);
  8092. switch (j.type())
  8093. {
  8094. case value_t::object:
  8095. return header_size + calc_bson_object_size(*j.m_value.object);
  8096. case value_t::array:
  8097. return header_size + calc_bson_array_size(*j.m_value.array);
  8098. case value_t::boolean:
  8099. return header_size + 1ul;
  8100. case value_t::number_float:
  8101. return header_size + 8ul;
  8102. case value_t::number_integer:
  8103. return header_size + calc_bson_integer_size(j.m_value.number_integer);
  8104. case value_t::number_unsigned:
  8105. return header_size + calc_bson_unsigned_size(j.m_value.number_unsigned);
  8106. case value_t::string:
  8107. return header_size + calc_bson_string_size(*j.m_value.string);
  8108. case value_t::null:
  8109. return header_size + 0ul;
  8110. // LCOV_EXCL_START
  8111. default:
  8112. assert(false);
  8113. return 0ul;
  8114. // LCOV_EXCL_STOP
  8115. };
  8116. }
  8117. /*!
  8118. @brief Serializes the JSON value @a j to BSON and associates it with the
  8119. key @a name.
  8120. @param name The name to associate with the JSON entity @a j within the
  8121. current BSON document
  8122. @return The size of the BSON entry
  8123. */
  8124. void write_bson_element(const string_t& name,
  8125. const BasicJsonType& j)
  8126. {
  8127. switch (j.type())
  8128. {
  8129. case value_t::object:
  8130. return write_bson_object_entry(name, *j.m_value.object);
  8131. case value_t::array:
  8132. return write_bson_array(name, *j.m_value.array);
  8133. case value_t::boolean:
  8134. return write_bson_boolean(name, j.m_value.boolean);
  8135. case value_t::number_float:
  8136. return write_bson_double(name, j.m_value.number_float);
  8137. case value_t::number_integer:
  8138. return write_bson_integer(name, j.m_value.number_integer);
  8139. case value_t::number_unsigned:
  8140. return write_bson_unsigned(name, j.m_value.number_unsigned);
  8141. case value_t::string:
  8142. return write_bson_string(name, *j.m_value.string);
  8143. case value_t::null:
  8144. return write_bson_null(name);
  8145. // LCOV_EXCL_START
  8146. default:
  8147. assert(false);
  8148. return;
  8149. // LCOV_EXCL_STOP
  8150. };
  8151. }
  8152. /*!
  8153. @brief Calculates the size of the BSON serialization of the given
  8154. JSON-object @a j.
  8155. @param[in] j JSON value to serialize
  8156. @pre j.type() == value_t::object
  8157. */
  8158. static std::size_t calc_bson_object_size(const typename BasicJsonType::object_t& value)
  8159. {
  8160. std::size_t document_size = std::accumulate(value.begin(), value.end(), 0ul,
  8161. [](size_t result, const typename BasicJsonType::object_t::value_type & el)
  8162. {
  8163. return result += calc_bson_element_size(el.first, el.second);
  8164. });
  8165. return sizeof(std::int32_t) + document_size + 1ul;
  8166. }
  8167. /*!
  8168. @param[in] j JSON value to serialize
  8169. @pre j.type() == value_t::object
  8170. */
  8171. void write_bson_object(const typename BasicJsonType::object_t& value)
  8172. {
  8173. write_number<std::int32_t, true>(static_cast<std::int32_t>(calc_bson_object_size(value)));
  8174. for (const auto& el : value)
  8175. {
  8176. write_bson_element(el.first, el.second);
  8177. }
  8178. oa->write_character(to_char_type(0x00));
  8179. }
  8180. //////////
  8181. // CBOR //
  8182. //////////
  8183. static constexpr CharType get_cbor_float_prefix(float /*unused*/)
  8184. {
  8185. return to_char_type(0xFA); // Single-Precision Float
  8186. }
  8187. static constexpr CharType get_cbor_float_prefix(double /*unused*/)
  8188. {
  8189. return to_char_type(0xFB); // Double-Precision Float
  8190. }
  8191. /////////////
  8192. // MsgPack //
  8193. /////////////
  8194. static constexpr CharType get_msgpack_float_prefix(float /*unused*/)
  8195. {
  8196. return to_char_type(0xCA); // float 32
  8197. }
  8198. static constexpr CharType get_msgpack_float_prefix(double /*unused*/)
  8199. {
  8200. return to_char_type(0xCB); // float 64
  8201. }
  8202. ////////////
  8203. // UBJSON //
  8204. ////////////
  8205. // UBJSON: write number (floating point)
  8206. template<typename NumberType, typename std::enable_if<
  8207. std::is_floating_point<NumberType>::value, int>::type = 0>
  8208. void write_number_with_ubjson_prefix(const NumberType n,
  8209. const bool add_prefix)
  8210. {
  8211. if (add_prefix)
  8212. {
  8213. oa->write_character(get_ubjson_float_prefix(n));
  8214. }
  8215. write_number(n);
  8216. }
  8217. // UBJSON: write number (unsigned integer)
  8218. template<typename NumberType, typename std::enable_if<
  8219. std::is_unsigned<NumberType>::value, int>::type = 0>
  8220. void write_number_with_ubjson_prefix(const NumberType n,
  8221. const bool add_prefix)
  8222. {
  8223. if (n <= static_cast<uint64_t>((std::numeric_limits<int8_t>::max)()))
  8224. {
  8225. if (add_prefix)
  8226. {
  8227. oa->write_character(to_char_type('i')); // int8
  8228. }
  8229. write_number(static_cast<uint8_t>(n));
  8230. }
  8231. else if (n <= (std::numeric_limits<uint8_t>::max)())
  8232. {
  8233. if (add_prefix)
  8234. {
  8235. oa->write_character(to_char_type('U')); // uint8
  8236. }
  8237. write_number(static_cast<uint8_t>(n));
  8238. }
  8239. else if (n <= static_cast<uint64_t>((std::numeric_limits<int16_t>::max)()))
  8240. {
  8241. if (add_prefix)
  8242. {
  8243. oa->write_character(to_char_type('I')); // int16
  8244. }
  8245. write_number(static_cast<int16_t>(n));
  8246. }
  8247. else if (n <= static_cast<uint64_t>((std::numeric_limits<int32_t>::max)()))
  8248. {
  8249. if (add_prefix)
  8250. {
  8251. oa->write_character(to_char_type('l')); // int32
  8252. }
  8253. write_number(static_cast<int32_t>(n));
  8254. }
  8255. else if (n <= static_cast<uint64_t>((std::numeric_limits<int64_t>::max)()))
  8256. {
  8257. if (add_prefix)
  8258. {
  8259. oa->write_character(to_char_type('L')); // int64
  8260. }
  8261. write_number(static_cast<int64_t>(n));
  8262. }
  8263. else
  8264. {
  8265. JSON_THROW(out_of_range::create(407, "integer number " + std::to_string(n) + " cannot be represented by UBJSON as it does not fit int64"));
  8266. }
  8267. }
  8268. // UBJSON: write number (signed integer)
  8269. template<typename NumberType, typename std::enable_if<
  8270. std::is_signed<NumberType>::value and
  8271. not std::is_floating_point<NumberType>::value, int>::type = 0>
  8272. void write_number_with_ubjson_prefix(const NumberType n,
  8273. const bool add_prefix)
  8274. {
  8275. if ((std::numeric_limits<int8_t>::min)() <= n and n <= (std::numeric_limits<int8_t>::max)())
  8276. {
  8277. if (add_prefix)
  8278. {
  8279. oa->write_character(to_char_type('i')); // int8
  8280. }
  8281. write_number(static_cast<int8_t>(n));
  8282. }
  8283. 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)()))
  8284. {
  8285. if (add_prefix)
  8286. {
  8287. oa->write_character(to_char_type('U')); // uint8
  8288. }
  8289. write_number(static_cast<uint8_t>(n));
  8290. }
  8291. else if ((std::numeric_limits<int16_t>::min)() <= n and n <= (std::numeric_limits<int16_t>::max)())
  8292. {
  8293. if (add_prefix)
  8294. {
  8295. oa->write_character(to_char_type('I')); // int16
  8296. }
  8297. write_number(static_cast<int16_t>(n));
  8298. }
  8299. else if ((std::numeric_limits<int32_t>::min)() <= n and n <= (std::numeric_limits<int32_t>::max)())
  8300. {
  8301. if (add_prefix)
  8302. {
  8303. oa->write_character(to_char_type('l')); // int32
  8304. }
  8305. write_number(static_cast<int32_t>(n));
  8306. }
  8307. else if ((std::numeric_limits<int64_t>::min)() <= n and n <= (std::numeric_limits<int64_t>::max)())
  8308. {
  8309. if (add_prefix)
  8310. {
  8311. oa->write_character(to_char_type('L')); // int64
  8312. }
  8313. write_number(static_cast<int64_t>(n));
  8314. }
  8315. // LCOV_EXCL_START
  8316. else
  8317. {
  8318. JSON_THROW(out_of_range::create(407, "integer number " + std::to_string(n) + " cannot be represented by UBJSON as it does not fit int64"));
  8319. }
  8320. // LCOV_EXCL_STOP
  8321. }
  8322. /*!
  8323. @brief determine the type prefix of container values
  8324. @note This function does not need to be 100% accurate when it comes to
  8325. integer limits. In case a number exceeds the limits of int64_t,
  8326. this will be detected by a later call to function
  8327. write_number_with_ubjson_prefix. Therefore, we return 'L' for any
  8328. value that does not fit the previous limits.
  8329. */
  8330. CharType ubjson_prefix(const BasicJsonType& j) const noexcept
  8331. {
  8332. switch (j.type())
  8333. {
  8334. case value_t::null:
  8335. return 'Z';
  8336. case value_t::boolean:
  8337. return j.m_value.boolean ? 'T' : 'F';
  8338. case value_t::number_integer:
  8339. {
  8340. if ((std::numeric_limits<int8_t>::min)() <= j.m_value.number_integer and j.m_value.number_integer <= (std::numeric_limits<int8_t>::max)())
  8341. {
  8342. return 'i';
  8343. }
  8344. if ((std::numeric_limits<uint8_t>::min)() <= j.m_value.number_integer and j.m_value.number_integer <= (std::numeric_limits<uint8_t>::max)())
  8345. {
  8346. return 'U';
  8347. }
  8348. if ((std::numeric_limits<int16_t>::min)() <= j.m_value.number_integer and j.m_value.number_integer <= (std::numeric_limits<int16_t>::max)())
  8349. {
  8350. return 'I';
  8351. }
  8352. if ((std::numeric_limits<int32_t>::min)() <= j.m_value.number_integer and j.m_value.number_integer <= (std::numeric_limits<int32_t>::max)())
  8353. {
  8354. return 'l';
  8355. }
  8356. // no check and assume int64_t (see note above)
  8357. return 'L';
  8358. }
  8359. case value_t::number_unsigned:
  8360. {
  8361. if (j.m_value.number_unsigned <= (std::numeric_limits<int8_t>::max)())
  8362. {
  8363. return 'i';
  8364. }
  8365. if (j.m_value.number_unsigned <= (std::numeric_limits<uint8_t>::max)())
  8366. {
  8367. return 'U';
  8368. }
  8369. if (j.m_value.number_unsigned <= (std::numeric_limits<int16_t>::max)())
  8370. {
  8371. return 'I';
  8372. }
  8373. if (j.m_value.number_unsigned <= (std::numeric_limits<int32_t>::max)())
  8374. {
  8375. return 'l';
  8376. }
  8377. // no check and assume int64_t (see note above)
  8378. return 'L';
  8379. }
  8380. case value_t::number_float:
  8381. return get_ubjson_float_prefix(j.m_value.number_float);
  8382. case value_t::string:
  8383. return 'S';
  8384. case value_t::array:
  8385. return '[';
  8386. case value_t::object:
  8387. return '{';
  8388. default: // discarded values
  8389. return 'N';
  8390. }
  8391. }
  8392. static constexpr CharType get_ubjson_float_prefix(float /*unused*/)
  8393. {
  8394. return 'd'; // float 32
  8395. }
  8396. static constexpr CharType get_ubjson_float_prefix(double /*unused*/)
  8397. {
  8398. return 'D'; // float 64
  8399. }
  8400. ///////////////////////
  8401. // Utility functions //
  8402. ///////////////////////
  8403. /*
  8404. @brief write a number to output input
  8405. @param[in] n number of type @a NumberType
  8406. @tparam NumberType the type of the number
  8407. @tparam OutputIsLittleEndian Set to true if output data is
  8408. required to be little endian
  8409. @note This function needs to respect the system's endianess, because bytes
  8410. in CBOR, MessagePack, and UBJSON are stored in network order (big
  8411. endian) and therefore need reordering on little endian systems.
  8412. */
  8413. template<typename NumberType, bool OutputIsLittleEndian = false>
  8414. void write_number(const NumberType n)
  8415. {
  8416. // step 1: write number to array of length NumberType
  8417. std::array<CharType, sizeof(NumberType)> vec;
  8418. std::memcpy(vec.data(), &n, sizeof(NumberType));
  8419. // step 2: write array to output (with possible reordering)
  8420. if (is_little_endian and not OutputIsLittleEndian)
  8421. {
  8422. // reverse byte order prior to conversion if necessary
  8423. std::reverse(vec.begin(), vec.end());
  8424. }
  8425. oa->write_characters(vec.data(), sizeof(NumberType));
  8426. }
  8427. public:
  8428. // The following to_char_type functions are implement the conversion
  8429. // between uint8_t and CharType. In case CharType is not unsigned,
  8430. // such a conversion is required to allow values greater than 128.
  8431. // See <https://github.com/nlohmann/json/issues/1286> for a discussion.
  8432. template < typename C = CharType,
  8433. enable_if_t < std::is_signed<C>::value and std::is_signed<char>::value > * = nullptr >
  8434. static constexpr CharType to_char_type(std::uint8_t x) noexcept
  8435. {
  8436. return *reinterpret_cast<char*>(&x);
  8437. }
  8438. template < typename C = CharType,
  8439. enable_if_t < std::is_signed<C>::value and std::is_unsigned<char>::value > * = nullptr >
  8440. static CharType to_char_type(std::uint8_t x) noexcept
  8441. {
  8442. static_assert(sizeof(std::uint8_t) == sizeof(CharType), "size of CharType must be equal to std::uint8_t");
  8443. static_assert(std::is_pod<CharType>::value, "CharType must be POD");
  8444. CharType result;
  8445. std::memcpy(&result, &x, sizeof(x));
  8446. return result;
  8447. }
  8448. template<typename C = CharType,
  8449. enable_if_t<std::is_unsigned<C>::value>* = nullptr>
  8450. static constexpr CharType to_char_type(std::uint8_t x) noexcept
  8451. {
  8452. return x;
  8453. }
  8454. template < typename InputCharType, typename C = CharType,
  8455. enable_if_t <
  8456. std::is_signed<C>::value and
  8457. std::is_signed<char>::value and
  8458. std::is_same<char, typename std::remove_cv<InputCharType>::type>::value
  8459. > * = nullptr >
  8460. static constexpr CharType to_char_type(InputCharType x) noexcept
  8461. {
  8462. return x;
  8463. }
  8464. private:
  8465. /// whether we can assume little endianess
  8466. const bool is_little_endian = binary_reader<BasicJsonType>::little_endianess();
  8467. /// the output
  8468. output_adapter_t<CharType> oa = nullptr;
  8469. };
  8470. } // namespace detail
  8471. } // namespace nlohmann
  8472. // #include <nlohmann/detail/output/serializer.hpp>
  8473. #include <algorithm> // reverse, remove, fill, find, none_of
  8474. #include <array> // array
  8475. #include <cassert> // assert
  8476. #include <ciso646> // and, or
  8477. #include <clocale> // localeconv, lconv
  8478. #include <cmath> // labs, isfinite, isnan, signbit
  8479. #include <cstddef> // size_t, ptrdiff_t
  8480. #include <cstdint> // uint8_t
  8481. #include <cstdio> // snprintf
  8482. #include <limits> // numeric_limits
  8483. #include <string> // string
  8484. #include <type_traits> // is_same
  8485. // #include <nlohmann/detail/exceptions.hpp>
  8486. // #include <nlohmann/detail/conversions/to_chars.hpp>
  8487. #include <cassert> // assert
  8488. #include <ciso646> // or, and, not
  8489. #include <cmath> // signbit, isfinite
  8490. #include <cstdint> // intN_t, uintN_t
  8491. #include <cstring> // memcpy, memmove
  8492. namespace nlohmann
  8493. {
  8494. namespace detail
  8495. {
  8496. /*!
  8497. @brief implements the Grisu2 algorithm for binary to decimal floating-point
  8498. conversion.
  8499. This implementation is a slightly modified version of the reference
  8500. implementation which may be obtained from
  8501. http://florian.loitsch.com/publications (bench.tar.gz).
  8502. The code is distributed under the MIT license, Copyright (c) 2009 Florian Loitsch.
  8503. For a detailed description of the algorithm see:
  8504. [1] Loitsch, "Printing Floating-Point Numbers Quickly and Accurately with
  8505. Integers", Proceedings of the ACM SIGPLAN 2010 Conference on Programming
  8506. Language Design and Implementation, PLDI 2010
  8507. [2] Burger, Dybvig, "Printing Floating-Point Numbers Quickly and Accurately",
  8508. Proceedings of the ACM SIGPLAN 1996 Conference on Programming Language
  8509. Design and Implementation, PLDI 1996
  8510. */
  8511. namespace dtoa_impl
  8512. {
  8513. template <typename Target, typename Source>
  8514. Target reinterpret_bits(const Source source)
  8515. {
  8516. static_assert(sizeof(Target) == sizeof(Source), "size mismatch");
  8517. Target target;
  8518. std::memcpy(&target, &source, sizeof(Source));
  8519. return target;
  8520. }
  8521. struct diyfp // f * 2^e
  8522. {
  8523. static constexpr int kPrecision = 64; // = q
  8524. uint64_t f = 0;
  8525. int e = 0;
  8526. constexpr diyfp(uint64_t f_, int e_) noexcept : f(f_), e(e_) {}
  8527. /*!
  8528. @brief returns x - y
  8529. @pre x.e == y.e and x.f >= y.f
  8530. */
  8531. static diyfp sub(const diyfp& x, const diyfp& y) noexcept
  8532. {
  8533. assert(x.e == y.e);
  8534. assert(x.f >= y.f);
  8535. return {x.f - y.f, x.e};
  8536. }
  8537. /*!
  8538. @brief returns x * y
  8539. @note The result is rounded. (Only the upper q bits are returned.)
  8540. */
  8541. static diyfp mul(const diyfp& x, const diyfp& y) noexcept
  8542. {
  8543. static_assert(kPrecision == 64, "internal error");
  8544. // Computes:
  8545. // f = round((x.f * y.f) / 2^q)
  8546. // e = x.e + y.e + q
  8547. // Emulate the 64-bit * 64-bit multiplication:
  8548. //
  8549. // p = u * v
  8550. // = (u_lo + 2^32 u_hi) (v_lo + 2^32 v_hi)
  8551. // = (u_lo v_lo ) + 2^32 ((u_lo v_hi ) + (u_hi v_lo )) + 2^64 (u_hi v_hi )
  8552. // = (p0 ) + 2^32 ((p1 ) + (p2 )) + 2^64 (p3 )
  8553. // = (p0_lo + 2^32 p0_hi) + 2^32 ((p1_lo + 2^32 p1_hi) + (p2_lo + 2^32 p2_hi)) + 2^64 (p3 )
  8554. // = (p0_lo ) + 2^32 (p0_hi + p1_lo + p2_lo ) + 2^64 (p1_hi + p2_hi + p3)
  8555. // = (p0_lo ) + 2^32 (Q ) + 2^64 (H )
  8556. // = (p0_lo ) + 2^32 (Q_lo + 2^32 Q_hi ) + 2^64 (H )
  8557. //
  8558. // (Since Q might be larger than 2^32 - 1)
  8559. //
  8560. // = (p0_lo + 2^32 Q_lo) + 2^64 (Q_hi + H)
  8561. //
  8562. // (Q_hi + H does not overflow a 64-bit int)
  8563. //
  8564. // = p_lo + 2^64 p_hi
  8565. const uint64_t u_lo = x.f & 0xFFFFFFFF;
  8566. const uint64_t u_hi = x.f >> 32;
  8567. const uint64_t v_lo = y.f & 0xFFFFFFFF;
  8568. const uint64_t v_hi = y.f >> 32;
  8569. const uint64_t p0 = u_lo * v_lo;
  8570. const uint64_t p1 = u_lo * v_hi;
  8571. const uint64_t p2 = u_hi * v_lo;
  8572. const uint64_t p3 = u_hi * v_hi;
  8573. const uint64_t p0_hi = p0 >> 32;
  8574. const uint64_t p1_lo = p1 & 0xFFFFFFFF;
  8575. const uint64_t p1_hi = p1 >> 32;
  8576. const uint64_t p2_lo = p2 & 0xFFFFFFFF;
  8577. const uint64_t p2_hi = p2 >> 32;
  8578. uint64_t Q = p0_hi + p1_lo + p2_lo;
  8579. // The full product might now be computed as
  8580. //
  8581. // p_hi = p3 + p2_hi + p1_hi + (Q >> 32)
  8582. // p_lo = p0_lo + (Q << 32)
  8583. //
  8584. // But in this particular case here, the full p_lo is not required.
  8585. // Effectively we only need to add the highest bit in p_lo to p_hi (and
  8586. // Q_hi + 1 does not overflow).
  8587. Q += uint64_t{1} << (64 - 32 - 1); // round, ties up
  8588. const uint64_t h = p3 + p2_hi + p1_hi + (Q >> 32);
  8589. return {h, x.e + y.e + 64};
  8590. }
  8591. /*!
  8592. @brief normalize x such that the significand is >= 2^(q-1)
  8593. @pre x.f != 0
  8594. */
  8595. static diyfp normalize(diyfp x) noexcept
  8596. {
  8597. assert(x.f != 0);
  8598. while ((x.f >> 63) == 0)
  8599. {
  8600. x.f <<= 1;
  8601. x.e--;
  8602. }
  8603. return x;
  8604. }
  8605. /*!
  8606. @brief normalize x such that the result has the exponent E
  8607. @pre e >= x.e and the upper e - x.e bits of x.f must be zero.
  8608. */
  8609. static diyfp normalize_to(const diyfp& x, const int target_exponent) noexcept
  8610. {
  8611. const int delta = x.e - target_exponent;
  8612. assert(delta >= 0);
  8613. assert(((x.f << delta) >> delta) == x.f);
  8614. return {x.f << delta, target_exponent};
  8615. }
  8616. };
  8617. struct boundaries
  8618. {
  8619. diyfp w;
  8620. diyfp minus;
  8621. diyfp plus;
  8622. };
  8623. /*!
  8624. Compute the (normalized) diyfp representing the input number 'value' and its
  8625. boundaries.
  8626. @pre value must be finite and positive
  8627. */
  8628. template <typename FloatType>
  8629. boundaries compute_boundaries(FloatType value)
  8630. {
  8631. assert(std::isfinite(value));
  8632. assert(value > 0);
  8633. // Convert the IEEE representation into a diyfp.
  8634. //
  8635. // If v is denormal:
  8636. // value = 0.F * 2^(1 - bias) = ( F) * 2^(1 - bias - (p-1))
  8637. // If v is normalized:
  8638. // value = 1.F * 2^(E - bias) = (2^(p-1) + F) * 2^(E - bias - (p-1))
  8639. static_assert(std::numeric_limits<FloatType>::is_iec559,
  8640. "internal error: dtoa_short requires an IEEE-754 floating-point implementation");
  8641. constexpr int kPrecision = std::numeric_limits<FloatType>::digits; // = p (includes the hidden bit)
  8642. constexpr int kBias = std::numeric_limits<FloatType>::max_exponent - 1 + (kPrecision - 1);
  8643. constexpr int kMinExp = 1 - kBias;
  8644. constexpr uint64_t kHiddenBit = uint64_t{1} << (kPrecision - 1); // = 2^(p-1)
  8645. using bits_type = typename std::conditional< kPrecision == 24, uint32_t, uint64_t >::type;
  8646. const uint64_t bits = reinterpret_bits<bits_type>(value);
  8647. const uint64_t E = bits >> (kPrecision - 1);
  8648. const uint64_t F = bits & (kHiddenBit - 1);
  8649. const bool is_denormal = (E == 0);
  8650. const diyfp v = is_denormal
  8651. ? diyfp(F, kMinExp)
  8652. : diyfp(F + kHiddenBit, static_cast<int>(E) - kBias);
  8653. // Compute the boundaries m- and m+ of the floating-point value
  8654. // v = f * 2^e.
  8655. //
  8656. // Determine v- and v+, the floating-point predecessor and successor if v,
  8657. // respectively.
  8658. //
  8659. // v- = v - 2^e if f != 2^(p-1) or e == e_min (A)
  8660. // = v - 2^(e-1) if f == 2^(p-1) and e > e_min (B)
  8661. //
  8662. // v+ = v + 2^e
  8663. //
  8664. // Let m- = (v- + v) / 2 and m+ = (v + v+) / 2. All real numbers _strictly_
  8665. // between m- and m+ round to v, regardless of how the input rounding
  8666. // algorithm breaks ties.
  8667. //
  8668. // ---+-------------+-------------+-------------+-------------+--- (A)
  8669. // v- m- v m+ v+
  8670. //
  8671. // -----------------+------+------+-------------+-------------+--- (B)
  8672. // v- m- v m+ v+
  8673. const bool lower_boundary_is_closer = (F == 0 and E > 1);
  8674. const diyfp m_plus = diyfp(2 * v.f + 1, v.e - 1);
  8675. const diyfp m_minus = lower_boundary_is_closer
  8676. ? diyfp(4 * v.f - 1, v.e - 2) // (B)
  8677. : diyfp(2 * v.f - 1, v.e - 1); // (A)
  8678. // Determine the normalized w+ = m+.
  8679. const diyfp w_plus = diyfp::normalize(m_plus);
  8680. // Determine w- = m- such that e_(w-) = e_(w+).
  8681. const diyfp w_minus = diyfp::normalize_to(m_minus, w_plus.e);
  8682. return {diyfp::normalize(v), w_minus, w_plus};
  8683. }
  8684. // Given normalized diyfp w, Grisu needs to find a (normalized) cached
  8685. // power-of-ten c, such that the exponent of the product c * w = f * 2^e lies
  8686. // within a certain range [alpha, gamma] (Definition 3.2 from [1])
  8687. //
  8688. // alpha <= e = e_c + e_w + q <= gamma
  8689. //
  8690. // or
  8691. //
  8692. // f_c * f_w * 2^alpha <= f_c 2^(e_c) * f_w 2^(e_w) * 2^q
  8693. // <= f_c * f_w * 2^gamma
  8694. //
  8695. // Since c and w are normalized, i.e. 2^(q-1) <= f < 2^q, this implies
  8696. //
  8697. // 2^(q-1) * 2^(q-1) * 2^alpha <= c * w * 2^q < 2^q * 2^q * 2^gamma
  8698. //
  8699. // or
  8700. //
  8701. // 2^(q - 2 + alpha) <= c * w < 2^(q + gamma)
  8702. //
  8703. // The choice of (alpha,gamma) determines the size of the table and the form of
  8704. // the digit generation procedure. Using (alpha,gamma)=(-60,-32) works out well
  8705. // in practice:
  8706. //
  8707. // The idea is to cut the number c * w = f * 2^e into two parts, which can be
  8708. // processed independently: An integral part p1, and a fractional part p2:
  8709. //
  8710. // f * 2^e = ( (f div 2^-e) * 2^-e + (f mod 2^-e) ) * 2^e
  8711. // = (f div 2^-e) + (f mod 2^-e) * 2^e
  8712. // = p1 + p2 * 2^e
  8713. //
  8714. // The conversion of p1 into decimal form requires a series of divisions and
  8715. // modulos by (a power of) 10. These operations are faster for 32-bit than for
  8716. // 64-bit integers, so p1 should ideally fit into a 32-bit integer. This can be
  8717. // achieved by choosing
  8718. //
  8719. // -e >= 32 or e <= -32 := gamma
  8720. //
  8721. // In order to convert the fractional part
  8722. //
  8723. // p2 * 2^e = p2 / 2^-e = d[-1] / 10^1 + d[-2] / 10^2 + ...
  8724. //
  8725. // into decimal form, the fraction is repeatedly multiplied by 10 and the digits
  8726. // d[-i] are extracted in order:
  8727. //
  8728. // (10 * p2) div 2^-e = d[-1]
  8729. // (10 * p2) mod 2^-e = d[-2] / 10^1 + ...
  8730. //
  8731. // The multiplication by 10 must not overflow. It is sufficient to choose
  8732. //
  8733. // 10 * p2 < 16 * p2 = 2^4 * p2 <= 2^64.
  8734. //
  8735. // Since p2 = f mod 2^-e < 2^-e,
  8736. //
  8737. // -e <= 60 or e >= -60 := alpha
  8738. constexpr int kAlpha = -60;
  8739. constexpr int kGamma = -32;
  8740. struct cached_power // c = f * 2^e ~= 10^k
  8741. {
  8742. uint64_t f;
  8743. int e;
  8744. int k;
  8745. };
  8746. /*!
  8747. For a normalized diyfp w = f * 2^e, this function returns a (normalized) cached
  8748. power-of-ten c = f_c * 2^e_c, such that the exponent of the product w * c
  8749. satisfies (Definition 3.2 from [1])
  8750. alpha <= e_c + e + q <= gamma.
  8751. */
  8752. inline cached_power get_cached_power_for_binary_exponent(int e)
  8753. {
  8754. // Now
  8755. //
  8756. // alpha <= e_c + e + q <= gamma (1)
  8757. // ==> f_c * 2^alpha <= c * 2^e * 2^q
  8758. //
  8759. // and since the c's are normalized, 2^(q-1) <= f_c,
  8760. //
  8761. // ==> 2^(q - 1 + alpha) <= c * 2^(e + q)
  8762. // ==> 2^(alpha - e - 1) <= c
  8763. //
  8764. // If c were an exakt power of ten, i.e. c = 10^k, one may determine k as
  8765. //
  8766. // k = ceil( log_10( 2^(alpha - e - 1) ) )
  8767. // = ceil( (alpha - e - 1) * log_10(2) )
  8768. //
  8769. // From the paper:
  8770. // "In theory the result of the procedure could be wrong since c is rounded,
  8771. // and the computation itself is approximated [...]. In practice, however,
  8772. // this simple function is sufficient."
  8773. //
  8774. // For IEEE double precision floating-point numbers converted into
  8775. // normalized diyfp's w = f * 2^e, with q = 64,
  8776. //
  8777. // e >= -1022 (min IEEE exponent)
  8778. // -52 (p - 1)
  8779. // -52 (p - 1, possibly normalize denormal IEEE numbers)
  8780. // -11 (normalize the diyfp)
  8781. // = -1137
  8782. //
  8783. // and
  8784. //
  8785. // e <= +1023 (max IEEE exponent)
  8786. // -52 (p - 1)
  8787. // -11 (normalize the diyfp)
  8788. // = 960
  8789. //
  8790. // This binary exponent range [-1137,960] results in a decimal exponent
  8791. // range [-307,324]. One does not need to store a cached power for each
  8792. // k in this range. For each such k it suffices to find a cached power
  8793. // such that the exponent of the product lies in [alpha,gamma].
  8794. // This implies that the difference of the decimal exponents of adjacent
  8795. // table entries must be less than or equal to
  8796. //
  8797. // floor( (gamma - alpha) * log_10(2) ) = 8.
  8798. //
  8799. // (A smaller distance gamma-alpha would require a larger table.)
  8800. // NB:
  8801. // Actually this function returns c, such that -60 <= e_c + e + 64 <= -34.
  8802. constexpr int kCachedPowersSize = 79;
  8803. constexpr int kCachedPowersMinDecExp = -300;
  8804. constexpr int kCachedPowersDecStep = 8;
  8805. static constexpr cached_power kCachedPowers[] =
  8806. {
  8807. { 0xAB70FE17C79AC6CA, -1060, -300 },
  8808. { 0xFF77B1FCBEBCDC4F, -1034, -292 },
  8809. { 0xBE5691EF416BD60C, -1007, -284 },
  8810. { 0x8DD01FAD907FFC3C, -980, -276 },
  8811. { 0xD3515C2831559A83, -954, -268 },
  8812. { 0x9D71AC8FADA6C9B5, -927, -260 },
  8813. { 0xEA9C227723EE8BCB, -901, -252 },
  8814. { 0xAECC49914078536D, -874, -244 },
  8815. { 0x823C12795DB6CE57, -847, -236 },
  8816. { 0xC21094364DFB5637, -821, -228 },
  8817. { 0x9096EA6F3848984F, -794, -220 },
  8818. { 0xD77485CB25823AC7, -768, -212 },
  8819. { 0xA086CFCD97BF97F4, -741, -204 },
  8820. { 0xEF340A98172AACE5, -715, -196 },
  8821. { 0xB23867FB2A35B28E, -688, -188 },
  8822. { 0x84C8D4DFD2C63F3B, -661, -180 },
  8823. { 0xC5DD44271AD3CDBA, -635, -172 },
  8824. { 0x936B9FCEBB25C996, -608, -164 },
  8825. { 0xDBAC6C247D62A584, -582, -156 },
  8826. { 0xA3AB66580D5FDAF6, -555, -148 },
  8827. { 0xF3E2F893DEC3F126, -529, -140 },
  8828. { 0xB5B5ADA8AAFF80B8, -502, -132 },
  8829. { 0x87625F056C7C4A8B, -475, -124 },
  8830. { 0xC9BCFF6034C13053, -449, -116 },
  8831. { 0x964E858C91BA2655, -422, -108 },
  8832. { 0xDFF9772470297EBD, -396, -100 },
  8833. { 0xA6DFBD9FB8E5B88F, -369, -92 },
  8834. { 0xF8A95FCF88747D94, -343, -84 },
  8835. { 0xB94470938FA89BCF, -316, -76 },
  8836. { 0x8A08F0F8BF0F156B, -289, -68 },
  8837. { 0xCDB02555653131B6, -263, -60 },
  8838. { 0x993FE2C6D07B7FAC, -236, -52 },
  8839. { 0xE45C10C42A2B3B06, -210, -44 },
  8840. { 0xAA242499697392D3, -183, -36 },
  8841. { 0xFD87B5F28300CA0E, -157, -28 },
  8842. { 0xBCE5086492111AEB, -130, -20 },
  8843. { 0x8CBCCC096F5088CC, -103, -12 },
  8844. { 0xD1B71758E219652C, -77, -4 },
  8845. { 0x9C40000000000000, -50, 4 },
  8846. { 0xE8D4A51000000000, -24, 12 },
  8847. { 0xAD78EBC5AC620000, 3, 20 },
  8848. { 0x813F3978F8940984, 30, 28 },
  8849. { 0xC097CE7BC90715B3, 56, 36 },
  8850. { 0x8F7E32CE7BEA5C70, 83, 44 },
  8851. { 0xD5D238A4ABE98068, 109, 52 },
  8852. { 0x9F4F2726179A2245, 136, 60 },
  8853. { 0xED63A231D4C4FB27, 162, 68 },
  8854. { 0xB0DE65388CC8ADA8, 189, 76 },
  8855. { 0x83C7088E1AAB65DB, 216, 84 },
  8856. { 0xC45D1DF942711D9A, 242, 92 },
  8857. { 0x924D692CA61BE758, 269, 100 },
  8858. { 0xDA01EE641A708DEA, 295, 108 },
  8859. { 0xA26DA3999AEF774A, 322, 116 },
  8860. { 0xF209787BB47D6B85, 348, 124 },
  8861. { 0xB454E4A179DD1877, 375, 132 },
  8862. { 0x865B86925B9BC5C2, 402, 140 },
  8863. { 0xC83553C5C8965D3D, 428, 148 },
  8864. { 0x952AB45CFA97A0B3, 455, 156 },
  8865. { 0xDE469FBD99A05FE3, 481, 164 },
  8866. { 0xA59BC234DB398C25, 508, 172 },
  8867. { 0xF6C69A72A3989F5C, 534, 180 },
  8868. { 0xB7DCBF5354E9BECE, 561, 188 },
  8869. { 0x88FCF317F22241E2, 588, 196 },
  8870. { 0xCC20CE9BD35C78A5, 614, 204 },
  8871. { 0x98165AF37B2153DF, 641, 212 },
  8872. { 0xE2A0B5DC971F303A, 667, 220 },
  8873. { 0xA8D9D1535CE3B396, 694, 228 },
  8874. { 0xFB9B7CD9A4A7443C, 720, 236 },
  8875. { 0xBB764C4CA7A44410, 747, 244 },
  8876. { 0x8BAB8EEFB6409C1A, 774, 252 },
  8877. { 0xD01FEF10A657842C, 800, 260 },
  8878. { 0x9B10A4E5E9913129, 827, 268 },
  8879. { 0xE7109BFBA19C0C9D, 853, 276 },
  8880. { 0xAC2820D9623BF429, 880, 284 },
  8881. { 0x80444B5E7AA7CF85, 907, 292 },
  8882. { 0xBF21E44003ACDD2D, 933, 300 },
  8883. { 0x8E679C2F5E44FF8F, 960, 308 },
  8884. { 0xD433179D9C8CB841, 986, 316 },
  8885. { 0x9E19DB92B4E31BA9, 1013, 324 },
  8886. };
  8887. // This computation gives exactly the same results for k as
  8888. // k = ceil((kAlpha - e - 1) * 0.30102999566398114)
  8889. // for |e| <= 1500, but doesn't require floating-point operations.
  8890. // NB: log_10(2) ~= 78913 / 2^18
  8891. assert(e >= -1500);
  8892. assert(e <= 1500);
  8893. const int f = kAlpha - e - 1;
  8894. const int k = (f * 78913) / (1 << 18) + static_cast<int>(f > 0);
  8895. const int index = (-kCachedPowersMinDecExp + k + (kCachedPowersDecStep - 1)) / kCachedPowersDecStep;
  8896. assert(index >= 0);
  8897. assert(index < kCachedPowersSize);
  8898. static_cast<void>(kCachedPowersSize); // Fix warning.
  8899. const cached_power cached = kCachedPowers[index];
  8900. assert(kAlpha <= cached.e + e + 64);
  8901. assert(kGamma >= cached.e + e + 64);
  8902. return cached;
  8903. }
  8904. /*!
  8905. For n != 0, returns k, such that pow10 := 10^(k-1) <= n < 10^k.
  8906. For n == 0, returns 1 and sets pow10 := 1.
  8907. */
  8908. inline int find_largest_pow10(const uint32_t n, uint32_t& pow10)
  8909. {
  8910. // LCOV_EXCL_START
  8911. if (n >= 1000000000)
  8912. {
  8913. pow10 = 1000000000;
  8914. return 10;
  8915. }
  8916. // LCOV_EXCL_STOP
  8917. else if (n >= 100000000)
  8918. {
  8919. pow10 = 100000000;
  8920. return 9;
  8921. }
  8922. else if (n >= 10000000)
  8923. {
  8924. pow10 = 10000000;
  8925. return 8;
  8926. }
  8927. else if (n >= 1000000)
  8928. {
  8929. pow10 = 1000000;
  8930. return 7;
  8931. }
  8932. else if (n >= 100000)
  8933. {
  8934. pow10 = 100000;
  8935. return 6;
  8936. }
  8937. else if (n >= 10000)
  8938. {
  8939. pow10 = 10000;
  8940. return 5;
  8941. }
  8942. else if (n >= 1000)
  8943. {
  8944. pow10 = 1000;
  8945. return 4;
  8946. }
  8947. else if (n >= 100)
  8948. {
  8949. pow10 = 100;
  8950. return 3;
  8951. }
  8952. else if (n >= 10)
  8953. {
  8954. pow10 = 10;
  8955. return 2;
  8956. }
  8957. else
  8958. {
  8959. pow10 = 1;
  8960. return 1;
  8961. }
  8962. }
  8963. inline void grisu2_round(char* buf, int len, uint64_t dist, uint64_t delta,
  8964. uint64_t rest, uint64_t ten_k)
  8965. {
  8966. assert(len >= 1);
  8967. assert(dist <= delta);
  8968. assert(rest <= delta);
  8969. assert(ten_k > 0);
  8970. // <--------------------------- delta ---->
  8971. // <---- dist --------->
  8972. // --------------[------------------+-------------------]--------------
  8973. // M- w M+
  8974. //
  8975. // ten_k
  8976. // <------>
  8977. // <---- rest ---->
  8978. // --------------[------------------+----+--------------]--------------
  8979. // w V
  8980. // = buf * 10^k
  8981. //
  8982. // ten_k represents a unit-in-the-last-place in the decimal representation
  8983. // stored in buf.
  8984. // Decrement buf by ten_k while this takes buf closer to w.
  8985. // The tests are written in this order to avoid overflow in unsigned
  8986. // integer arithmetic.
  8987. while (rest < dist
  8988. and delta - rest >= ten_k
  8989. and (rest + ten_k < dist or dist - rest > rest + ten_k - dist))
  8990. {
  8991. assert(buf[len - 1] != '0');
  8992. buf[len - 1]--;
  8993. rest += ten_k;
  8994. }
  8995. }
  8996. /*!
  8997. Generates V = buffer * 10^decimal_exponent, such that M- <= V <= M+.
  8998. M- and M+ must be normalized and share the same exponent -60 <= e <= -32.
  8999. */
  9000. inline void grisu2_digit_gen(char* buffer, int& length, int& decimal_exponent,
  9001. diyfp M_minus, diyfp w, diyfp M_plus)
  9002. {
  9003. static_assert(kAlpha >= -60, "internal error");
  9004. static_assert(kGamma <= -32, "internal error");
  9005. // Generates the digits (and the exponent) of a decimal floating-point
  9006. // number V = buffer * 10^decimal_exponent in the range [M-, M+]. The diyfp's
  9007. // w, M- and M+ share the same exponent e, which satisfies alpha <= e <= gamma.
  9008. //
  9009. // <--------------------------- delta ---->
  9010. // <---- dist --------->
  9011. // --------------[------------------+-------------------]--------------
  9012. // M- w M+
  9013. //
  9014. // Grisu2 generates the digits of M+ from left to right and stops as soon as
  9015. // V is in [M-,M+].
  9016. assert(M_plus.e >= kAlpha);
  9017. assert(M_plus.e <= kGamma);
  9018. uint64_t delta = diyfp::sub(M_plus, M_minus).f; // (significand of (M+ - M-), implicit exponent is e)
  9019. uint64_t dist = diyfp::sub(M_plus, w ).f; // (significand of (M+ - w ), implicit exponent is e)
  9020. // Split M+ = f * 2^e into two parts p1 and p2 (note: e < 0):
  9021. //
  9022. // M+ = f * 2^e
  9023. // = ((f div 2^-e) * 2^-e + (f mod 2^-e)) * 2^e
  9024. // = ((p1 ) * 2^-e + (p2 )) * 2^e
  9025. // = p1 + p2 * 2^e
  9026. const diyfp one(uint64_t{1} << -M_plus.e, M_plus.e);
  9027. auto 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.)
  9028. uint64_t p2 = M_plus.f & (one.f - 1); // p2 = f mod 2^-e
  9029. // 1)
  9030. //
  9031. // Generate the digits of the integral part p1 = d[n-1]...d[1]d[0]
  9032. assert(p1 > 0);
  9033. uint32_t pow10;
  9034. const int k = find_largest_pow10(p1, pow10);
  9035. // 10^(k-1) <= p1 < 10^k, pow10 = 10^(k-1)
  9036. //
  9037. // p1 = (p1 div 10^(k-1)) * 10^(k-1) + (p1 mod 10^(k-1))
  9038. // = (d[k-1] ) * 10^(k-1) + (p1 mod 10^(k-1))
  9039. //
  9040. // M+ = p1 + p2 * 2^e
  9041. // = d[k-1] * 10^(k-1) + (p1 mod 10^(k-1)) + p2 * 2^e
  9042. // = d[k-1] * 10^(k-1) + ((p1 mod 10^(k-1)) * 2^-e + p2) * 2^e
  9043. // = d[k-1] * 10^(k-1) + ( rest) * 2^e
  9044. //
  9045. // Now generate the digits d[n] of p1 from left to right (n = k-1,...,0)
  9046. //
  9047. // p1 = d[k-1]...d[n] * 10^n + d[n-1]...d[0]
  9048. //
  9049. // but stop as soon as
  9050. //
  9051. // rest * 2^e = (d[n-1]...d[0] * 2^-e + p2) * 2^e <= delta * 2^e
  9052. int n = k;
  9053. while (n > 0)
  9054. {
  9055. // Invariants:
  9056. // M+ = buffer * 10^n + (p1 + p2 * 2^e) (buffer = 0 for n = k)
  9057. // pow10 = 10^(n-1) <= p1 < 10^n
  9058. //
  9059. const uint32_t d = p1 / pow10; // d = p1 div 10^(n-1)
  9060. const uint32_t r = p1 % pow10; // r = p1 mod 10^(n-1)
  9061. //
  9062. // M+ = buffer * 10^n + (d * 10^(n-1) + r) + p2 * 2^e
  9063. // = (buffer * 10 + d) * 10^(n-1) + (r + p2 * 2^e)
  9064. //
  9065. assert(d <= 9);
  9066. buffer[length++] = static_cast<char>('0' + d); // buffer := buffer * 10 + d
  9067. //
  9068. // M+ = buffer * 10^(n-1) + (r + p2 * 2^e)
  9069. //
  9070. p1 = r;
  9071. n--;
  9072. //
  9073. // M+ = buffer * 10^n + (p1 + p2 * 2^e)
  9074. // pow10 = 10^n
  9075. //
  9076. // Now check if enough digits have been generated.
  9077. // Compute
  9078. //
  9079. // p1 + p2 * 2^e = (p1 * 2^-e + p2) * 2^e = rest * 2^e
  9080. //
  9081. // Note:
  9082. // Since rest and delta share the same exponent e, it suffices to
  9083. // compare the significands.
  9084. const uint64_t rest = (uint64_t{p1} << -one.e) + p2;
  9085. if (rest <= delta)
  9086. {
  9087. // V = buffer * 10^n, with M- <= V <= M+.
  9088. decimal_exponent += n;
  9089. // We may now just stop. But instead look if the buffer could be
  9090. // decremented to bring V closer to w.
  9091. //
  9092. // pow10 = 10^n is now 1 ulp in the decimal representation V.
  9093. // The rounding procedure works with diyfp's with an implicit
  9094. // exponent of e.
  9095. //
  9096. // 10^n = (10^n * 2^-e) * 2^e = ulp * 2^e
  9097. //
  9098. const uint64_t ten_n = uint64_t{pow10} << -one.e;
  9099. grisu2_round(buffer, length, dist, delta, rest, ten_n);
  9100. return;
  9101. }
  9102. pow10 /= 10;
  9103. //
  9104. // pow10 = 10^(n-1) <= p1 < 10^n
  9105. // Invariants restored.
  9106. }
  9107. // 2)
  9108. //
  9109. // The digits of the integral part have been generated:
  9110. //
  9111. // M+ = d[k-1]...d[1]d[0] + p2 * 2^e
  9112. // = buffer + p2 * 2^e
  9113. //
  9114. // Now generate the digits of the fractional part p2 * 2^e.
  9115. //
  9116. // Note:
  9117. // No decimal point is generated: the exponent is adjusted instead.
  9118. //
  9119. // p2 actually represents the fraction
  9120. //
  9121. // p2 * 2^e
  9122. // = p2 / 2^-e
  9123. // = d[-1] / 10^1 + d[-2] / 10^2 + ...
  9124. //
  9125. // Now generate the digits d[-m] of p1 from left to right (m = 1,2,...)
  9126. //
  9127. // p2 * 2^e = d[-1]d[-2]...d[-m] * 10^-m
  9128. // + 10^-m * (d[-m-1] / 10^1 + d[-m-2] / 10^2 + ...)
  9129. //
  9130. // using
  9131. //
  9132. // 10^m * p2 = ((10^m * p2) div 2^-e) * 2^-e + ((10^m * p2) mod 2^-e)
  9133. // = ( d) * 2^-e + ( r)
  9134. //
  9135. // or
  9136. // 10^m * p2 * 2^e = d + r * 2^e
  9137. //
  9138. // i.e.
  9139. //
  9140. // M+ = buffer + p2 * 2^e
  9141. // = buffer + 10^-m * (d + r * 2^e)
  9142. // = (buffer * 10^m + d) * 10^-m + 10^-m * r * 2^e
  9143. //
  9144. // and stop as soon as 10^-m * r * 2^e <= delta * 2^e
  9145. assert(p2 > delta);
  9146. int m = 0;
  9147. for (;;)
  9148. {
  9149. // Invariant:
  9150. // M+ = buffer * 10^-m + 10^-m * (d[-m-1] / 10 + d[-m-2] / 10^2 + ...) * 2^e
  9151. // = buffer * 10^-m + 10^-m * (p2 ) * 2^e
  9152. // = buffer * 10^-m + 10^-m * (1/10 * (10 * p2) ) * 2^e
  9153. // = buffer * 10^-m + 10^-m * (1/10 * ((10*p2 div 2^-e) * 2^-e + (10*p2 mod 2^-e)) * 2^e
  9154. //
  9155. assert(p2 <= UINT64_MAX / 10);
  9156. p2 *= 10;
  9157. const uint64_t d = p2 >> -one.e; // d = (10 * p2) div 2^-e
  9158. const uint64_t r = p2 & (one.f - 1); // r = (10 * p2) mod 2^-e
  9159. //
  9160. // M+ = buffer * 10^-m + 10^-m * (1/10 * (d * 2^-e + r) * 2^e
  9161. // = buffer * 10^-m + 10^-m * (1/10 * (d + r * 2^e))
  9162. // = (buffer * 10 + d) * 10^(-m-1) + 10^(-m-1) * r * 2^e
  9163. //
  9164. assert(d <= 9);
  9165. buffer[length++] = static_cast<char>('0' + d); // buffer := buffer * 10 + d
  9166. //
  9167. // M+ = buffer * 10^(-m-1) + 10^(-m-1) * r * 2^e
  9168. //
  9169. p2 = r;
  9170. m++;
  9171. //
  9172. // M+ = buffer * 10^-m + 10^-m * p2 * 2^e
  9173. // Invariant restored.
  9174. // Check if enough digits have been generated.
  9175. //
  9176. // 10^-m * p2 * 2^e <= delta * 2^e
  9177. // p2 * 2^e <= 10^m * delta * 2^e
  9178. // p2 <= 10^m * delta
  9179. delta *= 10;
  9180. dist *= 10;
  9181. if (p2 <= delta)
  9182. {
  9183. break;
  9184. }
  9185. }
  9186. // V = buffer * 10^-m, with M- <= V <= M+.
  9187. decimal_exponent -= m;
  9188. // 1 ulp in the decimal representation is now 10^-m.
  9189. // Since delta and dist are now scaled by 10^m, we need to do the
  9190. // same with ulp in order to keep the units in sync.
  9191. //
  9192. // 10^m * 10^-m = 1 = 2^-e * 2^e = ten_m * 2^e
  9193. //
  9194. const uint64_t ten_m = one.f;
  9195. grisu2_round(buffer, length, dist, delta, p2, ten_m);
  9196. // By construction this algorithm generates the shortest possible decimal
  9197. // number (Loitsch, Theorem 6.2) which rounds back to w.
  9198. // For an input number of precision p, at least
  9199. //
  9200. // N = 1 + ceil(p * log_10(2))
  9201. //
  9202. // decimal digits are sufficient to identify all binary floating-point
  9203. // numbers (Matula, "In-and-Out conversions").
  9204. // This implies that the algorithm does not produce more than N decimal
  9205. // digits.
  9206. //
  9207. // N = 17 for p = 53 (IEEE double precision)
  9208. // N = 9 for p = 24 (IEEE single precision)
  9209. }
  9210. /*!
  9211. v = buf * 10^decimal_exponent
  9212. len is the length of the buffer (number of decimal digits)
  9213. The buffer must be large enough, i.e. >= max_digits10.
  9214. */
  9215. inline void grisu2(char* buf, int& len, int& decimal_exponent,
  9216. diyfp m_minus, diyfp v, diyfp m_plus)
  9217. {
  9218. assert(m_plus.e == m_minus.e);
  9219. assert(m_plus.e == v.e);
  9220. // --------(-----------------------+-----------------------)-------- (A)
  9221. // m- v m+
  9222. //
  9223. // --------------------(-----------+-----------------------)-------- (B)
  9224. // m- v m+
  9225. //
  9226. // First scale v (and m- and m+) such that the exponent is in the range
  9227. // [alpha, gamma].
  9228. const cached_power cached = get_cached_power_for_binary_exponent(m_plus.e);
  9229. const diyfp c_minus_k(cached.f, cached.e); // = c ~= 10^-k
  9230. // The exponent of the products is = v.e + c_minus_k.e + q and is in the range [alpha,gamma]
  9231. const diyfp w = diyfp::mul(v, c_minus_k);
  9232. const diyfp w_minus = diyfp::mul(m_minus, c_minus_k);
  9233. const diyfp w_plus = diyfp::mul(m_plus, c_minus_k);
  9234. // ----(---+---)---------------(---+---)---------------(---+---)----
  9235. // w- w w+
  9236. // = c*m- = c*v = c*m+
  9237. //
  9238. // diyfp::mul rounds its result and c_minus_k is approximated too. w, w- and
  9239. // w+ are now off by a small amount.
  9240. // In fact:
  9241. //
  9242. // w - v * 10^k < 1 ulp
  9243. //
  9244. // To account for this inaccuracy, add resp. subtract 1 ulp.
  9245. //
  9246. // --------+---[---------------(---+---)---------------]---+--------
  9247. // w- M- w M+ w+
  9248. //
  9249. // Now any number in [M-, M+] (bounds included) will round to w when input,
  9250. // regardless of how the input rounding algorithm breaks ties.
  9251. //
  9252. // And digit_gen generates the shortest possible such number in [M-, M+].
  9253. // Note that this does not mean that Grisu2 always generates the shortest
  9254. // possible number in the interval (m-, m+).
  9255. const diyfp M_minus(w_minus.f + 1, w_minus.e);
  9256. const diyfp M_plus (w_plus.f - 1, w_plus.e );
  9257. decimal_exponent = -cached.k; // = -(-k) = k
  9258. grisu2_digit_gen(buf, len, decimal_exponent, M_minus, w, M_plus);
  9259. }
  9260. /*!
  9261. v = buf * 10^decimal_exponent
  9262. len is the length of the buffer (number of decimal digits)
  9263. The buffer must be large enough, i.e. >= max_digits10.
  9264. */
  9265. template <typename FloatType>
  9266. void grisu2(char* buf, int& len, int& decimal_exponent, FloatType value)
  9267. {
  9268. static_assert(diyfp::kPrecision >= std::numeric_limits<FloatType>::digits + 3,
  9269. "internal error: not enough precision");
  9270. assert(std::isfinite(value));
  9271. assert(value > 0);
  9272. // If the neighbors (and boundaries) of 'value' are always computed for double-precision
  9273. // numbers, all float's can be recovered using strtod (and strtof). However, the resulting
  9274. // decimal representations are not exactly "short".
  9275. //
  9276. // The documentation for 'std::to_chars' (https://en.cppreference.com/w/cpp/utility/to_chars)
  9277. // says "value is converted to a string as if by std::sprintf in the default ("C") locale"
  9278. // and since sprintf promotes float's to double's, I think this is exactly what 'std::to_chars'
  9279. // does.
  9280. // On the other hand, the documentation for 'std::to_chars' requires that "parsing the
  9281. // representation using the corresponding std::from_chars function recovers value exactly". That
  9282. // indicates that single precision floating-point numbers should be recovered using
  9283. // 'std::strtof'.
  9284. //
  9285. // NB: If the neighbors are computed for single-precision numbers, there is a single float
  9286. // (7.0385307e-26f) which can't be recovered using strtod. The resulting double precision
  9287. // value is off by 1 ulp.
  9288. #if 0
  9289. const boundaries w = compute_boundaries(static_cast<double>(value));
  9290. #else
  9291. const boundaries w = compute_boundaries(value);
  9292. #endif
  9293. grisu2(buf, len, decimal_exponent, w.minus, w.w, w.plus);
  9294. }
  9295. /*!
  9296. @brief appends a decimal representation of e to buf
  9297. @return a pointer to the element following the exponent.
  9298. @pre -1000 < e < 1000
  9299. */
  9300. inline char* append_exponent(char* buf, int e)
  9301. {
  9302. assert(e > -1000);
  9303. assert(e < 1000);
  9304. if (e < 0)
  9305. {
  9306. e = -e;
  9307. *buf++ = '-';
  9308. }
  9309. else
  9310. {
  9311. *buf++ = '+';
  9312. }
  9313. auto k = static_cast<uint32_t>(e);
  9314. if (k < 10)
  9315. {
  9316. // Always print at least two digits in the exponent.
  9317. // This is for compatibility with printf("%g").
  9318. *buf++ = '0';
  9319. *buf++ = static_cast<char>('0' + k);
  9320. }
  9321. else if (k < 100)
  9322. {
  9323. *buf++ = static_cast<char>('0' + k / 10);
  9324. k %= 10;
  9325. *buf++ = static_cast<char>('0' + k);
  9326. }
  9327. else
  9328. {
  9329. *buf++ = static_cast<char>('0' + k / 100);
  9330. k %= 100;
  9331. *buf++ = static_cast<char>('0' + k / 10);
  9332. k %= 10;
  9333. *buf++ = static_cast<char>('0' + k);
  9334. }
  9335. return buf;
  9336. }
  9337. /*!
  9338. @brief prettify v = buf * 10^decimal_exponent
  9339. If v is in the range [10^min_exp, 10^max_exp) it will be printed in fixed-point
  9340. notation. Otherwise it will be printed in exponential notation.
  9341. @pre min_exp < 0
  9342. @pre max_exp > 0
  9343. */
  9344. inline char* format_buffer(char* buf, int len, int decimal_exponent,
  9345. int min_exp, int max_exp)
  9346. {
  9347. assert(min_exp < 0);
  9348. assert(max_exp > 0);
  9349. const int k = len;
  9350. const int n = len + decimal_exponent;
  9351. // v = buf * 10^(n-k)
  9352. // k is the length of the buffer (number of decimal digits)
  9353. // n is the position of the decimal point relative to the start of the buffer.
  9354. if (k <= n and n <= max_exp)
  9355. {
  9356. // digits[000]
  9357. // len <= max_exp + 2
  9358. std::memset(buf + k, '0', static_cast<size_t>(n - k));
  9359. // Make it look like a floating-point number (#362, #378)
  9360. buf[n + 0] = '.';
  9361. buf[n + 1] = '0';
  9362. return buf + (n + 2);
  9363. }
  9364. if (0 < n and n <= max_exp)
  9365. {
  9366. // dig.its
  9367. // len <= max_digits10 + 1
  9368. assert(k > n);
  9369. std::memmove(buf + (n + 1), buf + n, static_cast<size_t>(k - n));
  9370. buf[n] = '.';
  9371. return buf + (k + 1);
  9372. }
  9373. if (min_exp < n and n <= 0)
  9374. {
  9375. // 0.[000]digits
  9376. // len <= 2 + (-min_exp - 1) + max_digits10
  9377. std::memmove(buf + (2 + -n), buf, static_cast<size_t>(k));
  9378. buf[0] = '0';
  9379. buf[1] = '.';
  9380. std::memset(buf + 2, '0', static_cast<size_t>(-n));
  9381. return buf + (2 + (-n) + k);
  9382. }
  9383. if (k == 1)
  9384. {
  9385. // dE+123
  9386. // len <= 1 + 5
  9387. buf += 1;
  9388. }
  9389. else
  9390. {
  9391. // d.igitsE+123
  9392. // len <= max_digits10 + 1 + 5
  9393. std::memmove(buf + 2, buf + 1, static_cast<size_t>(k - 1));
  9394. buf[1] = '.';
  9395. buf += 1 + k;
  9396. }
  9397. *buf++ = 'e';
  9398. return append_exponent(buf, n - 1);
  9399. }
  9400. } // namespace dtoa_impl
  9401. /*!
  9402. @brief generates a decimal representation of the floating-point number value in [first, last).
  9403. The format of the resulting decimal representation is similar to printf's %g
  9404. format. Returns an iterator pointing past-the-end of the decimal representation.
  9405. @note The input number must be finite, i.e. NaN's and Inf's are not supported.
  9406. @note The buffer must be large enough.
  9407. @note The result is NOT null-terminated.
  9408. */
  9409. template <typename FloatType>
  9410. char* to_chars(char* first, const char* last, FloatType value)
  9411. {
  9412. static_cast<void>(last); // maybe unused - fix warning
  9413. assert(std::isfinite(value));
  9414. // Use signbit(value) instead of (value < 0) since signbit works for -0.
  9415. if (std::signbit(value))
  9416. {
  9417. value = -value;
  9418. *first++ = '-';
  9419. }
  9420. if (value == 0) // +-0
  9421. {
  9422. *first++ = '0';
  9423. // Make it look like a floating-point number (#362, #378)
  9424. *first++ = '.';
  9425. *first++ = '0';
  9426. return first;
  9427. }
  9428. assert(last - first >= std::numeric_limits<FloatType>::max_digits10);
  9429. // Compute v = buffer * 10^decimal_exponent.
  9430. // The decimal digits are stored in the buffer, which needs to be interpreted
  9431. // as an unsigned decimal integer.
  9432. // len is the length of the buffer, i.e. the number of decimal digits.
  9433. int len = 0;
  9434. int decimal_exponent = 0;
  9435. dtoa_impl::grisu2(first, len, decimal_exponent, value);
  9436. assert(len <= std::numeric_limits<FloatType>::max_digits10);
  9437. // Format the buffer like printf("%.*g", prec, value)
  9438. constexpr int kMinExp = -4;
  9439. // Use digits10 here to increase compatibility with version 2.
  9440. constexpr int kMaxExp = std::numeric_limits<FloatType>::digits10;
  9441. assert(last - first >= kMaxExp + 2);
  9442. assert(last - first >= 2 + (-kMinExp - 1) + std::numeric_limits<FloatType>::max_digits10);
  9443. assert(last - first >= std::numeric_limits<FloatType>::max_digits10 + 6);
  9444. return dtoa_impl::format_buffer(first, len, decimal_exponent, kMinExp, kMaxExp);
  9445. }
  9446. } // namespace detail
  9447. } // namespace nlohmann
  9448. // #include <nlohmann/detail/macro_scope.hpp>
  9449. // #include <nlohmann/detail/meta/cpp_future.hpp>
  9450. // #include <nlohmann/detail/output/binary_writer.hpp>
  9451. // #include <nlohmann/detail/output/output_adapters.hpp>
  9452. // #include <nlohmann/detail/value_t.hpp>
  9453. namespace nlohmann
  9454. {
  9455. namespace detail
  9456. {
  9457. ///////////////////
  9458. // serialization //
  9459. ///////////////////
  9460. /// how to treat decoding errors
  9461. enum class error_handler_t
  9462. {
  9463. strict, ///< throw a type_error exception in case of invalid UTF-8
  9464. replace, ///< replace invalid UTF-8 sequences with U+FFFD
  9465. ignore ///< ignore invalid UTF-8 sequences
  9466. };
  9467. template<typename BasicJsonType>
  9468. class serializer
  9469. {
  9470. using string_t = typename BasicJsonType::string_t;
  9471. using number_float_t = typename BasicJsonType::number_float_t;
  9472. using number_integer_t = typename BasicJsonType::number_integer_t;
  9473. using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
  9474. static constexpr uint8_t UTF8_ACCEPT = 0;
  9475. static constexpr uint8_t UTF8_REJECT = 1;
  9476. public:
  9477. /*!
  9478. @param[in] s output stream to serialize to
  9479. @param[in] ichar indentation character to use
  9480. @param[in] error_handler_ how to react on decoding errors
  9481. */
  9482. serializer(output_adapter_t<char> s, const char ichar,
  9483. error_handler_t error_handler_ = error_handler_t::strict)
  9484. : o(std::move(s))
  9485. , loc(std::localeconv())
  9486. , thousands_sep(loc->thousands_sep == nullptr ? '\0' : * (loc->thousands_sep))
  9487. , decimal_point(loc->decimal_point == nullptr ? '\0' : * (loc->decimal_point))
  9488. , indent_char(ichar)
  9489. , indent_string(512, indent_char)
  9490. , error_handler(error_handler_)
  9491. {}
  9492. // delete because of pointer members
  9493. serializer(const serializer&) = delete;
  9494. serializer& operator=(const serializer&) = delete;
  9495. serializer(serializer&&) = delete;
  9496. serializer& operator=(serializer&&) = delete;
  9497. ~serializer() = default;
  9498. /*!
  9499. @brief internal implementation of the serialization function
  9500. This function is called by the public member function dump and organizes
  9501. the serialization internally. The indentation level is propagated as
  9502. additional parameter. In case of arrays and objects, the function is
  9503. called recursively.
  9504. - strings and object keys are escaped using `escape_string()`
  9505. - integer numbers are converted implicitly via `operator<<`
  9506. - floating-point numbers are converted to a string using `"%g"` format
  9507. @param[in] val value to serialize
  9508. @param[in] pretty_print whether the output shall be pretty-printed
  9509. @param[in] indent_step the indent level
  9510. @param[in] current_indent the current indent level (only used internally)
  9511. */
  9512. void dump(const BasicJsonType& val, const bool pretty_print,
  9513. const bool ensure_ascii,
  9514. const unsigned int indent_step,
  9515. const unsigned int current_indent = 0)
  9516. {
  9517. switch (val.m_type)
  9518. {
  9519. case value_t::object:
  9520. {
  9521. if (val.m_value.object->empty())
  9522. {
  9523. o->write_characters("{}", 2);
  9524. return;
  9525. }
  9526. if (pretty_print)
  9527. {
  9528. o->write_characters("{\n", 2);
  9529. // variable to hold indentation for recursive calls
  9530. const auto new_indent = current_indent + indent_step;
  9531. if (JSON_UNLIKELY(indent_string.size() < new_indent))
  9532. {
  9533. indent_string.resize(indent_string.size() * 2, ' ');
  9534. }
  9535. // first n-1 elements
  9536. auto i = val.m_value.object->cbegin();
  9537. for (std::size_t cnt = 0; cnt < val.m_value.object->size() - 1; ++cnt, ++i)
  9538. {
  9539. o->write_characters(indent_string.c_str(), new_indent);
  9540. o->write_character('\"');
  9541. dump_escaped(i->first, ensure_ascii);
  9542. o->write_characters("\": ", 3);
  9543. dump(i->second, true, ensure_ascii, indent_step, new_indent);
  9544. o->write_characters(",\n", 2);
  9545. }
  9546. // last element
  9547. assert(i != val.m_value.object->cend());
  9548. assert(std::next(i) == val.m_value.object->cend());
  9549. o->write_characters(indent_string.c_str(), new_indent);
  9550. o->write_character('\"');
  9551. dump_escaped(i->first, ensure_ascii);
  9552. o->write_characters("\": ", 3);
  9553. dump(i->second, true, ensure_ascii, indent_step, new_indent);
  9554. o->write_character('\n');
  9555. o->write_characters(indent_string.c_str(), current_indent);
  9556. o->write_character('}');
  9557. }
  9558. else
  9559. {
  9560. o->write_character('{');
  9561. // first n-1 elements
  9562. auto i = val.m_value.object->cbegin();
  9563. for (std::size_t cnt = 0; cnt < val.m_value.object->size() - 1; ++cnt, ++i)
  9564. {
  9565. o->write_character('\"');
  9566. dump_escaped(i->first, ensure_ascii);
  9567. o->write_characters("\":", 2);
  9568. dump(i->second, false, ensure_ascii, indent_step, current_indent);
  9569. o->write_character(',');
  9570. }
  9571. // last element
  9572. assert(i != val.m_value.object->cend());
  9573. assert(std::next(i) == val.m_value.object->cend());
  9574. o->write_character('\"');
  9575. dump_escaped(i->first, ensure_ascii);
  9576. o->write_characters("\":", 2);
  9577. dump(i->second, false, ensure_ascii, indent_step, current_indent);
  9578. o->write_character('}');
  9579. }
  9580. return;
  9581. }
  9582. case value_t::array:
  9583. {
  9584. if (val.m_value.array->empty())
  9585. {
  9586. o->write_characters("[]", 2);
  9587. return;
  9588. }
  9589. if (pretty_print)
  9590. {
  9591. o->write_characters("[\n", 2);
  9592. // variable to hold indentation for recursive calls
  9593. const auto new_indent = current_indent + indent_step;
  9594. if (JSON_UNLIKELY(indent_string.size() < new_indent))
  9595. {
  9596. indent_string.resize(indent_string.size() * 2, ' ');
  9597. }
  9598. // first n-1 elements
  9599. for (auto i = val.m_value.array->cbegin();
  9600. i != val.m_value.array->cend() - 1; ++i)
  9601. {
  9602. o->write_characters(indent_string.c_str(), new_indent);
  9603. dump(*i, true, ensure_ascii, indent_step, new_indent);
  9604. o->write_characters(",\n", 2);
  9605. }
  9606. // last element
  9607. assert(not val.m_value.array->empty());
  9608. o->write_characters(indent_string.c_str(), new_indent);
  9609. dump(val.m_value.array->back(), true, ensure_ascii, indent_step, new_indent);
  9610. o->write_character('\n');
  9611. o->write_characters(indent_string.c_str(), current_indent);
  9612. o->write_character(']');
  9613. }
  9614. else
  9615. {
  9616. o->write_character('[');
  9617. // first n-1 elements
  9618. for (auto i = val.m_value.array->cbegin();
  9619. i != val.m_value.array->cend() - 1; ++i)
  9620. {
  9621. dump(*i, false, ensure_ascii, indent_step, current_indent);
  9622. o->write_character(',');
  9623. }
  9624. // last element
  9625. assert(not val.m_value.array->empty());
  9626. dump(val.m_value.array->back(), false, ensure_ascii, indent_step, current_indent);
  9627. o->write_character(']');
  9628. }
  9629. return;
  9630. }
  9631. case value_t::string:
  9632. {
  9633. o->write_character('\"');
  9634. dump_escaped(*val.m_value.string, ensure_ascii);
  9635. o->write_character('\"');
  9636. return;
  9637. }
  9638. case value_t::boolean:
  9639. {
  9640. if (val.m_value.boolean)
  9641. {
  9642. o->write_characters("true", 4);
  9643. }
  9644. else
  9645. {
  9646. o->write_characters("false", 5);
  9647. }
  9648. return;
  9649. }
  9650. case value_t::number_integer:
  9651. {
  9652. dump_integer(val.m_value.number_integer);
  9653. return;
  9654. }
  9655. case value_t::number_unsigned:
  9656. {
  9657. dump_integer(val.m_value.number_unsigned);
  9658. return;
  9659. }
  9660. case value_t::number_float:
  9661. {
  9662. dump_float(val.m_value.number_float);
  9663. return;
  9664. }
  9665. case value_t::discarded:
  9666. {
  9667. o->write_characters("<discarded>", 11);
  9668. return;
  9669. }
  9670. case value_t::null:
  9671. {
  9672. o->write_characters("null", 4);
  9673. return;
  9674. }
  9675. }
  9676. }
  9677. private:
  9678. /*!
  9679. @brief dump escaped string
  9680. Escape a string by replacing certain special characters by a sequence of an
  9681. escape character (backslash) and another character and other control
  9682. characters by a sequence of "\u" followed by a four-digit hex
  9683. representation. The escaped string is written to output stream @a o.
  9684. @param[in] s the string to escape
  9685. @param[in] ensure_ascii whether to escape non-ASCII characters with
  9686. \uXXXX sequences
  9687. @complexity Linear in the length of string @a s.
  9688. */
  9689. void dump_escaped(const string_t& s, const bool ensure_ascii)
  9690. {
  9691. uint32_t codepoint;
  9692. uint8_t state = UTF8_ACCEPT;
  9693. std::size_t bytes = 0; // number of bytes written to string_buffer
  9694. // number of bytes written at the point of the last valid byte
  9695. std::size_t bytes_after_last_accept = 0;
  9696. std::size_t undumped_chars = 0;
  9697. for (std::size_t i = 0; i < s.size(); ++i)
  9698. {
  9699. const auto byte = static_cast<uint8_t>(s[i]);
  9700. switch (decode(state, codepoint, byte))
  9701. {
  9702. case UTF8_ACCEPT: // decode found a new code point
  9703. {
  9704. switch (codepoint)
  9705. {
  9706. case 0x08: // backspace
  9707. {
  9708. string_buffer[bytes++] = '\\';
  9709. string_buffer[bytes++] = 'b';
  9710. break;
  9711. }
  9712. case 0x09: // horizontal tab
  9713. {
  9714. string_buffer[bytes++] = '\\';
  9715. string_buffer[bytes++] = 't';
  9716. break;
  9717. }
  9718. case 0x0A: // newline
  9719. {
  9720. string_buffer[bytes++] = '\\';
  9721. string_buffer[bytes++] = 'n';
  9722. break;
  9723. }
  9724. case 0x0C: // formfeed
  9725. {
  9726. string_buffer[bytes++] = '\\';
  9727. string_buffer[bytes++] = 'f';
  9728. break;
  9729. }
  9730. case 0x0D: // carriage return
  9731. {
  9732. string_buffer[bytes++] = '\\';
  9733. string_buffer[bytes++] = 'r';
  9734. break;
  9735. }
  9736. case 0x22: // quotation mark
  9737. {
  9738. string_buffer[bytes++] = '\\';
  9739. string_buffer[bytes++] = '\"';
  9740. break;
  9741. }
  9742. case 0x5C: // reverse solidus
  9743. {
  9744. string_buffer[bytes++] = '\\';
  9745. string_buffer[bytes++] = '\\';
  9746. break;
  9747. }
  9748. default:
  9749. {
  9750. // escape control characters (0x00..0x1F) or, if
  9751. // ensure_ascii parameter is used, non-ASCII characters
  9752. if ((codepoint <= 0x1F) or (ensure_ascii and (codepoint >= 0x7F)))
  9753. {
  9754. if (codepoint <= 0xFFFF)
  9755. {
  9756. (std::snprintf)(string_buffer.data() + bytes, 7, "\\u%04x",
  9757. static_cast<uint16_t>(codepoint));
  9758. bytes += 6;
  9759. }
  9760. else
  9761. {
  9762. (std::snprintf)(string_buffer.data() + bytes, 13, "\\u%04x\\u%04x",
  9763. static_cast<uint16_t>(0xD7C0 + (codepoint >> 10)),
  9764. static_cast<uint16_t>(0xDC00 + (codepoint & 0x3FF)));
  9765. bytes += 12;
  9766. }
  9767. }
  9768. else
  9769. {
  9770. // copy byte to buffer (all previous bytes
  9771. // been copied have in default case above)
  9772. string_buffer[bytes++] = s[i];
  9773. }
  9774. break;
  9775. }
  9776. }
  9777. // write buffer and reset index; there must be 13 bytes
  9778. // left, as this is the maximal number of bytes to be
  9779. // written ("\uxxxx\uxxxx\0") for one code point
  9780. if (string_buffer.size() - bytes < 13)
  9781. {
  9782. o->write_characters(string_buffer.data(), bytes);
  9783. bytes = 0;
  9784. }
  9785. // remember the byte position of this accept
  9786. bytes_after_last_accept = bytes;
  9787. undumped_chars = 0;
  9788. break;
  9789. }
  9790. case UTF8_REJECT: // decode found invalid UTF-8 byte
  9791. {
  9792. switch (error_handler)
  9793. {
  9794. case error_handler_t::strict:
  9795. {
  9796. std::string sn(3, '\0');
  9797. (std::snprintf)(&sn[0], sn.size(), "%.2X", byte);
  9798. JSON_THROW(type_error::create(316, "invalid UTF-8 byte at index " + std::to_string(i) + ": 0x" + sn));
  9799. }
  9800. case error_handler_t::ignore:
  9801. case error_handler_t::replace:
  9802. {
  9803. // in case we saw this character the first time, we
  9804. // would like to read it again, because the byte
  9805. // may be OK for itself, but just not OK for the
  9806. // previous sequence
  9807. if (undumped_chars > 0)
  9808. {
  9809. --i;
  9810. }
  9811. // reset length buffer to the last accepted index;
  9812. // thus removing/ignoring the invalid characters
  9813. bytes = bytes_after_last_accept;
  9814. if (error_handler == error_handler_t::replace)
  9815. {
  9816. // add a replacement character
  9817. if (ensure_ascii)
  9818. {
  9819. string_buffer[bytes++] = '\\';
  9820. string_buffer[bytes++] = 'u';
  9821. string_buffer[bytes++] = 'f';
  9822. string_buffer[bytes++] = 'f';
  9823. string_buffer[bytes++] = 'f';
  9824. string_buffer[bytes++] = 'd';
  9825. }
  9826. else
  9827. {
  9828. string_buffer[bytes++] = detail::binary_writer<BasicJsonType, char>::to_char_type('\xEF');
  9829. string_buffer[bytes++] = detail::binary_writer<BasicJsonType, char>::to_char_type('\xBF');
  9830. string_buffer[bytes++] = detail::binary_writer<BasicJsonType, char>::to_char_type('\xBD');
  9831. }
  9832. bytes_after_last_accept = bytes;
  9833. }
  9834. undumped_chars = 0;
  9835. // continue processing the string
  9836. state = UTF8_ACCEPT;
  9837. break;
  9838. }
  9839. }
  9840. break;
  9841. }
  9842. default: // decode found yet incomplete multi-byte code point
  9843. {
  9844. if (not ensure_ascii)
  9845. {
  9846. // code point will not be escaped - copy byte to buffer
  9847. string_buffer[bytes++] = s[i];
  9848. }
  9849. ++undumped_chars;
  9850. break;
  9851. }
  9852. }
  9853. }
  9854. // we finished processing the string
  9855. if (JSON_LIKELY(state == UTF8_ACCEPT))
  9856. {
  9857. // write buffer
  9858. if (bytes > 0)
  9859. {
  9860. o->write_characters(string_buffer.data(), bytes);
  9861. }
  9862. }
  9863. else
  9864. {
  9865. // we finish reading, but do not accept: string was incomplete
  9866. switch (error_handler)
  9867. {
  9868. case error_handler_t::strict:
  9869. {
  9870. std::string sn(3, '\0');
  9871. (std::snprintf)(&sn[0], sn.size(), "%.2X", static_cast<uint8_t>(s.back()));
  9872. JSON_THROW(type_error::create(316, "incomplete UTF-8 string; last byte: 0x" + sn));
  9873. }
  9874. case error_handler_t::ignore:
  9875. {
  9876. // write all accepted bytes
  9877. o->write_characters(string_buffer.data(), bytes_after_last_accept);
  9878. break;
  9879. }
  9880. case error_handler_t::replace:
  9881. {
  9882. // write all accepted bytes
  9883. o->write_characters(string_buffer.data(), bytes_after_last_accept);
  9884. // add a replacement character
  9885. if (ensure_ascii)
  9886. {
  9887. o->write_characters("\\ufffd", 6);
  9888. }
  9889. else
  9890. {
  9891. o->write_characters("\xEF\xBF\xBD", 3);
  9892. }
  9893. break;
  9894. }
  9895. }
  9896. }
  9897. }
  9898. /*!
  9899. @brief dump an integer
  9900. Dump a given integer to output stream @a o. Works internally with
  9901. @a number_buffer.
  9902. @param[in] x integer number (signed or unsigned) to dump
  9903. @tparam NumberType either @a number_integer_t or @a number_unsigned_t
  9904. */
  9905. template<typename NumberType, detail::enable_if_t<
  9906. std::is_same<NumberType, number_unsigned_t>::value or
  9907. std::is_same<NumberType, number_integer_t>::value,
  9908. int> = 0>
  9909. void dump_integer(NumberType x)
  9910. {
  9911. // special case for "0"
  9912. if (x == 0)
  9913. {
  9914. o->write_character('0');
  9915. return;
  9916. }
  9917. const bool is_negative = std::is_same<NumberType, number_integer_t>::value and not (x >= 0); // see issue #755
  9918. std::size_t i = 0;
  9919. while (x != 0)
  9920. {
  9921. // spare 1 byte for '\0'
  9922. assert(i < number_buffer.size() - 1);
  9923. const auto digit = std::labs(static_cast<long>(x % 10));
  9924. number_buffer[i++] = static_cast<char>('0' + digit);
  9925. x /= 10;
  9926. }
  9927. if (is_negative)
  9928. {
  9929. // make sure there is capacity for the '-'
  9930. assert(i < number_buffer.size() - 2);
  9931. number_buffer[i++] = '-';
  9932. }
  9933. std::reverse(number_buffer.begin(), number_buffer.begin() + i);
  9934. o->write_characters(number_buffer.data(), i);
  9935. }
  9936. /*!
  9937. @brief dump a floating-point number
  9938. Dump a given floating-point number to output stream @a o. Works internally
  9939. with @a number_buffer.
  9940. @param[in] x floating-point number to dump
  9941. */
  9942. void dump_float(number_float_t x)
  9943. {
  9944. // NaN / inf
  9945. if (not std::isfinite(x))
  9946. {
  9947. o->write_characters("null", 4);
  9948. return;
  9949. }
  9950. // If number_float_t is an IEEE-754 single or double precision number,
  9951. // use the Grisu2 algorithm to produce short numbers which are
  9952. // guaranteed to round-trip, using strtof and strtod, resp.
  9953. //
  9954. // NB: The test below works if <long double> == <double>.
  9955. static constexpr bool is_ieee_single_or_double
  9956. = (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
  9957. (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);
  9958. dump_float(x, std::integral_constant<bool, is_ieee_single_or_double>());
  9959. }
  9960. void dump_float(number_float_t x, std::true_type /*is_ieee_single_or_double*/)
  9961. {
  9962. char* begin = number_buffer.data();
  9963. char* end = ::nlohmann::detail::to_chars(begin, begin + number_buffer.size(), x);
  9964. o->write_characters(begin, static_cast<size_t>(end - begin));
  9965. }
  9966. void dump_float(number_float_t x, std::false_type /*is_ieee_single_or_double*/)
  9967. {
  9968. // get number of digits for a float -> text -> float round-trip
  9969. static constexpr auto d = std::numeric_limits<number_float_t>::max_digits10;
  9970. // the actual conversion
  9971. std::ptrdiff_t len = (std::snprintf)(number_buffer.data(), number_buffer.size(), "%.*g", d, x);
  9972. // negative value indicates an error
  9973. assert(len > 0);
  9974. // check if buffer was large enough
  9975. assert(static_cast<std::size_t>(len) < number_buffer.size());
  9976. // erase thousands separator
  9977. if (thousands_sep != '\0')
  9978. {
  9979. const auto end = std::remove(number_buffer.begin(),
  9980. number_buffer.begin() + len, thousands_sep);
  9981. std::fill(end, number_buffer.end(), '\0');
  9982. assert((end - number_buffer.begin()) <= len);
  9983. len = (end - number_buffer.begin());
  9984. }
  9985. // convert decimal point to '.'
  9986. if (decimal_point != '\0' and decimal_point != '.')
  9987. {
  9988. const auto dec_pos = std::find(number_buffer.begin(), number_buffer.end(), decimal_point);
  9989. if (dec_pos != number_buffer.end())
  9990. {
  9991. *dec_pos = '.';
  9992. }
  9993. }
  9994. o->write_characters(number_buffer.data(), static_cast<std::size_t>(len));
  9995. // determine if need to append ".0"
  9996. const bool value_is_int_like =
  9997. std::none_of(number_buffer.begin(), number_buffer.begin() + len + 1,
  9998. [](char c)
  9999. {
  10000. return (c == '.' or c == 'e');
  10001. });
  10002. if (value_is_int_like)
  10003. {
  10004. o->write_characters(".0", 2);
  10005. }
  10006. }
  10007. /*!
  10008. @brief check whether a string is UTF-8 encoded
  10009. The function checks each byte of a string whether it is UTF-8 encoded. The
  10010. result of the check is stored in the @a state parameter. The function must
  10011. be called initially with state 0 (accept). State 1 means the string must
  10012. be rejected, because the current byte is not allowed. If the string is
  10013. completely processed, but the state is non-zero, the string ended
  10014. prematurely; that is, the last byte indicated more bytes should have
  10015. followed.
  10016. @param[in,out] state the state of the decoding
  10017. @param[in,out] codep codepoint (valid only if resulting state is UTF8_ACCEPT)
  10018. @param[in] byte next byte to decode
  10019. @return new state
  10020. @note The function has been edited: a std::array is used.
  10021. @copyright Copyright (c) 2008-2009 Bjoern Hoehrmann <bjoern@hoehrmann.de>
  10022. @sa http://bjoern.hoehrmann.de/utf-8/decoder/dfa/
  10023. */
  10024. static uint8_t decode(uint8_t& state, uint32_t& codep, const uint8_t byte) noexcept
  10025. {
  10026. static const std::array<uint8_t, 400> utf8d =
  10027. {
  10028. {
  10029. 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
  10030. 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
  10031. 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
  10032. 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
  10033. 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
  10034. 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
  10035. 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
  10036. 0xA, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x4, 0x3, 0x3, // E0..EF
  10037. 0xB, 0x6, 0x6, 0x6, 0x5, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, // F0..FF
  10038. 0x0, 0x1, 0x2, 0x3, 0x5, 0x8, 0x7, 0x1, 0x1, 0x1, 0x4, 0x6, 0x1, 0x1, 0x1, 0x1, // s0..s0
  10039. 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
  10040. 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
  10041. 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
  10042. 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
  10043. }
  10044. };
  10045. const uint8_t type = utf8d[byte];
  10046. codep = (state != UTF8_ACCEPT)
  10047. ? (byte & 0x3fu) | (codep << 6)
  10048. : static_cast<uint32_t>(0xff >> type) & (byte);
  10049. state = utf8d[256u + state * 16u + type];
  10050. return state;
  10051. }
  10052. private:
  10053. /// the output of the serializer
  10054. output_adapter_t<char> o = nullptr;
  10055. /// a (hopefully) large enough character buffer
  10056. std::array<char, 64> number_buffer{{}};
  10057. /// the locale
  10058. const std::lconv* loc = nullptr;
  10059. /// the locale's thousand separator character
  10060. const char thousands_sep = '\0';
  10061. /// the locale's decimal point character
  10062. const char decimal_point = '\0';
  10063. /// string buffer
  10064. std::array<char, 512> string_buffer{{}};
  10065. /// the indentation character
  10066. const char indent_char;
  10067. /// the indentation string
  10068. string_t indent_string;
  10069. /// error_handler how to react on decoding errors
  10070. const error_handler_t error_handler;
  10071. };
  10072. } // namespace detail
  10073. } // namespace nlohmann
  10074. // #include <nlohmann/detail/json_ref.hpp>
  10075. #include <initializer_list>
  10076. #include <utility>
  10077. // #include <nlohmann/detail/meta/type_traits.hpp>
  10078. namespace nlohmann
  10079. {
  10080. namespace detail
  10081. {
  10082. template<typename BasicJsonType>
  10083. class json_ref
  10084. {
  10085. public:
  10086. using value_type = BasicJsonType;
  10087. json_ref(value_type&& value)
  10088. : owned_value(std::move(value)), value_ref(&owned_value), is_rvalue(true)
  10089. {}
  10090. json_ref(const value_type& value)
  10091. : value_ref(const_cast<value_type*>(&value)), is_rvalue(false)
  10092. {}
  10093. json_ref(std::initializer_list<json_ref> init)
  10094. : owned_value(init), value_ref(&owned_value), is_rvalue(true)
  10095. {}
  10096. template <
  10097. class... Args,
  10098. enable_if_t<std::is_constructible<value_type, Args...>::value, int> = 0 >
  10099. json_ref(Args && ... args)
  10100. : owned_value(std::forward<Args>(args)...), value_ref(&owned_value),
  10101. is_rvalue(true) {}
  10102. // class should be movable only
  10103. json_ref(json_ref&&) = default;
  10104. json_ref(const json_ref&) = delete;
  10105. json_ref& operator=(const json_ref&) = delete;
  10106. json_ref& operator=(json_ref&&) = delete;
  10107. ~json_ref() = default;
  10108. value_type moved_or_copied() const
  10109. {
  10110. if (is_rvalue)
  10111. {
  10112. return std::move(*value_ref);
  10113. }
  10114. return *value_ref;
  10115. }
  10116. value_type const& operator*() const
  10117. {
  10118. return *static_cast<value_type const*>(value_ref);
  10119. }
  10120. value_type const* operator->() const
  10121. {
  10122. return static_cast<value_type const*>(value_ref);
  10123. }
  10124. private:
  10125. mutable value_type owned_value = nullptr;
  10126. value_type* value_ref = nullptr;
  10127. const bool is_rvalue;
  10128. };
  10129. } // namespace detail
  10130. } // namespace nlohmann
  10131. // #include <nlohmann/detail/json_pointer.hpp>
  10132. #include <cassert> // assert
  10133. #include <numeric> // accumulate
  10134. #include <string> // string
  10135. #include <vector> // vector
  10136. // #include <nlohmann/detail/macro_scope.hpp>
  10137. // #include <nlohmann/detail/exceptions.hpp>
  10138. // #include <nlohmann/detail/value_t.hpp>
  10139. namespace nlohmann
  10140. {
  10141. template<typename BasicJsonType>
  10142. class json_pointer
  10143. {
  10144. // allow basic_json to access private members
  10145. NLOHMANN_BASIC_JSON_TPL_DECLARATION
  10146. friend class basic_json;
  10147. public:
  10148. /*!
  10149. @brief create JSON pointer
  10150. Create a JSON pointer according to the syntax described in
  10151. [Section 3 of RFC6901](https://tools.ietf.org/html/rfc6901#section-3).
  10152. @param[in] s string representing the JSON pointer; if omitted, the empty
  10153. string is assumed which references the whole JSON value
  10154. @throw parse_error.107 if the given JSON pointer @a s is nonempty and does
  10155. not begin with a slash (`/`); see example below
  10156. @throw parse_error.108 if a tilde (`~`) in the given JSON pointer @a s is
  10157. not followed by `0` (representing `~`) or `1` (representing `/`); see
  10158. example below
  10159. @liveexample{The example shows the construction several valid JSON pointers
  10160. as well as the exceptional behavior.,json_pointer}
  10161. @since version 2.0.0
  10162. */
  10163. explicit json_pointer(const std::string& s = "")
  10164. : reference_tokens(split(s))
  10165. {}
  10166. /*!
  10167. @brief return a string representation of the JSON pointer
  10168. @invariant For each JSON pointer `ptr`, it holds:
  10169. @code {.cpp}
  10170. ptr == json_pointer(ptr.to_string());
  10171. @endcode
  10172. @return a string representation of the JSON pointer
  10173. @liveexample{The example shows the result of `to_string`.,
  10174. json_pointer__to_string}
  10175. @since version 2.0.0
  10176. */
  10177. std::string to_string() const
  10178. {
  10179. return std::accumulate(reference_tokens.begin(), reference_tokens.end(),
  10180. std::string{},
  10181. [](const std::string & a, const std::string & b)
  10182. {
  10183. return a + "/" + escape(b);
  10184. });
  10185. }
  10186. /// @copydoc to_string()
  10187. operator std::string() const
  10188. {
  10189. return to_string();
  10190. }
  10191. /*!
  10192. @param[in] s reference token to be converted into an array index
  10193. @return integer representation of @a s
  10194. @throw out_of_range.404 if string @a s could not be converted to an integer
  10195. */
  10196. static int array_index(const std::string& s)
  10197. {
  10198. std::size_t processed_chars = 0;
  10199. const int res = std::stoi(s, &processed_chars);
  10200. // check if the string was completely read
  10201. if (JSON_UNLIKELY(processed_chars != s.size()))
  10202. {
  10203. JSON_THROW(detail::out_of_range::create(404, "unresolved reference token '" + s + "'"));
  10204. }
  10205. return res;
  10206. }
  10207. private:
  10208. /*!
  10209. @brief remove and return last reference pointer
  10210. @throw out_of_range.405 if JSON pointer has no parent
  10211. */
  10212. std::string pop_back()
  10213. {
  10214. if (JSON_UNLIKELY(is_root()))
  10215. {
  10216. JSON_THROW(detail::out_of_range::create(405, "JSON pointer has no parent"));
  10217. }
  10218. auto last = reference_tokens.back();
  10219. reference_tokens.pop_back();
  10220. return last;
  10221. }
  10222. /// return whether pointer points to the root document
  10223. bool is_root() const noexcept
  10224. {
  10225. return reference_tokens.empty();
  10226. }
  10227. json_pointer top() const
  10228. {
  10229. if (JSON_UNLIKELY(is_root()))
  10230. {
  10231. JSON_THROW(detail::out_of_range::create(405, "JSON pointer has no parent"));
  10232. }
  10233. json_pointer result = *this;
  10234. result.reference_tokens = {reference_tokens[0]};
  10235. return result;
  10236. }
  10237. /*!
  10238. @brief create and return a reference to the pointed to value
  10239. @complexity Linear in the number of reference tokens.
  10240. @throw parse_error.109 if array index is not a number
  10241. @throw type_error.313 if value cannot be unflattened
  10242. */
  10243. BasicJsonType& get_and_create(BasicJsonType& j) const
  10244. {
  10245. using size_type = typename BasicJsonType::size_type;
  10246. auto result = &j;
  10247. // in case no reference tokens exist, return a reference to the JSON value
  10248. // j which will be overwritten by a primitive value
  10249. for (const auto& reference_token : reference_tokens)
  10250. {
  10251. switch (result->m_type)
  10252. {
  10253. case detail::value_t::null:
  10254. {
  10255. if (reference_token == "0")
  10256. {
  10257. // start a new array if reference token is 0
  10258. result = &result->operator[](0);
  10259. }
  10260. else
  10261. {
  10262. // start a new object otherwise
  10263. result = &result->operator[](reference_token);
  10264. }
  10265. break;
  10266. }
  10267. case detail::value_t::object:
  10268. {
  10269. // create an entry in the object
  10270. result = &result->operator[](reference_token);
  10271. break;
  10272. }
  10273. case detail::value_t::array:
  10274. {
  10275. // create an entry in the array
  10276. JSON_TRY
  10277. {
  10278. result = &result->operator[](static_cast<size_type>(array_index(reference_token)));
  10279. }
  10280. JSON_CATCH(std::invalid_argument&)
  10281. {
  10282. JSON_THROW(detail::parse_error::create(109, 0, "array index '" + reference_token + "' is not a number"));
  10283. }
  10284. break;
  10285. }
  10286. /*
  10287. The following code is only reached if there exists a reference
  10288. token _and_ the current value is primitive. In this case, we have
  10289. an error situation, because primitive values may only occur as
  10290. single value; that is, with an empty list of reference tokens.
  10291. */
  10292. default:
  10293. JSON_THROW(detail::type_error::create(313, "invalid value to unflatten"));
  10294. }
  10295. }
  10296. return *result;
  10297. }
  10298. /*!
  10299. @brief return a reference to the pointed to value
  10300. @note This version does not throw if a value is not present, but tries to
  10301. create nested values instead. For instance, calling this function
  10302. with pointer `"/this/that"` on a null value is equivalent to calling
  10303. `operator[]("this").operator[]("that")` on that value, effectively
  10304. changing the null value to an object.
  10305. @param[in] ptr a JSON value
  10306. @return reference to the JSON value pointed to by the JSON pointer
  10307. @complexity Linear in the length of the JSON pointer.
  10308. @throw parse_error.106 if an array index begins with '0'
  10309. @throw parse_error.109 if an array index was not a number
  10310. @throw out_of_range.404 if the JSON pointer can not be resolved
  10311. */
  10312. BasicJsonType& get_unchecked(BasicJsonType* ptr) const
  10313. {
  10314. using size_type = typename BasicJsonType::size_type;
  10315. for (const auto& reference_token : reference_tokens)
  10316. {
  10317. // convert null values to arrays or objects before continuing
  10318. if (ptr->m_type == detail::value_t::null)
  10319. {
  10320. // check if reference token is a number
  10321. const bool nums =
  10322. std::all_of(reference_token.begin(), reference_token.end(),
  10323. [](const char x)
  10324. {
  10325. return (x >= '0' and x <= '9');
  10326. });
  10327. // change value to array for numbers or "-" or to object otherwise
  10328. *ptr = (nums or reference_token == "-")
  10329. ? detail::value_t::array
  10330. : detail::value_t::object;
  10331. }
  10332. switch (ptr->m_type)
  10333. {
  10334. case detail::value_t::object:
  10335. {
  10336. // use unchecked object access
  10337. ptr = &ptr->operator[](reference_token);
  10338. break;
  10339. }
  10340. case detail::value_t::array:
  10341. {
  10342. // error condition (cf. RFC 6901, Sect. 4)
  10343. if (JSON_UNLIKELY(reference_token.size() > 1 and reference_token[0] == '0'))
  10344. {
  10345. JSON_THROW(detail::parse_error::create(106, 0,
  10346. "array index '" + reference_token +
  10347. "' must not begin with '0'"));
  10348. }
  10349. if (reference_token == "-")
  10350. {
  10351. // explicitly treat "-" as index beyond the end
  10352. ptr = &ptr->operator[](ptr->m_value.array->size());
  10353. }
  10354. else
  10355. {
  10356. // convert array index to number; unchecked access
  10357. JSON_TRY
  10358. {
  10359. ptr = &ptr->operator[](
  10360. static_cast<size_type>(array_index(reference_token)));
  10361. }
  10362. JSON_CATCH(std::invalid_argument&)
  10363. {
  10364. JSON_THROW(detail::parse_error::create(109, 0, "array index '" + reference_token + "' is not a number"));
  10365. }
  10366. }
  10367. break;
  10368. }
  10369. default:
  10370. JSON_THROW(detail::out_of_range::create(404, "unresolved reference token '" + reference_token + "'"));
  10371. }
  10372. }
  10373. return *ptr;
  10374. }
  10375. /*!
  10376. @throw parse_error.106 if an array index begins with '0'
  10377. @throw parse_error.109 if an array index was not a number
  10378. @throw out_of_range.402 if the array index '-' is used
  10379. @throw out_of_range.404 if the JSON pointer can not be resolved
  10380. */
  10381. BasicJsonType& get_checked(BasicJsonType* ptr) const
  10382. {
  10383. using size_type = typename BasicJsonType::size_type;
  10384. for (const auto& reference_token : reference_tokens)
  10385. {
  10386. switch (ptr->m_type)
  10387. {
  10388. case detail::value_t::object:
  10389. {
  10390. // note: at performs range check
  10391. ptr = &ptr->at(reference_token);
  10392. break;
  10393. }
  10394. case detail::value_t::array:
  10395. {
  10396. if (JSON_UNLIKELY(reference_token == "-"))
  10397. {
  10398. // "-" always fails the range check
  10399. JSON_THROW(detail::out_of_range::create(402,
  10400. "array index '-' (" + std::to_string(ptr->m_value.array->size()) +
  10401. ") is out of range"));
  10402. }
  10403. // error condition (cf. RFC 6901, Sect. 4)
  10404. if (JSON_UNLIKELY(reference_token.size() > 1 and reference_token[0] == '0'))
  10405. {
  10406. JSON_THROW(detail::parse_error::create(106, 0,
  10407. "array index '" + reference_token +
  10408. "' must not begin with '0'"));
  10409. }
  10410. // note: at performs range check
  10411. JSON_TRY
  10412. {
  10413. ptr = &ptr->at(static_cast<size_type>(array_index(reference_token)));
  10414. }
  10415. JSON_CATCH(std::invalid_argument&)
  10416. {
  10417. JSON_THROW(detail::parse_error::create(109, 0, "array index '" + reference_token + "' is not a number"));
  10418. }
  10419. break;
  10420. }
  10421. default:
  10422. JSON_THROW(detail::out_of_range::create(404, "unresolved reference token '" + reference_token + "'"));
  10423. }
  10424. }
  10425. return *ptr;
  10426. }
  10427. /*!
  10428. @brief return a const reference to the pointed to value
  10429. @param[in] ptr a JSON value
  10430. @return const reference to the JSON value pointed to by the JSON
  10431. pointer
  10432. @throw parse_error.106 if an array index begins with '0'
  10433. @throw parse_error.109 if an array index was not a number
  10434. @throw out_of_range.402 if the array index '-' is used
  10435. @throw out_of_range.404 if the JSON pointer can not be resolved
  10436. */
  10437. const BasicJsonType& get_unchecked(const BasicJsonType* ptr) const
  10438. {
  10439. using size_type = typename BasicJsonType::size_type;
  10440. for (const auto& reference_token : reference_tokens)
  10441. {
  10442. switch (ptr->m_type)
  10443. {
  10444. case detail::value_t::object:
  10445. {
  10446. // use unchecked object access
  10447. ptr = &ptr->operator[](reference_token);
  10448. break;
  10449. }
  10450. case detail::value_t::array:
  10451. {
  10452. if (JSON_UNLIKELY(reference_token == "-"))
  10453. {
  10454. // "-" cannot be used for const access
  10455. JSON_THROW(detail::out_of_range::create(402,
  10456. "array index '-' (" + std::to_string(ptr->m_value.array->size()) +
  10457. ") is out of range"));
  10458. }
  10459. // error condition (cf. RFC 6901, Sect. 4)
  10460. if (JSON_UNLIKELY(reference_token.size() > 1 and reference_token[0] == '0'))
  10461. {
  10462. JSON_THROW(detail::parse_error::create(106, 0,
  10463. "array index '" + reference_token +
  10464. "' must not begin with '0'"));
  10465. }
  10466. // use unchecked array access
  10467. JSON_TRY
  10468. {
  10469. ptr = &ptr->operator[](
  10470. static_cast<size_type>(array_index(reference_token)));
  10471. }
  10472. JSON_CATCH(std::invalid_argument&)
  10473. {
  10474. JSON_THROW(detail::parse_error::create(109, 0, "array index '" + reference_token + "' is not a number"));
  10475. }
  10476. break;
  10477. }
  10478. default:
  10479. JSON_THROW(detail::out_of_range::create(404, "unresolved reference token '" + reference_token + "'"));
  10480. }
  10481. }
  10482. return *ptr;
  10483. }
  10484. /*!
  10485. @throw parse_error.106 if an array index begins with '0'
  10486. @throw parse_error.109 if an array index was not a number
  10487. @throw out_of_range.402 if the array index '-' is used
  10488. @throw out_of_range.404 if the JSON pointer can not be resolved
  10489. */
  10490. const BasicJsonType& get_checked(const BasicJsonType* ptr) const
  10491. {
  10492. using size_type = typename BasicJsonType::size_type;
  10493. for (const auto& reference_token : reference_tokens)
  10494. {
  10495. switch (ptr->m_type)
  10496. {
  10497. case detail::value_t::object:
  10498. {
  10499. // note: at performs range check
  10500. ptr = &ptr->at(reference_token);
  10501. break;
  10502. }
  10503. case detail::value_t::array:
  10504. {
  10505. if (JSON_UNLIKELY(reference_token == "-"))
  10506. {
  10507. // "-" always fails the range check
  10508. JSON_THROW(detail::out_of_range::create(402,
  10509. "array index '-' (" + std::to_string(ptr->m_value.array->size()) +
  10510. ") is out of range"));
  10511. }
  10512. // error condition (cf. RFC 6901, Sect. 4)
  10513. if (JSON_UNLIKELY(reference_token.size() > 1 and reference_token[0] == '0'))
  10514. {
  10515. JSON_THROW(detail::parse_error::create(106, 0,
  10516. "array index '" + reference_token +
  10517. "' must not begin with '0'"));
  10518. }
  10519. // note: at performs range check
  10520. JSON_TRY
  10521. {
  10522. ptr = &ptr->at(static_cast<size_type>(array_index(reference_token)));
  10523. }
  10524. JSON_CATCH(std::invalid_argument&)
  10525. {
  10526. JSON_THROW(detail::parse_error::create(109, 0, "array index '" + reference_token + "' is not a number"));
  10527. }
  10528. break;
  10529. }
  10530. default:
  10531. JSON_THROW(detail::out_of_range::create(404, "unresolved reference token '" + reference_token + "'"));
  10532. }
  10533. }
  10534. return *ptr;
  10535. }
  10536. /*!
  10537. @brief split the string input to reference tokens
  10538. @note This function is only called by the json_pointer constructor.
  10539. All exceptions below are documented there.
  10540. @throw parse_error.107 if the pointer is not empty or begins with '/'
  10541. @throw parse_error.108 if character '~' is not followed by '0' or '1'
  10542. */
  10543. static std::vector<std::string> split(const std::string& reference_string)
  10544. {
  10545. std::vector<std::string> result;
  10546. // special case: empty reference string -> no reference tokens
  10547. if (reference_string.empty())
  10548. {
  10549. return result;
  10550. }
  10551. // check if nonempty reference string begins with slash
  10552. if (JSON_UNLIKELY(reference_string[0] != '/'))
  10553. {
  10554. JSON_THROW(detail::parse_error::create(107, 1,
  10555. "JSON pointer must be empty or begin with '/' - was: '" +
  10556. reference_string + "'"));
  10557. }
  10558. // extract the reference tokens:
  10559. // - slash: position of the last read slash (or end of string)
  10560. // - start: position after the previous slash
  10561. for (
  10562. // search for the first slash after the first character
  10563. std::size_t slash = reference_string.find_first_of('/', 1),
  10564. // set the beginning of the first reference token
  10565. start = 1;
  10566. // we can stop if start == 0 (if slash == std::string::npos)
  10567. start != 0;
  10568. // set the beginning of the next reference token
  10569. // (will eventually be 0 if slash == std::string::npos)
  10570. start = (slash == std::string::npos) ? 0 : slash + 1,
  10571. // find next slash
  10572. slash = reference_string.find_first_of('/', start))
  10573. {
  10574. // use the text between the beginning of the reference token
  10575. // (start) and the last slash (slash).
  10576. auto reference_token = reference_string.substr(start, slash - start);
  10577. // check reference tokens are properly escaped
  10578. for (std::size_t pos = reference_token.find_first_of('~');
  10579. pos != std::string::npos;
  10580. pos = reference_token.find_first_of('~', pos + 1))
  10581. {
  10582. assert(reference_token[pos] == '~');
  10583. // ~ must be followed by 0 or 1
  10584. if (JSON_UNLIKELY(pos == reference_token.size() - 1 or
  10585. (reference_token[pos + 1] != '0' and
  10586. reference_token[pos + 1] != '1')))
  10587. {
  10588. JSON_THROW(detail::parse_error::create(108, 0, "escape character '~' must be followed with '0' or '1'"));
  10589. }
  10590. }
  10591. // finally, store the reference token
  10592. unescape(reference_token);
  10593. result.push_back(reference_token);
  10594. }
  10595. return result;
  10596. }
  10597. /*!
  10598. @brief replace all occurrences of a substring by another string
  10599. @param[in,out] s the string to manipulate; changed so that all
  10600. occurrences of @a f are replaced with @a t
  10601. @param[in] f the substring to replace with @a t
  10602. @param[in] t the string to replace @a f
  10603. @pre The search string @a f must not be empty. **This precondition is
  10604. enforced with an assertion.**
  10605. @since version 2.0.0
  10606. */
  10607. static void replace_substring(std::string& s, const std::string& f,
  10608. const std::string& t)
  10609. {
  10610. assert(not f.empty());
  10611. for (auto pos = s.find(f); // find first occurrence of f
  10612. pos != std::string::npos; // make sure f was found
  10613. s.replace(pos, f.size(), t), // replace with t, and
  10614. pos = s.find(f, pos + t.size())) // find next occurrence of f
  10615. {}
  10616. }
  10617. /// escape "~" to "~0" and "/" to "~1"
  10618. static std::string escape(std::string s)
  10619. {
  10620. replace_substring(s, "~", "~0");
  10621. replace_substring(s, "/", "~1");
  10622. return s;
  10623. }
  10624. /// unescape "~1" to tilde and "~0" to slash (order is important!)
  10625. static void unescape(std::string& s)
  10626. {
  10627. replace_substring(s, "~1", "/");
  10628. replace_substring(s, "~0", "~");
  10629. }
  10630. /*!
  10631. @param[in] reference_string the reference string to the current value
  10632. @param[in] value the value to consider
  10633. @param[in,out] result the result object to insert values to
  10634. @note Empty objects or arrays are flattened to `null`.
  10635. */
  10636. static void flatten(const std::string& reference_string,
  10637. const BasicJsonType& value,
  10638. BasicJsonType& result)
  10639. {
  10640. switch (value.m_type)
  10641. {
  10642. case detail::value_t::array:
  10643. {
  10644. if (value.m_value.array->empty())
  10645. {
  10646. // flatten empty array as null
  10647. result[reference_string] = nullptr;
  10648. }
  10649. else
  10650. {
  10651. // iterate array and use index as reference string
  10652. for (std::size_t i = 0; i < value.m_value.array->size(); ++i)
  10653. {
  10654. flatten(reference_string + "/" + std::to_string(i),
  10655. value.m_value.array->operator[](i), result);
  10656. }
  10657. }
  10658. break;
  10659. }
  10660. case detail::value_t::object:
  10661. {
  10662. if (value.m_value.object->empty())
  10663. {
  10664. // flatten empty object as null
  10665. result[reference_string] = nullptr;
  10666. }
  10667. else
  10668. {
  10669. // iterate object and use keys as reference string
  10670. for (const auto& element : *value.m_value.object)
  10671. {
  10672. flatten(reference_string + "/" + escape(element.first), element.second, result);
  10673. }
  10674. }
  10675. break;
  10676. }
  10677. default:
  10678. {
  10679. // add primitive value with its reference string
  10680. result[reference_string] = value;
  10681. break;
  10682. }
  10683. }
  10684. }
  10685. /*!
  10686. @param[in] value flattened JSON
  10687. @return unflattened JSON
  10688. @throw parse_error.109 if array index is not a number
  10689. @throw type_error.314 if value is not an object
  10690. @throw type_error.315 if object values are not primitive
  10691. @throw type_error.313 if value cannot be unflattened
  10692. */
  10693. static BasicJsonType
  10694. unflatten(const BasicJsonType& value)
  10695. {
  10696. if (JSON_UNLIKELY(not value.is_object()))
  10697. {
  10698. JSON_THROW(detail::type_error::create(314, "only objects can be unflattened"));
  10699. }
  10700. BasicJsonType result;
  10701. // iterate the JSON object values
  10702. for (const auto& element : *value.m_value.object)
  10703. {
  10704. if (JSON_UNLIKELY(not element.second.is_primitive()))
  10705. {
  10706. JSON_THROW(detail::type_error::create(315, "values in object must be primitive"));
  10707. }
  10708. // assign value to reference pointed to by JSON pointer; Note that if
  10709. // the JSON pointer is "" (i.e., points to the whole value), function
  10710. // get_and_create returns a reference to result itself. An assignment
  10711. // will then create a primitive value.
  10712. json_pointer(element.first).get_and_create(result) = element.second;
  10713. }
  10714. return result;
  10715. }
  10716. friend bool operator==(json_pointer const& lhs,
  10717. json_pointer const& rhs) noexcept
  10718. {
  10719. return (lhs.reference_tokens == rhs.reference_tokens);
  10720. }
  10721. friend bool operator!=(json_pointer const& lhs,
  10722. json_pointer const& rhs) noexcept
  10723. {
  10724. return not (lhs == rhs);
  10725. }
  10726. /// the reference tokens
  10727. std::vector<std::string> reference_tokens;
  10728. };
  10729. } // namespace nlohmann
  10730. // #include <nlohmann/adl_serializer.hpp>
  10731. #include <utility>
  10732. // #include <nlohmann/detail/conversions/from_json.hpp>
  10733. // #include <nlohmann/detail/conversions/to_json.hpp>
  10734. namespace nlohmann
  10735. {
  10736. template<typename, typename>
  10737. struct adl_serializer
  10738. {
  10739. /*!
  10740. @brief convert a JSON value to any value type
  10741. This function is usually called by the `get()` function of the
  10742. @ref basic_json class (either explicit or via conversion operators).
  10743. @param[in] j JSON value to read from
  10744. @param[in,out] val value to write to
  10745. */
  10746. template<typename BasicJsonType, typename ValueType>
  10747. static auto from_json(BasicJsonType&& j, ValueType& val) noexcept(
  10748. noexcept(::nlohmann::from_json(std::forward<BasicJsonType>(j), val)))
  10749. -> decltype(::nlohmann::from_json(std::forward<BasicJsonType>(j), val), void())
  10750. {
  10751. ::nlohmann::from_json(std::forward<BasicJsonType>(j), val);
  10752. }
  10753. /*!
  10754. @brief convert any value type to a JSON value
  10755. This function is usually called by the constructors of the @ref basic_json
  10756. class.
  10757. @param[in,out] j JSON value to write to
  10758. @param[in] val value to read from
  10759. */
  10760. template <typename BasicJsonType, typename ValueType>
  10761. static auto to_json(BasicJsonType& j, ValueType&& val) noexcept(
  10762. noexcept(::nlohmann::to_json(j, std::forward<ValueType>(val))))
  10763. -> decltype(::nlohmann::to_json(j, std::forward<ValueType>(val)), void())
  10764. {
  10765. ::nlohmann::to_json(j, std::forward<ValueType>(val));
  10766. }
  10767. };
  10768. } // namespace nlohmann
  10769. /*!
  10770. @brief namespace for Niels Lohmann
  10771. @see https://github.com/nlohmann
  10772. @since version 1.0.0
  10773. */
  10774. namespace nlohmann
  10775. {
  10776. /*!
  10777. @brief a class to store JSON values
  10778. @tparam ObjectType type for JSON objects (`std::map` by default; will be used
  10779. in @ref object_t)
  10780. @tparam ArrayType type for JSON arrays (`std::vector` by default; will be used
  10781. in @ref array_t)
  10782. @tparam StringType type for JSON strings and object keys (`std::string` by
  10783. default; will be used in @ref string_t)
  10784. @tparam BooleanType type for JSON booleans (`bool` by default; will be used
  10785. in @ref boolean_t)
  10786. @tparam NumberIntegerType type for JSON integer numbers (`int64_t` by
  10787. default; will be used in @ref number_integer_t)
  10788. @tparam NumberUnsignedType type for JSON unsigned integer numbers (@c
  10789. `uint64_t` by default; will be used in @ref number_unsigned_t)
  10790. @tparam NumberFloatType type for JSON floating-point numbers (`double` by
  10791. default; will be used in @ref number_float_t)
  10792. @tparam AllocatorType type of the allocator to use (`std::allocator` by
  10793. default)
  10794. @tparam JSONSerializer the serializer to resolve internal calls to `to_json()`
  10795. and `from_json()` (@ref adl_serializer by default)
  10796. @requirement The class satisfies the following concept requirements:
  10797. - Basic
  10798. - [DefaultConstructible](https://en.cppreference.com/w/cpp/named_req/DefaultConstructible):
  10799. JSON values can be default constructed. The result will be a JSON null
  10800. value.
  10801. - [MoveConstructible](https://en.cppreference.com/w/cpp/named_req/MoveConstructible):
  10802. A JSON value can be constructed from an rvalue argument.
  10803. - [CopyConstructible](https://en.cppreference.com/w/cpp/named_req/CopyConstructible):
  10804. A JSON value can be copy-constructed from an lvalue expression.
  10805. - [MoveAssignable](https://en.cppreference.com/w/cpp/named_req/MoveAssignable):
  10806. A JSON value van be assigned from an rvalue argument.
  10807. - [CopyAssignable](https://en.cppreference.com/w/cpp/named_req/CopyAssignable):
  10808. A JSON value can be copy-assigned from an lvalue expression.
  10809. - [Destructible](https://en.cppreference.com/w/cpp/named_req/Destructible):
  10810. JSON values can be destructed.
  10811. - Layout
  10812. - [StandardLayoutType](https://en.cppreference.com/w/cpp/named_req/StandardLayoutType):
  10813. JSON values have
  10814. [standard layout](https://en.cppreference.com/w/cpp/language/data_members#Standard_layout):
  10815. All non-static data members are private and standard layout types, the
  10816. class has no virtual functions or (virtual) base classes.
  10817. - Library-wide
  10818. - [EqualityComparable](https://en.cppreference.com/w/cpp/named_req/EqualityComparable):
  10819. JSON values can be compared with `==`, see @ref
  10820. operator==(const_reference,const_reference).
  10821. - [LessThanComparable](https://en.cppreference.com/w/cpp/named_req/LessThanComparable):
  10822. JSON values can be compared with `<`, see @ref
  10823. operator<(const_reference,const_reference).
  10824. - [Swappable](https://en.cppreference.com/w/cpp/named_req/Swappable):
  10825. Any JSON lvalue or rvalue of can be swapped with any lvalue or rvalue of
  10826. other compatible types, using unqualified function call @ref swap().
  10827. - [NullablePointer](https://en.cppreference.com/w/cpp/named_req/NullablePointer):
  10828. JSON values can be compared against `std::nullptr_t` objects which are used
  10829. to model the `null` value.
  10830. - Container
  10831. - [Container](https://en.cppreference.com/w/cpp/named_req/Container):
  10832. JSON values can be used like STL containers and provide iterator access.
  10833. - [ReversibleContainer](https://en.cppreference.com/w/cpp/named_req/ReversibleContainer);
  10834. JSON values can be used like STL containers and provide reverse iterator
  10835. access.
  10836. @invariant The member variables @a m_value and @a m_type have the following
  10837. relationship:
  10838. - If `m_type == value_t::object`, then `m_value.object != nullptr`.
  10839. - If `m_type == value_t::array`, then `m_value.array != nullptr`.
  10840. - If `m_type == value_t::string`, then `m_value.string != nullptr`.
  10841. The invariants are checked by member function assert_invariant().
  10842. @internal
  10843. @note ObjectType trick from http://stackoverflow.com/a/9860911
  10844. @endinternal
  10845. @see [RFC 7159: The JavaScript Object Notation (JSON) Data Interchange
  10846. Format](http://rfc7159.net/rfc7159)
  10847. @since version 1.0.0
  10848. @nosubgrouping
  10849. */
  10850. NLOHMANN_BASIC_JSON_TPL_DECLARATION
  10851. class basic_json
  10852. {
  10853. private:
  10854. template<detail::value_t> friend struct detail::external_constructor;
  10855. friend ::nlohmann::json_pointer<basic_json>;
  10856. friend ::nlohmann::detail::parser<basic_json>;
  10857. friend ::nlohmann::detail::serializer<basic_json>;
  10858. template<typename BasicJsonType>
  10859. friend class ::nlohmann::detail::iter_impl;
  10860. template<typename BasicJsonType, typename CharType>
  10861. friend class ::nlohmann::detail::binary_writer;
  10862. template<typename BasicJsonType, typename SAX>
  10863. friend class ::nlohmann::detail::binary_reader;
  10864. template<typename BasicJsonType>
  10865. friend class ::nlohmann::detail::json_sax_dom_parser;
  10866. template<typename BasicJsonType>
  10867. friend class ::nlohmann::detail::json_sax_dom_callback_parser;
  10868. /// workaround type for MSVC
  10869. using basic_json_t = NLOHMANN_BASIC_JSON_TPL;
  10870. // convenience aliases for types residing in namespace detail;
  10871. using lexer = ::nlohmann::detail::lexer<basic_json>;
  10872. using parser = ::nlohmann::detail::parser<basic_json>;
  10873. using primitive_iterator_t = ::nlohmann::detail::primitive_iterator_t;
  10874. template<typename BasicJsonType>
  10875. using internal_iterator = ::nlohmann::detail::internal_iterator<BasicJsonType>;
  10876. template<typename BasicJsonType>
  10877. using iter_impl = ::nlohmann::detail::iter_impl<BasicJsonType>;
  10878. template<typename Iterator>
  10879. using iteration_proxy = ::nlohmann::detail::iteration_proxy<Iterator>;
  10880. template<typename Base> using json_reverse_iterator = ::nlohmann::detail::json_reverse_iterator<Base>;
  10881. template<typename CharType>
  10882. using output_adapter_t = ::nlohmann::detail::output_adapter_t<CharType>;
  10883. using binary_reader = ::nlohmann::detail::binary_reader<basic_json>;
  10884. template<typename CharType> using binary_writer = ::nlohmann::detail::binary_writer<basic_json, CharType>;
  10885. using serializer = ::nlohmann::detail::serializer<basic_json>;
  10886. public:
  10887. using value_t = detail::value_t;
  10888. /// JSON Pointer, see @ref nlohmann::json_pointer
  10889. using json_pointer = ::nlohmann::json_pointer<basic_json>;
  10890. template<typename T, typename SFINAE>
  10891. using json_serializer = JSONSerializer<T, SFINAE>;
  10892. /// how to treat decoding errors
  10893. using error_handler_t = detail::error_handler_t;
  10894. /// helper type for initializer lists of basic_json values
  10895. using initializer_list_t = std::initializer_list<detail::json_ref<basic_json>>;
  10896. using input_format_t = detail::input_format_t;
  10897. /// SAX interface type, see @ref nlohmann::json_sax
  10898. using json_sax_t = json_sax<basic_json>;
  10899. ////////////////
  10900. // exceptions //
  10901. ////////////////
  10902. /// @name exceptions
  10903. /// Classes to implement user-defined exceptions.
  10904. /// @{
  10905. /// @copydoc detail::exception
  10906. using exception = detail::exception;
  10907. /// @copydoc detail::parse_error
  10908. using parse_error = detail::parse_error;
  10909. /// @copydoc detail::invalid_iterator
  10910. using invalid_iterator = detail::invalid_iterator;
  10911. /// @copydoc detail::type_error
  10912. using type_error = detail::type_error;
  10913. /// @copydoc detail::out_of_range
  10914. using out_of_range = detail::out_of_range;
  10915. /// @copydoc detail::other_error
  10916. using other_error = detail::other_error;
  10917. /// @}
  10918. /////////////////////
  10919. // container types //
  10920. /////////////////////
  10921. /// @name container types
  10922. /// The canonic container types to use @ref basic_json like any other STL
  10923. /// container.
  10924. /// @{
  10925. /// the type of elements in a basic_json container
  10926. using value_type = basic_json;
  10927. /// the type of an element reference
  10928. using reference = value_type&;
  10929. /// the type of an element const reference
  10930. using const_reference = const value_type&;
  10931. /// a type to represent differences between iterators
  10932. using difference_type = std::ptrdiff_t;
  10933. /// a type to represent container sizes
  10934. using size_type = std::size_t;
  10935. /// the allocator type
  10936. using allocator_type = AllocatorType<basic_json>;
  10937. /// the type of an element pointer
  10938. using pointer = typename std::allocator_traits<allocator_type>::pointer;
  10939. /// the type of an element const pointer
  10940. using const_pointer = typename std::allocator_traits<allocator_type>::const_pointer;
  10941. /// an iterator for a basic_json container
  10942. using iterator = iter_impl<basic_json>;
  10943. /// a const iterator for a basic_json container
  10944. using const_iterator = iter_impl<const basic_json>;
  10945. /// a reverse iterator for a basic_json container
  10946. using reverse_iterator = json_reverse_iterator<typename basic_json::iterator>;
  10947. /// a const reverse iterator for a basic_json container
  10948. using const_reverse_iterator = json_reverse_iterator<typename basic_json::const_iterator>;
  10949. /// @}
  10950. /*!
  10951. @brief returns the allocator associated with the container
  10952. */
  10953. static allocator_type get_allocator()
  10954. {
  10955. return allocator_type();
  10956. }
  10957. /*!
  10958. @brief returns version information on the library
  10959. This function returns a JSON object with information about the library,
  10960. including the version number and information on the platform and compiler.
  10961. @return JSON object holding version information
  10962. key | description
  10963. ----------- | ---------------
  10964. `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).
  10965. `copyright` | The copyright line for the library as string.
  10966. `name` | The name of the library as string.
  10967. `platform` | The used platform as string. Possible values are `win32`, `linux`, `apple`, `unix`, and `unknown`.
  10968. `url` | The URL of the project as string.
  10969. `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).
  10970. @liveexample{The following code shows an example output of the `meta()`
  10971. function.,meta}
  10972. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  10973. changes to any JSON value.
  10974. @complexity Constant.
  10975. @since 2.1.0
  10976. */
  10977. static basic_json meta()
  10978. {
  10979. basic_json result;
  10980. result["copyright"] = "(C) 2013-2017 Niels Lohmann";
  10981. result["name"] = "JSON for Modern C++";
  10982. result["url"] = "https://github.com/nlohmann/json";
  10983. result["version"]["string"] =
  10984. std::to_string(NLOHMANN_JSON_VERSION_MAJOR) + "." +
  10985. std::to_string(NLOHMANN_JSON_VERSION_MINOR) + "." +
  10986. std::to_string(NLOHMANN_JSON_VERSION_PATCH);
  10987. result["version"]["major"] = NLOHMANN_JSON_VERSION_MAJOR;
  10988. result["version"]["minor"] = NLOHMANN_JSON_VERSION_MINOR;
  10989. result["version"]["patch"] = NLOHMANN_JSON_VERSION_PATCH;
  10990. #ifdef _WIN32
  10991. result["platform"] = "win32";
  10992. #elif defined __linux__
  10993. result["platform"] = "linux";
  10994. #elif defined __APPLE__
  10995. result["platform"] = "apple";
  10996. #elif defined __unix__
  10997. result["platform"] = "unix";
  10998. #else
  10999. result["platform"] = "unknown";
  11000. #endif
  11001. #if defined(__ICC) || defined(__INTEL_COMPILER)
  11002. result["compiler"] = {{"family", "icc"}, {"version", __INTEL_COMPILER}};
  11003. #elif defined(__clang__)
  11004. result["compiler"] = {{"family", "clang"}, {"version", __clang_version__}};
  11005. #elif defined(__GNUC__) || defined(__GNUG__)
  11006. result["compiler"] = {{"family", "gcc"}, {"version", std::to_string(__GNUC__) + "." + std::to_string(__GNUC_MINOR__) + "." + std::to_string(__GNUC_PATCHLEVEL__)}};
  11007. #elif defined(__HP_cc) || defined(__HP_aCC)
  11008. result["compiler"] = "hp"
  11009. #elif defined(__IBMCPP__)
  11010. result["compiler"] = {{"family", "ilecpp"}, {"version", __IBMCPP__}};
  11011. #elif defined(_MSC_VER)
  11012. result["compiler"] = {{"family", "msvc"}, {"version", _MSC_VER}};
  11013. #elif defined(__PGI)
  11014. result["compiler"] = {{"family", "pgcpp"}, {"version", __PGI}};
  11015. #elif defined(__SUNPRO_CC)
  11016. result["compiler"] = {{"family", "sunpro"}, {"version", __SUNPRO_CC}};
  11017. #else
  11018. result["compiler"] = {{"family", "unknown"}, {"version", "unknown"}};
  11019. #endif
  11020. #ifdef __cplusplus
  11021. result["compiler"]["c++"] = std::to_string(__cplusplus);
  11022. #else
  11023. result["compiler"]["c++"] = "unknown";
  11024. #endif
  11025. return result;
  11026. }
  11027. ///////////////////////////
  11028. // JSON value data types //
  11029. ///////////////////////////
  11030. /// @name JSON value data types
  11031. /// The data types to store a JSON value. These types are derived from
  11032. /// the template arguments passed to class @ref basic_json.
  11033. /// @{
  11034. #if defined(JSON_HAS_CPP_14)
  11035. // Use transparent comparator if possible, combined with perfect forwarding
  11036. // on find() and count() calls prevents unnecessary string construction.
  11037. using object_comparator_t = std::less<>;
  11038. #else
  11039. using object_comparator_t = std::less<StringType>;
  11040. #endif
  11041. /*!
  11042. @brief a type for an object
  11043. [RFC 7159](http://rfc7159.net/rfc7159) describes JSON objects as follows:
  11044. > An object is an unordered collection of zero or more name/value pairs,
  11045. > where a name is a string and a value is a string, number, boolean, null,
  11046. > object, or array.
  11047. To store objects in C++, a type is defined by the template parameters
  11048. described below.
  11049. @tparam ObjectType the container to store objects (e.g., `std::map` or
  11050. `std::unordered_map`)
  11051. @tparam StringType the type of the keys or names (e.g., `std::string`).
  11052. The comparison function `std::less<StringType>` is used to order elements
  11053. inside the container.
  11054. @tparam AllocatorType the allocator to use for objects (e.g.,
  11055. `std::allocator`)
  11056. #### Default type
  11057. With the default values for @a ObjectType (`std::map`), @a StringType
  11058. (`std::string`), and @a AllocatorType (`std::allocator`), the default
  11059. value for @a object_t is:
  11060. @code {.cpp}
  11061. std::map<
  11062. std::string, // key_type
  11063. basic_json, // value_type
  11064. std::less<std::string>, // key_compare
  11065. std::allocator<std::pair<const std::string, basic_json>> // allocator_type
  11066. >
  11067. @endcode
  11068. #### Behavior
  11069. The choice of @a object_t influences the behavior of the JSON class. With
  11070. the default type, objects have the following behavior:
  11071. - When all names are unique, objects will be interoperable in the sense
  11072. that all software implementations receiving that object will agree on
  11073. the name-value mappings.
  11074. - When the names within an object are not unique, it is unspecified which
  11075. one of the values for a given key will be chosen. For instance,
  11076. `{"key": 2, "key": 1}` could be equal to either `{"key": 1}` or
  11077. `{"key": 2}`.
  11078. - Internally, name/value pairs are stored in lexicographical order of the
  11079. names. Objects will also be serialized (see @ref dump) in this order.
  11080. For instance, `{"b": 1, "a": 2}` and `{"a": 2, "b": 1}` will be stored
  11081. and serialized as `{"a": 2, "b": 1}`.
  11082. - When comparing objects, the order of the name/value pairs is irrelevant.
  11083. This makes objects interoperable in the sense that they will not be
  11084. affected by these differences. For instance, `{"b": 1, "a": 2}` and
  11085. `{"a": 2, "b": 1}` will be treated as equal.
  11086. #### Limits
  11087. [RFC 7159](http://rfc7159.net/rfc7159) specifies:
  11088. > An implementation may set limits on the maximum depth of nesting.
  11089. In this class, the object's limit of nesting is not explicitly constrained.
  11090. However, a maximum depth of nesting may be introduced by the compiler or
  11091. runtime environment. A theoretical limit can be queried by calling the
  11092. @ref max_size function of a JSON object.
  11093. #### Storage
  11094. Objects are stored as pointers in a @ref basic_json type. That is, for any
  11095. access to object values, a pointer of type `object_t*` must be
  11096. dereferenced.
  11097. @sa @ref array_t -- type for an array value
  11098. @since version 1.0.0
  11099. @note The order name/value pairs are added to the object is *not*
  11100. preserved by the library. Therefore, iterating an object may return
  11101. name/value pairs in a different order than they were originally stored. In
  11102. fact, keys will be traversed in alphabetical order as `std::map` with
  11103. `std::less` is used by default. Please note this behavior conforms to [RFC
  11104. 7159](http://rfc7159.net/rfc7159), because any order implements the
  11105. specified "unordered" nature of JSON objects.
  11106. */
  11107. using object_t = ObjectType<StringType,
  11108. basic_json,
  11109. object_comparator_t,
  11110. AllocatorType<std::pair<const StringType,
  11111. basic_json>>>;
  11112. /*!
  11113. @brief a type for an array
  11114. [RFC 7159](http://rfc7159.net/rfc7159) describes JSON arrays as follows:
  11115. > An array is an ordered sequence of zero or more values.
  11116. To store objects in C++, a type is defined by the template parameters
  11117. explained below.
  11118. @tparam ArrayType container type to store arrays (e.g., `std::vector` or
  11119. `std::list`)
  11120. @tparam AllocatorType allocator to use for arrays (e.g., `std::allocator`)
  11121. #### Default type
  11122. With the default values for @a ArrayType (`std::vector`) and @a
  11123. AllocatorType (`std::allocator`), the default value for @a array_t is:
  11124. @code {.cpp}
  11125. std::vector<
  11126. basic_json, // value_type
  11127. std::allocator<basic_json> // allocator_type
  11128. >
  11129. @endcode
  11130. #### Limits
  11131. [RFC 7159](http://rfc7159.net/rfc7159) specifies:
  11132. > An implementation may set limits on the maximum depth of nesting.
  11133. In this class, the array's limit of nesting is not explicitly constrained.
  11134. However, a maximum depth of nesting may be introduced by the compiler or
  11135. runtime environment. A theoretical limit can be queried by calling the
  11136. @ref max_size function of a JSON array.
  11137. #### Storage
  11138. Arrays are stored as pointers in a @ref basic_json type. That is, for any
  11139. access to array values, a pointer of type `array_t*` must be dereferenced.
  11140. @sa @ref object_t -- type for an object value
  11141. @since version 1.0.0
  11142. */
  11143. using array_t = ArrayType<basic_json, AllocatorType<basic_json>>;
  11144. /*!
  11145. @brief a type for a string
  11146. [RFC 7159](http://rfc7159.net/rfc7159) describes JSON strings as follows:
  11147. > A string is a sequence of zero or more Unicode characters.
  11148. To store objects in C++, a type is defined by the template parameter
  11149. described below. Unicode values are split by the JSON class into
  11150. byte-sized characters during deserialization.
  11151. @tparam StringType the container to store strings (e.g., `std::string`).
  11152. Note this container is used for keys/names in objects, see @ref object_t.
  11153. #### Default type
  11154. With the default values for @a StringType (`std::string`), the default
  11155. value for @a string_t is:
  11156. @code {.cpp}
  11157. std::string
  11158. @endcode
  11159. #### Encoding
  11160. Strings are stored in UTF-8 encoding. Therefore, functions like
  11161. `std::string::size()` or `std::string::length()` return the number of
  11162. bytes in the string rather than the number of characters or glyphs.
  11163. #### String comparison
  11164. [RFC 7159](http://rfc7159.net/rfc7159) states:
  11165. > Software implementations are typically required to test names of object
  11166. > members for equality. Implementations that transform the textual
  11167. > representation into sequences of Unicode code units and then perform the
  11168. > comparison numerically, code unit by code unit, are interoperable in the
  11169. > sense that implementations will agree in all cases on equality or
  11170. > inequality of two strings. For example, implementations that compare
  11171. > strings with escaped characters unconverted may incorrectly find that
  11172. > `"a\\b"` and `"a\u005Cb"` are not equal.
  11173. This implementation is interoperable as it does compare strings code unit
  11174. by code unit.
  11175. #### Storage
  11176. String values are stored as pointers in a @ref basic_json type. That is,
  11177. for any access to string values, a pointer of type `string_t*` must be
  11178. dereferenced.
  11179. @since version 1.0.0
  11180. */
  11181. using string_t = StringType;
  11182. /*!
  11183. @brief a type for a boolean
  11184. [RFC 7159](http://rfc7159.net/rfc7159) implicitly describes a boolean as a
  11185. type which differentiates the two literals `true` and `false`.
  11186. To store objects in C++, a type is defined by the template parameter @a
  11187. BooleanType which chooses the type to use.
  11188. #### Default type
  11189. With the default values for @a BooleanType (`bool`), the default value for
  11190. @a boolean_t is:
  11191. @code {.cpp}
  11192. bool
  11193. @endcode
  11194. #### Storage
  11195. Boolean values are stored directly inside a @ref basic_json type.
  11196. @since version 1.0.0
  11197. */
  11198. using boolean_t = BooleanType;
  11199. /*!
  11200. @brief a type for a number (integer)
  11201. [RFC 7159](http://rfc7159.net/rfc7159) describes numbers as follows:
  11202. > The representation of numbers is similar to that used in most
  11203. > programming languages. A number is represented in base 10 using decimal
  11204. > digits. It contains an integer component that may be prefixed with an
  11205. > optional minus sign, which may be followed by a fraction part and/or an
  11206. > exponent part. Leading zeros are not allowed. (...) Numeric values that
  11207. > cannot be represented in the grammar below (such as Infinity and NaN)
  11208. > are not permitted.
  11209. This description includes both integer and floating-point numbers.
  11210. However, C++ allows more precise storage if it is known whether the number
  11211. is a signed integer, an unsigned integer or a floating-point number.
  11212. Therefore, three different types, @ref number_integer_t, @ref
  11213. number_unsigned_t and @ref number_float_t are used.
  11214. To store integer numbers in C++, a type is defined by the template
  11215. parameter @a NumberIntegerType which chooses the type to use.
  11216. #### Default type
  11217. With the default values for @a NumberIntegerType (`int64_t`), the default
  11218. value for @a number_integer_t is:
  11219. @code {.cpp}
  11220. int64_t
  11221. @endcode
  11222. #### Default behavior
  11223. - The restrictions about leading zeros is not enforced in C++. Instead,
  11224. leading zeros in integer literals lead to an interpretation as octal
  11225. number. Internally, the value will be stored as decimal number. For
  11226. instance, the C++ integer literal `010` will be serialized to `8`.
  11227. During deserialization, leading zeros yield an error.
  11228. - Not-a-number (NaN) values will be serialized to `null`.
  11229. #### Limits
  11230. [RFC 7159](http://rfc7159.net/rfc7159) specifies:
  11231. > An implementation may set limits on the range and precision of numbers.
  11232. When the default type is used, the maximal integer number that can be
  11233. stored is `9223372036854775807` (INT64_MAX) and the minimal integer number
  11234. that can be stored is `-9223372036854775808` (INT64_MIN). Integer numbers
  11235. that are out of range will yield over/underflow when used in a
  11236. constructor. During deserialization, too large or small integer numbers
  11237. will be automatically be stored as @ref number_unsigned_t or @ref
  11238. number_float_t.
  11239. [RFC 7159](http://rfc7159.net/rfc7159) further states:
  11240. > Note that when such software is used, numbers that are integers and are
  11241. > in the range \f$[-2^{53}+1, 2^{53}-1]\f$ are interoperable in the sense
  11242. > that implementations will agree exactly on their numeric values.
  11243. As this range is a subrange of the exactly supported range [INT64_MIN,
  11244. INT64_MAX], this class's integer type is interoperable.
  11245. #### Storage
  11246. Integer number values are stored directly inside a @ref basic_json type.
  11247. @sa @ref number_float_t -- type for number values (floating-point)
  11248. @sa @ref number_unsigned_t -- type for number values (unsigned integer)
  11249. @since version 1.0.0
  11250. */
  11251. using number_integer_t = NumberIntegerType;
  11252. /*!
  11253. @brief a type for a number (unsigned)
  11254. [RFC 7159](http://rfc7159.net/rfc7159) describes numbers as follows:
  11255. > The representation of numbers is similar to that used in most
  11256. > programming languages. A number is represented in base 10 using decimal
  11257. > digits. It contains an integer component that may be prefixed with an
  11258. > optional minus sign, which may be followed by a fraction part and/or an
  11259. > exponent part. Leading zeros are not allowed. (...) Numeric values that
  11260. > cannot be represented in the grammar below (such as Infinity and NaN)
  11261. > are not permitted.
  11262. This description includes both integer and floating-point numbers.
  11263. However, C++ allows more precise storage if it is known whether the number
  11264. is a signed integer, an unsigned integer or a floating-point number.
  11265. Therefore, three different types, @ref number_integer_t, @ref
  11266. number_unsigned_t and @ref number_float_t are used.
  11267. To store unsigned integer numbers in C++, a type is defined by the
  11268. template parameter @a NumberUnsignedType which chooses the type to use.
  11269. #### Default type
  11270. With the default values for @a NumberUnsignedType (`uint64_t`), the
  11271. default value for @a number_unsigned_t is:
  11272. @code {.cpp}
  11273. uint64_t
  11274. @endcode
  11275. #### Default behavior
  11276. - The restrictions about leading zeros is not enforced in C++. Instead,
  11277. leading zeros in integer literals lead to an interpretation as octal
  11278. number. Internally, the value will be stored as decimal number. For
  11279. instance, the C++ integer literal `010` will be serialized to `8`.
  11280. During deserialization, leading zeros yield an error.
  11281. - Not-a-number (NaN) values will be serialized to `null`.
  11282. #### Limits
  11283. [RFC 7159](http://rfc7159.net/rfc7159) specifies:
  11284. > An implementation may set limits on the range and precision of numbers.
  11285. When the default type is used, the maximal integer number that can be
  11286. stored is `18446744073709551615` (UINT64_MAX) and the minimal integer
  11287. number that can be stored is `0`. Integer numbers that are out of range
  11288. will yield over/underflow when used in a constructor. During
  11289. deserialization, too large or small integer numbers will be automatically
  11290. be stored as @ref number_integer_t or @ref number_float_t.
  11291. [RFC 7159](http://rfc7159.net/rfc7159) further states:
  11292. > Note that when such software is used, numbers that are integers and are
  11293. > in the range \f$[-2^{53}+1, 2^{53}-1]\f$ are interoperable in the sense
  11294. > that implementations will agree exactly on their numeric values.
  11295. As this range is a subrange (when considered in conjunction with the
  11296. number_integer_t type) of the exactly supported range [0, UINT64_MAX],
  11297. this class's integer type is interoperable.
  11298. #### Storage
  11299. Integer number values are stored directly inside a @ref basic_json type.
  11300. @sa @ref number_float_t -- type for number values (floating-point)
  11301. @sa @ref number_integer_t -- type for number values (integer)
  11302. @since version 2.0.0
  11303. */
  11304. using number_unsigned_t = NumberUnsignedType;
  11305. /*!
  11306. @brief a type for a number (floating-point)
  11307. [RFC 7159](http://rfc7159.net/rfc7159) describes numbers as follows:
  11308. > The representation of numbers is similar to that used in most
  11309. > programming languages. A number is represented in base 10 using decimal
  11310. > digits. It contains an integer component that may be prefixed with an
  11311. > optional minus sign, which may be followed by a fraction part and/or an
  11312. > exponent part. Leading zeros are not allowed. (...) Numeric values that
  11313. > cannot be represented in the grammar below (such as Infinity and NaN)
  11314. > are not permitted.
  11315. This description includes both integer and floating-point numbers.
  11316. However, C++ allows more precise storage if it is known whether the number
  11317. is a signed integer, an unsigned integer or a floating-point number.
  11318. Therefore, three different types, @ref number_integer_t, @ref
  11319. number_unsigned_t and @ref number_float_t are used.
  11320. To store floating-point numbers in C++, a type is defined by the template
  11321. parameter @a NumberFloatType which chooses the type to use.
  11322. #### Default type
  11323. With the default values for @a NumberFloatType (`double`), the default
  11324. value for @a number_float_t is:
  11325. @code {.cpp}
  11326. double
  11327. @endcode
  11328. #### Default behavior
  11329. - The restrictions about leading zeros is not enforced in C++. Instead,
  11330. leading zeros in floating-point literals will be ignored. Internally,
  11331. the value will be stored as decimal number. For instance, the C++
  11332. floating-point literal `01.2` will be serialized to `1.2`. During
  11333. deserialization, leading zeros yield an error.
  11334. - Not-a-number (NaN) values will be serialized to `null`.
  11335. #### Limits
  11336. [RFC 7159](http://rfc7159.net/rfc7159) states:
  11337. > This specification allows implementations to set limits on the range and
  11338. > precision of numbers accepted. Since software that implements IEEE
  11339. > 754-2008 binary64 (double precision) numbers is generally available and
  11340. > widely used, good interoperability can be achieved by implementations
  11341. > that expect no more precision or range than these provide, in the sense
  11342. > that implementations will approximate JSON numbers within the expected
  11343. > precision.
  11344. This implementation does exactly follow this approach, as it uses double
  11345. precision floating-point numbers. Note values smaller than
  11346. `-1.79769313486232e+308` and values greater than `1.79769313486232e+308`
  11347. will be stored as NaN internally and be serialized to `null`.
  11348. #### Storage
  11349. Floating-point number values are stored directly inside a @ref basic_json
  11350. type.
  11351. @sa @ref number_integer_t -- type for number values (integer)
  11352. @sa @ref number_unsigned_t -- type for number values (unsigned integer)
  11353. @since version 1.0.0
  11354. */
  11355. using number_float_t = NumberFloatType;
  11356. /// @}
  11357. private:
  11358. /// helper for exception-safe object creation
  11359. template<typename T, typename... Args>
  11360. static T* create(Args&& ... args)
  11361. {
  11362. AllocatorType<T> alloc;
  11363. using AllocatorTraits = std::allocator_traits<AllocatorType<T>>;
  11364. auto deleter = [&](T * object)
  11365. {
  11366. AllocatorTraits::deallocate(alloc, object, 1);
  11367. };
  11368. std::unique_ptr<T, decltype(deleter)> object(AllocatorTraits::allocate(alloc, 1), deleter);
  11369. AllocatorTraits::construct(alloc, object.get(), std::forward<Args>(args)...);
  11370. assert(object != nullptr);
  11371. return object.release();
  11372. }
  11373. ////////////////////////
  11374. // JSON value storage //
  11375. ////////////////////////
  11376. /*!
  11377. @brief a JSON value
  11378. The actual storage for a JSON value of the @ref basic_json class. This
  11379. union combines the different storage types for the JSON value types
  11380. defined in @ref value_t.
  11381. JSON type | value_t type | used type
  11382. --------- | --------------- | ------------------------
  11383. object | object | pointer to @ref object_t
  11384. array | array | pointer to @ref array_t
  11385. string | string | pointer to @ref string_t
  11386. boolean | boolean | @ref boolean_t
  11387. number | number_integer | @ref number_integer_t
  11388. number | number_unsigned | @ref number_unsigned_t
  11389. number | number_float | @ref number_float_t
  11390. null | null | *no value is stored*
  11391. @note Variable-length types (objects, arrays, and strings) are stored as
  11392. pointers. The size of the union should not exceed 64 bits if the default
  11393. value types are used.
  11394. @since version 1.0.0
  11395. */
  11396. union json_value
  11397. {
  11398. /// object (stored with pointer to save storage)
  11399. object_t* object;
  11400. /// array (stored with pointer to save storage)
  11401. array_t* array;
  11402. /// string (stored with pointer to save storage)
  11403. string_t* string;
  11404. /// boolean
  11405. boolean_t boolean;
  11406. /// number (integer)
  11407. number_integer_t number_integer;
  11408. /// number (unsigned integer)
  11409. number_unsigned_t number_unsigned;
  11410. /// number (floating-point)
  11411. number_float_t number_float;
  11412. /// default constructor (for null values)
  11413. json_value() = default;
  11414. /// constructor for booleans
  11415. json_value(boolean_t v) noexcept : boolean(v) {}
  11416. /// constructor for numbers (integer)
  11417. json_value(number_integer_t v) noexcept : number_integer(v) {}
  11418. /// constructor for numbers (unsigned)
  11419. json_value(number_unsigned_t v) noexcept : number_unsigned(v) {}
  11420. /// constructor for numbers (floating-point)
  11421. json_value(number_float_t v) noexcept : number_float(v) {}
  11422. /// constructor for empty values of a given type
  11423. json_value(value_t t)
  11424. {
  11425. switch (t)
  11426. {
  11427. case value_t::object:
  11428. {
  11429. object = create<object_t>();
  11430. break;
  11431. }
  11432. case value_t::array:
  11433. {
  11434. array = create<array_t>();
  11435. break;
  11436. }
  11437. case value_t::string:
  11438. {
  11439. string = create<string_t>("");
  11440. break;
  11441. }
  11442. case value_t::boolean:
  11443. {
  11444. boolean = boolean_t(false);
  11445. break;
  11446. }
  11447. case value_t::number_integer:
  11448. {
  11449. number_integer = number_integer_t(0);
  11450. break;
  11451. }
  11452. case value_t::number_unsigned:
  11453. {
  11454. number_unsigned = number_unsigned_t(0);
  11455. break;
  11456. }
  11457. case value_t::number_float:
  11458. {
  11459. number_float = number_float_t(0.0);
  11460. break;
  11461. }
  11462. case value_t::null:
  11463. {
  11464. object = nullptr; // silence warning, see #821
  11465. break;
  11466. }
  11467. default:
  11468. {
  11469. object = nullptr; // silence warning, see #821
  11470. if (JSON_UNLIKELY(t == value_t::null))
  11471. {
  11472. JSON_THROW(other_error::create(500, "961c151d2e87f2686a955a9be24d316f1362bf21 3.5.0")); // LCOV_EXCL_LINE
  11473. }
  11474. break;
  11475. }
  11476. }
  11477. }
  11478. /// constructor for strings
  11479. json_value(const string_t& value)
  11480. {
  11481. string = create<string_t>(value);
  11482. }
  11483. /// constructor for rvalue strings
  11484. json_value(string_t&& value)
  11485. {
  11486. string = create<string_t>(std::move(value));
  11487. }
  11488. /// constructor for objects
  11489. json_value(const object_t& value)
  11490. {
  11491. object = create<object_t>(value);
  11492. }
  11493. /// constructor for rvalue objects
  11494. json_value(object_t&& value)
  11495. {
  11496. object = create<object_t>(std::move(value));
  11497. }
  11498. /// constructor for arrays
  11499. json_value(const array_t& value)
  11500. {
  11501. array = create<array_t>(value);
  11502. }
  11503. /// constructor for rvalue arrays
  11504. json_value(array_t&& value)
  11505. {
  11506. array = create<array_t>(std::move(value));
  11507. }
  11508. void destroy(value_t t) noexcept
  11509. {
  11510. switch (t)
  11511. {
  11512. case value_t::object:
  11513. {
  11514. AllocatorType<object_t> alloc;
  11515. std::allocator_traits<decltype(alloc)>::destroy(alloc, object);
  11516. std::allocator_traits<decltype(alloc)>::deallocate(alloc, object, 1);
  11517. break;
  11518. }
  11519. case value_t::array:
  11520. {
  11521. AllocatorType<array_t> alloc;
  11522. std::allocator_traits<decltype(alloc)>::destroy(alloc, array);
  11523. std::allocator_traits<decltype(alloc)>::deallocate(alloc, array, 1);
  11524. break;
  11525. }
  11526. case value_t::string:
  11527. {
  11528. AllocatorType<string_t> alloc;
  11529. std::allocator_traits<decltype(alloc)>::destroy(alloc, string);
  11530. std::allocator_traits<decltype(alloc)>::deallocate(alloc, string, 1);
  11531. break;
  11532. }
  11533. default:
  11534. {
  11535. break;
  11536. }
  11537. }
  11538. }
  11539. };
  11540. /*!
  11541. @brief checks the class invariants
  11542. This function asserts the class invariants. It needs to be called at the
  11543. end of every constructor to make sure that created objects respect the
  11544. invariant. Furthermore, it has to be called each time the type of a JSON
  11545. value is changed, because the invariant expresses a relationship between
  11546. @a m_type and @a m_value.
  11547. */
  11548. void assert_invariant() const noexcept
  11549. {
  11550. assert(m_type != value_t::object or m_value.object != nullptr);
  11551. assert(m_type != value_t::array or m_value.array != nullptr);
  11552. assert(m_type != value_t::string or m_value.string != nullptr);
  11553. }
  11554. public:
  11555. //////////////////////////
  11556. // JSON parser callback //
  11557. //////////////////////////
  11558. /*!
  11559. @brief parser event types
  11560. The parser callback distinguishes the following events:
  11561. - `object_start`: the parser read `{` and started to process a JSON object
  11562. - `key`: the parser read a key of a value in an object
  11563. - `object_end`: the parser read `}` and finished processing a JSON object
  11564. - `array_start`: the parser read `[` and started to process a JSON array
  11565. - `array_end`: the parser read `]` and finished processing a JSON array
  11566. - `value`: the parser finished reading a JSON value
  11567. @image html callback_events.png "Example when certain parse events are triggered"
  11568. @sa @ref parser_callback_t for more information and examples
  11569. */
  11570. using parse_event_t = typename parser::parse_event_t;
  11571. /*!
  11572. @brief per-element parser callback type
  11573. With a parser callback function, the result of parsing a JSON text can be
  11574. influenced. When passed to @ref parse, it is called on certain events
  11575. (passed as @ref parse_event_t via parameter @a event) with a set recursion
  11576. depth @a depth and context JSON value @a parsed. The return value of the
  11577. callback function is a boolean indicating whether the element that emitted
  11578. the callback shall be kept or not.
  11579. We distinguish six scenarios (determined by the event type) in which the
  11580. callback function can be called. The following table describes the values
  11581. of the parameters @a depth, @a event, and @a parsed.
  11582. parameter @a event | description | parameter @a depth | parameter @a parsed
  11583. ------------------ | ----------- | ------------------ | -------------------
  11584. 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
  11585. 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
  11586. 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
  11587. 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
  11588. 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
  11589. parse_event_t::value | the parser finished reading a JSON value | depth of the value | the parsed JSON value
  11590. @image html callback_events.png "Example when certain parse events are triggered"
  11591. Discarding a value (i.e., returning `false`) has different effects
  11592. depending on the context in which function was called:
  11593. - Discarded values in structured types are skipped. That is, the parser
  11594. will behave as if the discarded value was never read.
  11595. - In case a value outside a structured type is skipped, it is replaced
  11596. with `null`. This case happens if the top-level element is skipped.
  11597. @param[in] depth the depth of the recursion during parsing
  11598. @param[in] event an event of type parse_event_t indicating the context in
  11599. the callback function has been called
  11600. @param[in,out] parsed the current intermediate parse result; note that
  11601. writing to this value has no effect for parse_event_t::key events
  11602. @return Whether the JSON value which called the function during parsing
  11603. should be kept (`true`) or not (`false`). In the latter case, it is either
  11604. skipped completely or replaced by an empty discarded object.
  11605. @sa @ref parse for examples
  11606. @since version 1.0.0
  11607. */
  11608. using parser_callback_t = typename parser::parser_callback_t;
  11609. //////////////////
  11610. // constructors //
  11611. //////////////////
  11612. /// @name constructors and destructors
  11613. /// Constructors of class @ref basic_json, copy/move constructor, copy
  11614. /// assignment, static functions creating objects, and the destructor.
  11615. /// @{
  11616. /*!
  11617. @brief create an empty value with a given type
  11618. Create an empty JSON value with a given type. The value will be default
  11619. initialized with an empty value which depends on the type:
  11620. Value type | initial value
  11621. ----------- | -------------
  11622. null | `null`
  11623. boolean | `false`
  11624. string | `""`
  11625. number | `0`
  11626. object | `{}`
  11627. array | `[]`
  11628. @param[in] v the type of the value to create
  11629. @complexity Constant.
  11630. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  11631. changes to any JSON value.
  11632. @liveexample{The following code shows the constructor for different @ref
  11633. value_t values,basic_json__value_t}
  11634. @sa @ref clear() -- restores the postcondition of this constructor
  11635. @since version 1.0.0
  11636. */
  11637. basic_json(const value_t v)
  11638. : m_type(v), m_value(v)
  11639. {
  11640. assert_invariant();
  11641. }
  11642. /*!
  11643. @brief create a null object
  11644. Create a `null` JSON value. It either takes a null pointer as parameter
  11645. (explicitly creating `null`) or no parameter (implicitly creating `null`).
  11646. The passed null pointer itself is not read -- it is only used to choose
  11647. the right constructor.
  11648. @complexity Constant.
  11649. @exceptionsafety No-throw guarantee: this constructor never throws
  11650. exceptions.
  11651. @liveexample{The following code shows the constructor with and without a
  11652. null pointer parameter.,basic_json__nullptr_t}
  11653. @since version 1.0.0
  11654. */
  11655. basic_json(std::nullptr_t = nullptr) noexcept
  11656. : basic_json(value_t::null)
  11657. {
  11658. assert_invariant();
  11659. }
  11660. /*!
  11661. @brief create a JSON value
  11662. This is a "catch all" constructor for all compatible JSON types; that is,
  11663. types for which a `to_json()` method exists. The constructor forwards the
  11664. parameter @a val to that method (to `json_serializer<U>::to_json` method
  11665. with `U = uncvref_t<CompatibleType>`, to be exact).
  11666. Template type @a CompatibleType includes, but is not limited to, the
  11667. following types:
  11668. - **arrays**: @ref array_t and all kinds of compatible containers such as
  11669. `std::vector`, `std::deque`, `std::list`, `std::forward_list`,
  11670. `std::array`, `std::valarray`, `std::set`, `std::unordered_set`,
  11671. `std::multiset`, and `std::unordered_multiset` with a `value_type` from
  11672. which a @ref basic_json value can be constructed.
  11673. - **objects**: @ref object_t and all kinds of compatible associative
  11674. containers such as `std::map`, `std::unordered_map`, `std::multimap`,
  11675. and `std::unordered_multimap` with a `key_type` compatible to
  11676. @ref string_t and a `value_type` from which a @ref basic_json value can
  11677. be constructed.
  11678. - **strings**: @ref string_t, string literals, and all compatible string
  11679. containers can be used.
  11680. - **numbers**: @ref number_integer_t, @ref number_unsigned_t,
  11681. @ref number_float_t, and all convertible number types such as `int`,
  11682. `size_t`, `int64_t`, `float` or `double` can be used.
  11683. - **boolean**: @ref boolean_t / `bool` can be used.
  11684. See the examples below.
  11685. @tparam CompatibleType a type such that:
  11686. - @a CompatibleType is not derived from `std::istream`,
  11687. - @a CompatibleType is not @ref basic_json (to avoid hijacking copy/move
  11688. constructors),
  11689. - @a CompatibleType is not a different @ref basic_json type (i.e. with different template arguments)
  11690. - @a CompatibleType is not a @ref basic_json nested type (e.g.,
  11691. @ref json_pointer, @ref iterator, etc ...)
  11692. - @ref @ref json_serializer<U> has a
  11693. `to_json(basic_json_t&, CompatibleType&&)` method
  11694. @tparam U = `uncvref_t<CompatibleType>`
  11695. @param[in] val the value to be forwarded to the respective constructor
  11696. @complexity Usually linear in the size of the passed @a val, also
  11697. depending on the implementation of the called `to_json()`
  11698. method.
  11699. @exceptionsafety Depends on the called constructor. For types directly
  11700. supported by the library (i.e., all types for which no `to_json()` function
  11701. was provided), strong guarantee holds: if an exception is thrown, there are
  11702. no changes to any JSON value.
  11703. @liveexample{The following code shows the constructor with several
  11704. compatible types.,basic_json__CompatibleType}
  11705. @since version 2.1.0
  11706. */
  11707. template <typename CompatibleType,
  11708. typename U = detail::uncvref_t<CompatibleType>,
  11709. detail::enable_if_t<
  11710. not detail::is_basic_json<U>::value and detail::is_compatible_type<basic_json_t, U>::value, int> = 0>
  11711. basic_json(CompatibleType && val) noexcept(noexcept(
  11712. JSONSerializer<U>::to_json(std::declval<basic_json_t&>(),
  11713. std::forward<CompatibleType>(val))))
  11714. {
  11715. JSONSerializer<U>::to_json(*this, std::forward<CompatibleType>(val));
  11716. assert_invariant();
  11717. }
  11718. /*!
  11719. @brief create a JSON value from an existing one
  11720. This is a constructor for existing @ref basic_json types.
  11721. It does not hijack copy/move constructors, since the parameter has different
  11722. template arguments than the current ones.
  11723. The constructor tries to convert the internal @ref m_value of the parameter.
  11724. @tparam BasicJsonType a type such that:
  11725. - @a BasicJsonType is a @ref basic_json type.
  11726. - @a BasicJsonType has different template arguments than @ref basic_json_t.
  11727. @param[in] val the @ref basic_json value to be converted.
  11728. @complexity Usually linear in the size of the passed @a val, also
  11729. depending on the implementation of the called `to_json()`
  11730. method.
  11731. @exceptionsafety Depends on the called constructor. For types directly
  11732. supported by the library (i.e., all types for which no `to_json()` function
  11733. was provided), strong guarantee holds: if an exception is thrown, there are
  11734. no changes to any JSON value.
  11735. @since version 3.2.0
  11736. */
  11737. template <typename BasicJsonType,
  11738. detail::enable_if_t<
  11739. detail::is_basic_json<BasicJsonType>::value and not std::is_same<basic_json, BasicJsonType>::value, int> = 0>
  11740. basic_json(const BasicJsonType& val)
  11741. {
  11742. using other_boolean_t = typename BasicJsonType::boolean_t;
  11743. using other_number_float_t = typename BasicJsonType::number_float_t;
  11744. using other_number_integer_t = typename BasicJsonType::number_integer_t;
  11745. using other_number_unsigned_t = typename BasicJsonType::number_unsigned_t;
  11746. using other_string_t = typename BasicJsonType::string_t;
  11747. using other_object_t = typename BasicJsonType::object_t;
  11748. using other_array_t = typename BasicJsonType::array_t;
  11749. switch (val.type())
  11750. {
  11751. case value_t::boolean:
  11752. JSONSerializer<other_boolean_t>::to_json(*this, val.template get<other_boolean_t>());
  11753. break;
  11754. case value_t::number_float:
  11755. JSONSerializer<other_number_float_t>::to_json(*this, val.template get<other_number_float_t>());
  11756. break;
  11757. case value_t::number_integer:
  11758. JSONSerializer<other_number_integer_t>::to_json(*this, val.template get<other_number_integer_t>());
  11759. break;
  11760. case value_t::number_unsigned:
  11761. JSONSerializer<other_number_unsigned_t>::to_json(*this, val.template get<other_number_unsigned_t>());
  11762. break;
  11763. case value_t::string:
  11764. JSONSerializer<other_string_t>::to_json(*this, val.template get_ref<const other_string_t&>());
  11765. break;
  11766. case value_t::object:
  11767. JSONSerializer<other_object_t>::to_json(*this, val.template get_ref<const other_object_t&>());
  11768. break;
  11769. case value_t::array:
  11770. JSONSerializer<other_array_t>::to_json(*this, val.template get_ref<const other_array_t&>());
  11771. break;
  11772. case value_t::null:
  11773. *this = nullptr;
  11774. break;
  11775. case value_t::discarded:
  11776. m_type = value_t::discarded;
  11777. break;
  11778. }
  11779. assert_invariant();
  11780. }
  11781. /*!
  11782. @brief create a container (array or object) from an initializer list
  11783. Creates a JSON value of type array or object from the passed initializer
  11784. list @a init. In case @a type_deduction is `true` (default), the type of
  11785. the JSON value to be created is deducted from the initializer list @a init
  11786. according to the following rules:
  11787. 1. If the list is empty, an empty JSON object value `{}` is created.
  11788. 2. If the list consists of pairs whose first element is a string, a JSON
  11789. object value is created where the first elements of the pairs are
  11790. treated as keys and the second elements are as values.
  11791. 3. In all other cases, an array is created.
  11792. The rules aim to create the best fit between a C++ initializer list and
  11793. JSON values. The rationale is as follows:
  11794. 1. The empty initializer list is written as `{}` which is exactly an empty
  11795. JSON object.
  11796. 2. C++ has no way of describing mapped types other than to list a list of
  11797. pairs. As JSON requires that keys must be of type string, rule 2 is the
  11798. weakest constraint one can pose on initializer lists to interpret them
  11799. as an object.
  11800. 3. In all other cases, the initializer list could not be interpreted as
  11801. JSON object type, so interpreting it as JSON array type is safe.
  11802. With the rules described above, the following JSON values cannot be
  11803. expressed by an initializer list:
  11804. - the empty array (`[]`): use @ref array(initializer_list_t)
  11805. with an empty initializer list in this case
  11806. - arrays whose elements satisfy rule 2: use @ref
  11807. array(initializer_list_t) with the same initializer list
  11808. in this case
  11809. @note When used without parentheses around an empty initializer list, @ref
  11810. basic_json() is called instead of this function, yielding the JSON null
  11811. value.
  11812. @param[in] init initializer list with JSON values
  11813. @param[in] type_deduction internal parameter; when set to `true`, the type
  11814. of the JSON value is deducted from the initializer list @a init; when set
  11815. to `false`, the type provided via @a manual_type is forced. This mode is
  11816. used by the functions @ref array(initializer_list_t) and
  11817. @ref object(initializer_list_t).
  11818. @param[in] manual_type internal parameter; when @a type_deduction is set
  11819. to `false`, the created JSON value will use the provided type (only @ref
  11820. value_t::array and @ref value_t::object are valid); when @a type_deduction
  11821. is set to `true`, this parameter has no effect
  11822. @throw type_error.301 if @a type_deduction is `false`, @a manual_type is
  11823. `value_t::object`, but @a init contains an element which is not a pair
  11824. whose first element is a string. In this case, the constructor could not
  11825. create an object. If @a type_deduction would have be `true`, an array
  11826. would have been created. See @ref object(initializer_list_t)
  11827. for an example.
  11828. @complexity Linear in the size of the initializer list @a init.
  11829. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  11830. changes to any JSON value.
  11831. @liveexample{The example below shows how JSON values are created from
  11832. initializer lists.,basic_json__list_init_t}
  11833. @sa @ref array(initializer_list_t) -- create a JSON array
  11834. value from an initializer list
  11835. @sa @ref object(initializer_list_t) -- create a JSON object
  11836. value from an initializer list
  11837. @since version 1.0.0
  11838. */
  11839. basic_json(initializer_list_t init,
  11840. bool type_deduction = true,
  11841. value_t manual_type = value_t::array)
  11842. {
  11843. // check if each element is an array with two elements whose first
  11844. // element is a string
  11845. bool is_an_object = std::all_of(init.begin(), init.end(),
  11846. [](const detail::json_ref<basic_json>& element_ref)
  11847. {
  11848. return (element_ref->is_array() and element_ref->size() == 2 and (*element_ref)[0].is_string());
  11849. });
  11850. // adjust type if type deduction is not wanted
  11851. if (not type_deduction)
  11852. {
  11853. // if array is wanted, do not create an object though possible
  11854. if (manual_type == value_t::array)
  11855. {
  11856. is_an_object = false;
  11857. }
  11858. // if object is wanted but impossible, throw an exception
  11859. if (JSON_UNLIKELY(manual_type == value_t::object and not is_an_object))
  11860. {
  11861. JSON_THROW(type_error::create(301, "cannot create object from initializer list"));
  11862. }
  11863. }
  11864. if (is_an_object)
  11865. {
  11866. // the initializer list is a list of pairs -> create object
  11867. m_type = value_t::object;
  11868. m_value = value_t::object;
  11869. std::for_each(init.begin(), init.end(), [this](const detail::json_ref<basic_json>& element_ref)
  11870. {
  11871. auto element = element_ref.moved_or_copied();
  11872. m_value.object->emplace(
  11873. std::move(*((*element.m_value.array)[0].m_value.string)),
  11874. std::move((*element.m_value.array)[1]));
  11875. });
  11876. }
  11877. else
  11878. {
  11879. // the initializer list describes an array -> create array
  11880. m_type = value_t::array;
  11881. m_value.array = create<array_t>(init.begin(), init.end());
  11882. }
  11883. assert_invariant();
  11884. }
  11885. /*!
  11886. @brief explicitly create an array from an initializer list
  11887. Creates a JSON array value from a given initializer list. That is, given a
  11888. list of values `a, b, c`, creates the JSON value `[a, b, c]`. If the
  11889. initializer list is empty, the empty array `[]` is created.
  11890. @note This function is only needed to express two edge cases that cannot
  11891. be realized with the initializer list constructor (@ref
  11892. basic_json(initializer_list_t, bool, value_t)). These cases
  11893. are:
  11894. 1. creating an array whose elements are all pairs whose first element is a
  11895. string -- in this case, the initializer list constructor would create an
  11896. object, taking the first elements as keys
  11897. 2. creating an empty array -- passing the empty initializer list to the
  11898. initializer list constructor yields an empty object
  11899. @param[in] init initializer list with JSON values to create an array from
  11900. (optional)
  11901. @return JSON array value
  11902. @complexity Linear in the size of @a init.
  11903. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  11904. changes to any JSON value.
  11905. @liveexample{The following code shows an example for the `array`
  11906. function.,array}
  11907. @sa @ref basic_json(initializer_list_t, bool, value_t) --
  11908. create a JSON value from an initializer list
  11909. @sa @ref object(initializer_list_t) -- create a JSON object
  11910. value from an initializer list
  11911. @since version 1.0.0
  11912. */
  11913. static basic_json array(initializer_list_t init = {})
  11914. {
  11915. return basic_json(init, false, value_t::array);
  11916. }
  11917. /*!
  11918. @brief explicitly create an object from an initializer list
  11919. Creates a JSON object value from a given initializer list. The initializer
  11920. lists elements must be pairs, and their first elements must be strings. If
  11921. the initializer list is empty, the empty object `{}` is created.
  11922. @note This function is only added for symmetry reasons. In contrast to the
  11923. related function @ref array(initializer_list_t), there are
  11924. no cases which can only be expressed by this function. That is, any
  11925. initializer list @a init can also be passed to the initializer list
  11926. constructor @ref basic_json(initializer_list_t, bool, value_t).
  11927. @param[in] init initializer list to create an object from (optional)
  11928. @return JSON object value
  11929. @throw type_error.301 if @a init is not a list of pairs whose first
  11930. elements are strings. In this case, no object can be created. When such a
  11931. value is passed to @ref basic_json(initializer_list_t, bool, value_t),
  11932. an array would have been created from the passed initializer list @a init.
  11933. See example below.
  11934. @complexity Linear in the size of @a init.
  11935. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  11936. changes to any JSON value.
  11937. @liveexample{The following code shows an example for the `object`
  11938. function.,object}
  11939. @sa @ref basic_json(initializer_list_t, bool, value_t) --
  11940. create a JSON value from an initializer list
  11941. @sa @ref array(initializer_list_t) -- create a JSON array
  11942. value from an initializer list
  11943. @since version 1.0.0
  11944. */
  11945. static basic_json object(initializer_list_t init = {})
  11946. {
  11947. return basic_json(init, false, value_t::object);
  11948. }
  11949. /*!
  11950. @brief construct an array with count copies of given value
  11951. Constructs a JSON array value by creating @a cnt copies of a passed value.
  11952. In case @a cnt is `0`, an empty array is created.
  11953. @param[in] cnt the number of JSON copies of @a val to create
  11954. @param[in] val the JSON value to copy
  11955. @post `std::distance(begin(),end()) == cnt` holds.
  11956. @complexity Linear in @a cnt.
  11957. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  11958. changes to any JSON value.
  11959. @liveexample{The following code shows examples for the @ref
  11960. basic_json(size_type\, const basic_json&)
  11961. constructor.,basic_json__size_type_basic_json}
  11962. @since version 1.0.0
  11963. */
  11964. basic_json(size_type cnt, const basic_json& val)
  11965. : m_type(value_t::array)
  11966. {
  11967. m_value.array = create<array_t>(cnt, val);
  11968. assert_invariant();
  11969. }
  11970. /*!
  11971. @brief construct a JSON container given an iterator range
  11972. Constructs the JSON value with the contents of the range `[first, last)`.
  11973. The semantics depends on the different types a JSON value can have:
  11974. - In case of a null type, invalid_iterator.206 is thrown.
  11975. - In case of other primitive types (number, boolean, or string), @a first
  11976. must be `begin()` and @a last must be `end()`. In this case, the value is
  11977. copied. Otherwise, invalid_iterator.204 is thrown.
  11978. - In case of structured types (array, object), the constructor behaves as
  11979. similar versions for `std::vector` or `std::map`; that is, a JSON array
  11980. or object is constructed from the values in the range.
  11981. @tparam InputIT an input iterator type (@ref iterator or @ref
  11982. const_iterator)
  11983. @param[in] first begin of the range to copy from (included)
  11984. @param[in] last end of the range to copy from (excluded)
  11985. @pre Iterators @a first and @a last must be initialized. **This
  11986. precondition is enforced with an assertion (see warning).** If
  11987. assertions are switched off, a violation of this precondition yields
  11988. undefined behavior.
  11989. @pre Range `[first, last)` is valid. Usually, this precondition cannot be
  11990. checked efficiently. Only certain edge cases are detected; see the
  11991. description of the exceptions below. A violation of this precondition
  11992. yields undefined behavior.
  11993. @warning A precondition is enforced with a runtime assertion that will
  11994. result in calling `std::abort` if this precondition is not met.
  11995. Assertions can be disabled by defining `NDEBUG` at compile time.
  11996. See https://en.cppreference.com/w/cpp/error/assert for more
  11997. information.
  11998. @throw invalid_iterator.201 if iterators @a first and @a last are not
  11999. compatible (i.e., do not belong to the same JSON value). In this case,
  12000. the range `[first, last)` is undefined.
  12001. @throw invalid_iterator.204 if iterators @a first and @a last belong to a
  12002. primitive type (number, boolean, or string), but @a first does not point
  12003. to the first element any more. In this case, the range `[first, last)` is
  12004. undefined. See example code below.
  12005. @throw invalid_iterator.206 if iterators @a first and @a last belong to a
  12006. null value. In this case, the range `[first, last)` is undefined.
  12007. @complexity Linear in distance between @a first and @a last.
  12008. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  12009. changes to any JSON value.
  12010. @liveexample{The example below shows several ways to create JSON values by
  12011. specifying a subrange with iterators.,basic_json__InputIt_InputIt}
  12012. @since version 1.0.0
  12013. */
  12014. template<class InputIT, typename std::enable_if<
  12015. std::is_same<InputIT, typename basic_json_t::iterator>::value or
  12016. std::is_same<InputIT, typename basic_json_t::const_iterator>::value, int>::type = 0>
  12017. basic_json(InputIT first, InputIT last)
  12018. {
  12019. assert(first.m_object != nullptr);
  12020. assert(last.m_object != nullptr);
  12021. // make sure iterator fits the current value
  12022. if (JSON_UNLIKELY(first.m_object != last.m_object))
  12023. {
  12024. JSON_THROW(invalid_iterator::create(201, "iterators are not compatible"));
  12025. }
  12026. // copy type from first iterator
  12027. m_type = first.m_object->m_type;
  12028. // check if iterator range is complete for primitive values
  12029. switch (m_type)
  12030. {
  12031. case value_t::boolean:
  12032. case value_t::number_float:
  12033. case value_t::number_integer:
  12034. case value_t::number_unsigned:
  12035. case value_t::string:
  12036. {
  12037. if (JSON_UNLIKELY(not first.m_it.primitive_iterator.is_begin()
  12038. or not last.m_it.primitive_iterator.is_end()))
  12039. {
  12040. JSON_THROW(invalid_iterator::create(204, "iterators out of range"));
  12041. }
  12042. break;
  12043. }
  12044. default:
  12045. break;
  12046. }
  12047. switch (m_type)
  12048. {
  12049. case value_t::number_integer:
  12050. {
  12051. m_value.number_integer = first.m_object->m_value.number_integer;
  12052. break;
  12053. }
  12054. case value_t::number_unsigned:
  12055. {
  12056. m_value.number_unsigned = first.m_object->m_value.number_unsigned;
  12057. break;
  12058. }
  12059. case value_t::number_float:
  12060. {
  12061. m_value.number_float = first.m_object->m_value.number_float;
  12062. break;
  12063. }
  12064. case value_t::boolean:
  12065. {
  12066. m_value.boolean = first.m_object->m_value.boolean;
  12067. break;
  12068. }
  12069. case value_t::string:
  12070. {
  12071. m_value = *first.m_object->m_value.string;
  12072. break;
  12073. }
  12074. case value_t::object:
  12075. {
  12076. m_value.object = create<object_t>(first.m_it.object_iterator,
  12077. last.m_it.object_iterator);
  12078. break;
  12079. }
  12080. case value_t::array:
  12081. {
  12082. m_value.array = create<array_t>(first.m_it.array_iterator,
  12083. last.m_it.array_iterator);
  12084. break;
  12085. }
  12086. default:
  12087. JSON_THROW(invalid_iterator::create(206, "cannot construct with iterators from " +
  12088. std::string(first.m_object->type_name())));
  12089. }
  12090. assert_invariant();
  12091. }
  12092. ///////////////////////////////////////
  12093. // other constructors and destructor //
  12094. ///////////////////////////////////////
  12095. /// @private
  12096. basic_json(const detail::json_ref<basic_json>& ref)
  12097. : basic_json(ref.moved_or_copied())
  12098. {}
  12099. /*!
  12100. @brief copy constructor
  12101. Creates a copy of a given JSON value.
  12102. @param[in] other the JSON value to copy
  12103. @post `*this == other`
  12104. @complexity Linear in the size of @a other.
  12105. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  12106. changes to any JSON value.
  12107. @requirement This function helps `basic_json` satisfying the
  12108. [Container](https://en.cppreference.com/w/cpp/named_req/Container)
  12109. requirements:
  12110. - The complexity is linear.
  12111. - As postcondition, it holds: `other == basic_json(other)`.
  12112. @liveexample{The following code shows an example for the copy
  12113. constructor.,basic_json__basic_json}
  12114. @since version 1.0.0
  12115. */
  12116. basic_json(const basic_json& other)
  12117. : m_type(other.m_type)
  12118. {
  12119. // check of passed value is valid
  12120. other.assert_invariant();
  12121. switch (m_type)
  12122. {
  12123. case value_t::object:
  12124. {
  12125. m_value = *other.m_value.object;
  12126. break;
  12127. }
  12128. case value_t::array:
  12129. {
  12130. m_value = *other.m_value.array;
  12131. break;
  12132. }
  12133. case value_t::string:
  12134. {
  12135. m_value = *other.m_value.string;
  12136. break;
  12137. }
  12138. case value_t::boolean:
  12139. {
  12140. m_value = other.m_value.boolean;
  12141. break;
  12142. }
  12143. case value_t::number_integer:
  12144. {
  12145. m_value = other.m_value.number_integer;
  12146. break;
  12147. }
  12148. case value_t::number_unsigned:
  12149. {
  12150. m_value = other.m_value.number_unsigned;
  12151. break;
  12152. }
  12153. case value_t::number_float:
  12154. {
  12155. m_value = other.m_value.number_float;
  12156. break;
  12157. }
  12158. default:
  12159. break;
  12160. }
  12161. assert_invariant();
  12162. }
  12163. /*!
  12164. @brief move constructor
  12165. Move constructor. Constructs a JSON value with the contents of the given
  12166. value @a other using move semantics. It "steals" the resources from @a
  12167. other and leaves it as JSON null value.
  12168. @param[in,out] other value to move to this object
  12169. @post `*this` has the same value as @a other before the call.
  12170. @post @a other is a JSON null value.
  12171. @complexity Constant.
  12172. @exceptionsafety No-throw guarantee: this constructor never throws
  12173. exceptions.
  12174. @requirement This function helps `basic_json` satisfying the
  12175. [MoveConstructible](https://en.cppreference.com/w/cpp/named_req/MoveConstructible)
  12176. requirements.
  12177. @liveexample{The code below shows the move constructor explicitly called
  12178. via std::move.,basic_json__moveconstructor}
  12179. @since version 1.0.0
  12180. */
  12181. basic_json(basic_json&& other) noexcept
  12182. : m_type(std::move(other.m_type)),
  12183. m_value(std::move(other.m_value))
  12184. {
  12185. // check that passed value is valid
  12186. other.assert_invariant();
  12187. // invalidate payload
  12188. other.m_type = value_t::null;
  12189. other.m_value = {};
  12190. assert_invariant();
  12191. }
  12192. /*!
  12193. @brief copy assignment
  12194. Copy assignment operator. Copies a JSON value via the "copy and swap"
  12195. strategy: It is expressed in terms of the copy constructor, destructor,
  12196. and the `swap()` member function.
  12197. @param[in] other value to copy from
  12198. @complexity Linear.
  12199. @requirement This function helps `basic_json` satisfying the
  12200. [Container](https://en.cppreference.com/w/cpp/named_req/Container)
  12201. requirements:
  12202. - The complexity is linear.
  12203. @liveexample{The code below shows and example for the copy assignment. It
  12204. creates a copy of value `a` which is then swapped with `b`. Finally\, the
  12205. copy of `a` (which is the null value after the swap) is
  12206. destroyed.,basic_json__copyassignment}
  12207. @since version 1.0.0
  12208. */
  12209. basic_json& operator=(basic_json other) noexcept (
  12210. std::is_nothrow_move_constructible<value_t>::value and
  12211. std::is_nothrow_move_assignable<value_t>::value and
  12212. std::is_nothrow_move_constructible<json_value>::value and
  12213. std::is_nothrow_move_assignable<json_value>::value
  12214. )
  12215. {
  12216. // check that passed value is valid
  12217. other.assert_invariant();
  12218. using std::swap;
  12219. swap(m_type, other.m_type);
  12220. swap(m_value, other.m_value);
  12221. assert_invariant();
  12222. return *this;
  12223. }
  12224. /*!
  12225. @brief destructor
  12226. Destroys the JSON value and frees all allocated memory.
  12227. @complexity Linear.
  12228. @requirement This function helps `basic_json` satisfying the
  12229. [Container](https://en.cppreference.com/w/cpp/named_req/Container)
  12230. requirements:
  12231. - The complexity is linear.
  12232. - All stored elements are destroyed and all memory is freed.
  12233. @since version 1.0.0
  12234. */
  12235. ~basic_json() noexcept
  12236. {
  12237. assert_invariant();
  12238. m_value.destroy(m_type);
  12239. }
  12240. /// @}
  12241. public:
  12242. ///////////////////////
  12243. // object inspection //
  12244. ///////////////////////
  12245. /// @name object inspection
  12246. /// Functions to inspect the type of a JSON value.
  12247. /// @{
  12248. /*!
  12249. @brief serialization
  12250. Serialization function for JSON values. The function tries to mimic
  12251. Python's `json.dumps()` function, and currently supports its @a indent
  12252. and @a ensure_ascii parameters.
  12253. @param[in] indent If indent is nonnegative, then array elements and object
  12254. members will be pretty-printed with that indent level. An indent level of
  12255. `0` will only insert newlines. `-1` (the default) selects the most compact
  12256. representation.
  12257. @param[in] indent_char The character to use for indentation if @a indent is
  12258. greater than `0`. The default is ` ` (space).
  12259. @param[in] ensure_ascii If @a ensure_ascii is true, all non-ASCII characters
  12260. in the output are escaped with `\uXXXX` sequences, and the result consists
  12261. of ASCII characters only.
  12262. @param[in] error_handler how to react on decoding errors; there are three
  12263. possible values: `strict` (throws and exception in case a decoding error
  12264. occurs; default), `replace` (replace invalid UTF-8 sequences with U+FFFD),
  12265. and `ignore` (ignore invalid UTF-8 sequences during serialization).
  12266. @return string containing the serialization of the JSON value
  12267. @throw type_error.316 if a string stored inside the JSON value is not
  12268. UTF-8 encoded
  12269. @complexity Linear.
  12270. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  12271. changes in the JSON value.
  12272. @liveexample{The following example shows the effect of different @a indent\,
  12273. @a indent_char\, and @a ensure_ascii parameters to the result of the
  12274. serialization.,dump}
  12275. @see https://docs.python.org/2/library/json.html#json.dump
  12276. @since version 1.0.0; indentation character @a indent_char, option
  12277. @a ensure_ascii and exceptions added in version 3.0.0; error
  12278. handlers added in version 3.4.0.
  12279. */
  12280. string_t dump(const int indent = -1,
  12281. const char indent_char = ' ',
  12282. const bool ensure_ascii = false,
  12283. const error_handler_t error_handler = error_handler_t::strict) const
  12284. {
  12285. string_t result;
  12286. serializer s(detail::output_adapter<char, string_t>(result), indent_char, error_handler);
  12287. if (indent >= 0)
  12288. {
  12289. s.dump(*this, true, ensure_ascii, static_cast<unsigned int>(indent));
  12290. }
  12291. else
  12292. {
  12293. s.dump(*this, false, ensure_ascii, 0);
  12294. }
  12295. return result;
  12296. }
  12297. /*!
  12298. @brief return the type of the JSON value (explicit)
  12299. Return the type of the JSON value as a value from the @ref value_t
  12300. enumeration.
  12301. @return the type of the JSON value
  12302. Value type | return value
  12303. ------------------------- | -------------------------
  12304. null | value_t::null
  12305. boolean | value_t::boolean
  12306. string | value_t::string
  12307. number (integer) | value_t::number_integer
  12308. number (unsigned integer) | value_t::number_unsigned
  12309. number (floating-point) | value_t::number_float
  12310. object | value_t::object
  12311. array | value_t::array
  12312. discarded | value_t::discarded
  12313. @complexity Constant.
  12314. @exceptionsafety No-throw guarantee: this member function never throws
  12315. exceptions.
  12316. @liveexample{The following code exemplifies `type()` for all JSON
  12317. types.,type}
  12318. @sa @ref operator value_t() -- return the type of the JSON value (implicit)
  12319. @sa @ref type_name() -- return the type as string
  12320. @since version 1.0.0
  12321. */
  12322. constexpr value_t type() const noexcept
  12323. {
  12324. return m_type;
  12325. }
  12326. /*!
  12327. @brief return whether type is primitive
  12328. This function returns true if and only if the JSON type is primitive
  12329. (string, number, boolean, or null).
  12330. @return `true` if type is primitive (string, number, boolean, or null),
  12331. `false` otherwise.
  12332. @complexity Constant.
  12333. @exceptionsafety No-throw guarantee: this member function never throws
  12334. exceptions.
  12335. @liveexample{The following code exemplifies `is_primitive()` for all JSON
  12336. types.,is_primitive}
  12337. @sa @ref is_structured() -- returns whether JSON value is structured
  12338. @sa @ref is_null() -- returns whether JSON value is `null`
  12339. @sa @ref is_string() -- returns whether JSON value is a string
  12340. @sa @ref is_boolean() -- returns whether JSON value is a boolean
  12341. @sa @ref is_number() -- returns whether JSON value is a number
  12342. @since version 1.0.0
  12343. */
  12344. constexpr bool is_primitive() const noexcept
  12345. {
  12346. return is_null() or is_string() or is_boolean() or is_number();
  12347. }
  12348. /*!
  12349. @brief return whether type is structured
  12350. This function returns true if and only if the JSON type is structured
  12351. (array or object).
  12352. @return `true` if type is structured (array or object), `false` otherwise.
  12353. @complexity Constant.
  12354. @exceptionsafety No-throw guarantee: this member function never throws
  12355. exceptions.
  12356. @liveexample{The following code exemplifies `is_structured()` for all JSON
  12357. types.,is_structured}
  12358. @sa @ref is_primitive() -- returns whether value is primitive
  12359. @sa @ref is_array() -- returns whether value is an array
  12360. @sa @ref is_object() -- returns whether value is an object
  12361. @since version 1.0.0
  12362. */
  12363. constexpr bool is_structured() const noexcept
  12364. {
  12365. return is_array() or is_object();
  12366. }
  12367. /*!
  12368. @brief return whether value is null
  12369. This function returns true if and only if the JSON value is null.
  12370. @return `true` if type is null, `false` otherwise.
  12371. @complexity Constant.
  12372. @exceptionsafety No-throw guarantee: this member function never throws
  12373. exceptions.
  12374. @liveexample{The following code exemplifies `is_null()` for all JSON
  12375. types.,is_null}
  12376. @since version 1.0.0
  12377. */
  12378. constexpr bool is_null() const noexcept
  12379. {
  12380. return (m_type == value_t::null);
  12381. }
  12382. /*!
  12383. @brief return whether value is a boolean
  12384. This function returns true if and only if the JSON value is a boolean.
  12385. @return `true` if type is boolean, `false` otherwise.
  12386. @complexity Constant.
  12387. @exceptionsafety No-throw guarantee: this member function never throws
  12388. exceptions.
  12389. @liveexample{The following code exemplifies `is_boolean()` for all JSON
  12390. types.,is_boolean}
  12391. @since version 1.0.0
  12392. */
  12393. constexpr bool is_boolean() const noexcept
  12394. {
  12395. return (m_type == value_t::boolean);
  12396. }
  12397. /*!
  12398. @brief return whether value is a number
  12399. This function returns true if and only if the JSON value is a number. This
  12400. includes both integer (signed and unsigned) and floating-point values.
  12401. @return `true` if type is number (regardless whether integer, unsigned
  12402. integer or floating-type), `false` otherwise.
  12403. @complexity Constant.
  12404. @exceptionsafety No-throw guarantee: this member function never throws
  12405. exceptions.
  12406. @liveexample{The following code exemplifies `is_number()` for all JSON
  12407. types.,is_number}
  12408. @sa @ref is_number_integer() -- check if value is an integer or unsigned
  12409. integer number
  12410. @sa @ref is_number_unsigned() -- check if value is an unsigned integer
  12411. number
  12412. @sa @ref is_number_float() -- check if value is a floating-point number
  12413. @since version 1.0.0
  12414. */
  12415. constexpr bool is_number() const noexcept
  12416. {
  12417. return is_number_integer() or is_number_float();
  12418. }
  12419. /*!
  12420. @brief return whether value is an integer number
  12421. This function returns true if and only if the JSON value is a signed or
  12422. unsigned integer number. This excludes floating-point values.
  12423. @return `true` if type is an integer or unsigned integer number, `false`
  12424. otherwise.
  12425. @complexity Constant.
  12426. @exceptionsafety No-throw guarantee: this member function never throws
  12427. exceptions.
  12428. @liveexample{The following code exemplifies `is_number_integer()` for all
  12429. JSON types.,is_number_integer}
  12430. @sa @ref is_number() -- check if value is a number
  12431. @sa @ref is_number_unsigned() -- check if value is an unsigned integer
  12432. number
  12433. @sa @ref is_number_float() -- check if value is a floating-point number
  12434. @since version 1.0.0
  12435. */
  12436. constexpr bool is_number_integer() const noexcept
  12437. {
  12438. return (m_type == value_t::number_integer or m_type == value_t::number_unsigned);
  12439. }
  12440. /*!
  12441. @brief return whether value is an unsigned integer number
  12442. This function returns true if and only if the JSON value is an unsigned
  12443. integer number. This excludes floating-point and signed integer values.
  12444. @return `true` if type is an unsigned integer number, `false` otherwise.
  12445. @complexity Constant.
  12446. @exceptionsafety No-throw guarantee: this member function never throws
  12447. exceptions.
  12448. @liveexample{The following code exemplifies `is_number_unsigned()` for all
  12449. JSON types.,is_number_unsigned}
  12450. @sa @ref is_number() -- check if value is a number
  12451. @sa @ref is_number_integer() -- check if value is an integer or unsigned
  12452. integer number
  12453. @sa @ref is_number_float() -- check if value is a floating-point number
  12454. @since version 2.0.0
  12455. */
  12456. constexpr bool is_number_unsigned() const noexcept
  12457. {
  12458. return (m_type == value_t::number_unsigned);
  12459. }
  12460. /*!
  12461. @brief return whether value is a floating-point number
  12462. This function returns true if and only if the JSON value is a
  12463. floating-point number. This excludes signed and unsigned integer values.
  12464. @return `true` if type is a floating-point number, `false` otherwise.
  12465. @complexity Constant.
  12466. @exceptionsafety No-throw guarantee: this member function never throws
  12467. exceptions.
  12468. @liveexample{The following code exemplifies `is_number_float()` for all
  12469. JSON types.,is_number_float}
  12470. @sa @ref is_number() -- check if value is number
  12471. @sa @ref is_number_integer() -- check if value is an integer number
  12472. @sa @ref is_number_unsigned() -- check if value is an unsigned integer
  12473. number
  12474. @since version 1.0.0
  12475. */
  12476. constexpr bool is_number_float() const noexcept
  12477. {
  12478. return (m_type == value_t::number_float);
  12479. }
  12480. /*!
  12481. @brief return whether value is an object
  12482. This function returns true if and only if the JSON value is an object.
  12483. @return `true` if type is object, `false` otherwise.
  12484. @complexity Constant.
  12485. @exceptionsafety No-throw guarantee: this member function never throws
  12486. exceptions.
  12487. @liveexample{The following code exemplifies `is_object()` for all JSON
  12488. types.,is_object}
  12489. @since version 1.0.0
  12490. */
  12491. constexpr bool is_object() const noexcept
  12492. {
  12493. return (m_type == value_t::object);
  12494. }
  12495. /*!
  12496. @brief return whether value is an array
  12497. This function returns true if and only if the JSON value is an array.
  12498. @return `true` if type is array, `false` otherwise.
  12499. @complexity Constant.
  12500. @exceptionsafety No-throw guarantee: this member function never throws
  12501. exceptions.
  12502. @liveexample{The following code exemplifies `is_array()` for all JSON
  12503. types.,is_array}
  12504. @since version 1.0.0
  12505. */
  12506. constexpr bool is_array() const noexcept
  12507. {
  12508. return (m_type == value_t::array);
  12509. }
  12510. /*!
  12511. @brief return whether value is a string
  12512. This function returns true if and only if the JSON value is a string.
  12513. @return `true` if type is string, `false` otherwise.
  12514. @complexity Constant.
  12515. @exceptionsafety No-throw guarantee: this member function never throws
  12516. exceptions.
  12517. @liveexample{The following code exemplifies `is_string()` for all JSON
  12518. types.,is_string}
  12519. @since version 1.0.0
  12520. */
  12521. constexpr bool is_string() const noexcept
  12522. {
  12523. return (m_type == value_t::string);
  12524. }
  12525. /*!
  12526. @brief return whether value is discarded
  12527. This function returns true if and only if the JSON value was discarded
  12528. during parsing with a callback function (see @ref parser_callback_t).
  12529. @note This function will always be `false` for JSON values after parsing.
  12530. That is, discarded values can only occur during parsing, but will be
  12531. removed when inside a structured value or replaced by null in other cases.
  12532. @return `true` if type is discarded, `false` otherwise.
  12533. @complexity Constant.
  12534. @exceptionsafety No-throw guarantee: this member function never throws
  12535. exceptions.
  12536. @liveexample{The following code exemplifies `is_discarded()` for all JSON
  12537. types.,is_discarded}
  12538. @since version 1.0.0
  12539. */
  12540. constexpr bool is_discarded() const noexcept
  12541. {
  12542. return (m_type == value_t::discarded);
  12543. }
  12544. /*!
  12545. @brief return the type of the JSON value (implicit)
  12546. Implicitly return the type of the JSON value as a value from the @ref
  12547. value_t enumeration.
  12548. @return the type of the JSON value
  12549. @complexity Constant.
  12550. @exceptionsafety No-throw guarantee: this member function never throws
  12551. exceptions.
  12552. @liveexample{The following code exemplifies the @ref value_t operator for
  12553. all JSON types.,operator__value_t}
  12554. @sa @ref type() -- return the type of the JSON value (explicit)
  12555. @sa @ref type_name() -- return the type as string
  12556. @since version 1.0.0
  12557. */
  12558. constexpr operator value_t() const noexcept
  12559. {
  12560. return m_type;
  12561. }
  12562. /// @}
  12563. private:
  12564. //////////////////
  12565. // value access //
  12566. //////////////////
  12567. /// get a boolean (explicit)
  12568. boolean_t get_impl(boolean_t* /*unused*/) const
  12569. {
  12570. if (JSON_LIKELY(is_boolean()))
  12571. {
  12572. return m_value.boolean;
  12573. }
  12574. JSON_THROW(type_error::create(302, "type must be boolean, but is " + std::string(type_name())));
  12575. }
  12576. /// get a pointer to the value (object)
  12577. object_t* get_impl_ptr(object_t* /*unused*/) noexcept
  12578. {
  12579. return is_object() ? m_value.object : nullptr;
  12580. }
  12581. /// get a pointer to the value (object)
  12582. constexpr const object_t* get_impl_ptr(const object_t* /*unused*/) const noexcept
  12583. {
  12584. return is_object() ? m_value.object : nullptr;
  12585. }
  12586. /// get a pointer to the value (array)
  12587. array_t* get_impl_ptr(array_t* /*unused*/) noexcept
  12588. {
  12589. return is_array() ? m_value.array : nullptr;
  12590. }
  12591. /// get a pointer to the value (array)
  12592. constexpr const array_t* get_impl_ptr(const array_t* /*unused*/) const noexcept
  12593. {
  12594. return is_array() ? m_value.array : nullptr;
  12595. }
  12596. /// get a pointer to the value (string)
  12597. string_t* get_impl_ptr(string_t* /*unused*/) noexcept
  12598. {
  12599. return is_string() ? m_value.string : nullptr;
  12600. }
  12601. /// get a pointer to the value (string)
  12602. constexpr const string_t* get_impl_ptr(const string_t* /*unused*/) const noexcept
  12603. {
  12604. return is_string() ? m_value.string : nullptr;
  12605. }
  12606. /// get a pointer to the value (boolean)
  12607. boolean_t* get_impl_ptr(boolean_t* /*unused*/) noexcept
  12608. {
  12609. return is_boolean() ? &m_value.boolean : nullptr;
  12610. }
  12611. /// get a pointer to the value (boolean)
  12612. constexpr const boolean_t* get_impl_ptr(const boolean_t* /*unused*/) const noexcept
  12613. {
  12614. return is_boolean() ? &m_value.boolean : nullptr;
  12615. }
  12616. /// get a pointer to the value (integer number)
  12617. number_integer_t* get_impl_ptr(number_integer_t* /*unused*/) noexcept
  12618. {
  12619. return is_number_integer() ? &m_value.number_integer : nullptr;
  12620. }
  12621. /// get a pointer to the value (integer number)
  12622. constexpr const number_integer_t* get_impl_ptr(const number_integer_t* /*unused*/) const noexcept
  12623. {
  12624. return is_number_integer() ? &m_value.number_integer : nullptr;
  12625. }
  12626. /// get a pointer to the value (unsigned number)
  12627. number_unsigned_t* get_impl_ptr(number_unsigned_t* /*unused*/) noexcept
  12628. {
  12629. return is_number_unsigned() ? &m_value.number_unsigned : nullptr;
  12630. }
  12631. /// get a pointer to the value (unsigned number)
  12632. constexpr const number_unsigned_t* get_impl_ptr(const number_unsigned_t* /*unused*/) const noexcept
  12633. {
  12634. return is_number_unsigned() ? &m_value.number_unsigned : nullptr;
  12635. }
  12636. /// get a pointer to the value (floating-point number)
  12637. number_float_t* get_impl_ptr(number_float_t* /*unused*/) noexcept
  12638. {
  12639. return is_number_float() ? &m_value.number_float : nullptr;
  12640. }
  12641. /// get a pointer to the value (floating-point number)
  12642. constexpr const number_float_t* get_impl_ptr(const number_float_t* /*unused*/) const noexcept
  12643. {
  12644. return is_number_float() ? &m_value.number_float : nullptr;
  12645. }
  12646. /*!
  12647. @brief helper function to implement get_ref()
  12648. This function helps to implement get_ref() without code duplication for
  12649. const and non-const overloads
  12650. @tparam ThisType will be deduced as `basic_json` or `const basic_json`
  12651. @throw type_error.303 if ReferenceType does not match underlying value
  12652. type of the current JSON
  12653. */
  12654. template<typename ReferenceType, typename ThisType>
  12655. static ReferenceType get_ref_impl(ThisType& obj)
  12656. {
  12657. // delegate the call to get_ptr<>()
  12658. auto ptr = obj.template get_ptr<typename std::add_pointer<ReferenceType>::type>();
  12659. if (JSON_LIKELY(ptr != nullptr))
  12660. {
  12661. return *ptr;
  12662. }
  12663. JSON_THROW(type_error::create(303, "incompatible ReferenceType for get_ref, actual type is " + std::string(obj.type_name())));
  12664. }
  12665. public:
  12666. /// @name value access
  12667. /// Direct access to the stored value of a JSON value.
  12668. /// @{
  12669. /*!
  12670. @brief get special-case overload
  12671. This overloads avoids a lot of template boilerplate, it can be seen as the
  12672. identity method
  12673. @tparam BasicJsonType == @ref basic_json
  12674. @return a copy of *this
  12675. @complexity Constant.
  12676. @since version 2.1.0
  12677. */
  12678. template<typename BasicJsonType, detail::enable_if_t<
  12679. std::is_same<typename std::remove_const<BasicJsonType>::type, basic_json_t>::value,
  12680. int> = 0>
  12681. basic_json get() const
  12682. {
  12683. return *this;
  12684. }
  12685. /*!
  12686. @brief get special-case overload
  12687. This overloads converts the current @ref basic_json in a different
  12688. @ref basic_json type
  12689. @tparam BasicJsonType == @ref basic_json
  12690. @return a copy of *this, converted into @tparam BasicJsonType
  12691. @complexity Depending on the implementation of the called `from_json()`
  12692. method.
  12693. @since version 3.2.0
  12694. */
  12695. template<typename BasicJsonType, detail::enable_if_t<
  12696. not std::is_same<BasicJsonType, basic_json>::value and
  12697. detail::is_basic_json<BasicJsonType>::value, int> = 0>
  12698. BasicJsonType get() const
  12699. {
  12700. return *this;
  12701. }
  12702. /*!
  12703. @brief get a value (explicit)
  12704. Explicit type conversion between the JSON value and a compatible value
  12705. which is [CopyConstructible](https://en.cppreference.com/w/cpp/named_req/CopyConstructible)
  12706. and [DefaultConstructible](https://en.cppreference.com/w/cpp/named_req/DefaultConstructible).
  12707. The value is converted by calling the @ref json_serializer<ValueType>
  12708. `from_json()` method.
  12709. The function is equivalent to executing
  12710. @code {.cpp}
  12711. ValueType ret;
  12712. JSONSerializer<ValueType>::from_json(*this, ret);
  12713. return ret;
  12714. @endcode
  12715. This overloads is chosen if:
  12716. - @a ValueType is not @ref basic_json,
  12717. - @ref json_serializer<ValueType> has a `from_json()` method of the form
  12718. `void from_json(const basic_json&, ValueType&)`, and
  12719. - @ref json_serializer<ValueType> does not have a `from_json()` method of
  12720. the form `ValueType from_json(const basic_json&)`
  12721. @tparam ValueTypeCV the provided value type
  12722. @tparam ValueType the returned value type
  12723. @return copy of the JSON value, converted to @a ValueType
  12724. @throw what @ref json_serializer<ValueType> `from_json()` method throws
  12725. @liveexample{The example below shows several conversions from JSON values
  12726. to other types. There a few things to note: (1) Floating-point numbers can
  12727. be converted to integers\, (2) A JSON array can be converted to a standard
  12728. `std::vector<short>`\, (3) A JSON object can be converted to C++
  12729. associative containers such as `std::unordered_map<std::string\,
  12730. json>`.,get__ValueType_const}
  12731. @since version 2.1.0
  12732. */
  12733. template<typename ValueTypeCV, typename ValueType = detail::uncvref_t<ValueTypeCV>,
  12734. detail::enable_if_t <
  12735. not detail::is_basic_json<ValueType>::value and
  12736. detail::has_from_json<basic_json_t, ValueType>::value and
  12737. not detail::has_non_default_from_json<basic_json_t, ValueType>::value,
  12738. int> = 0>
  12739. ValueType get() const noexcept(noexcept(
  12740. JSONSerializer<ValueType>::from_json(std::declval<const basic_json_t&>(), std::declval<ValueType&>())))
  12741. {
  12742. // we cannot static_assert on ValueTypeCV being non-const, because
  12743. // there is support for get<const basic_json_t>(), which is why we
  12744. // still need the uncvref
  12745. static_assert(not std::is_reference<ValueTypeCV>::value,
  12746. "get() cannot be used with reference types, you might want to use get_ref()");
  12747. static_assert(std::is_default_constructible<ValueType>::value,
  12748. "types must be DefaultConstructible when used with get()");
  12749. ValueType ret;
  12750. JSONSerializer<ValueType>::from_json(*this, ret);
  12751. return ret;
  12752. }
  12753. /*!
  12754. @brief get a value (explicit); special case
  12755. Explicit type conversion between the JSON value and a compatible value
  12756. which is **not** [CopyConstructible](https://en.cppreference.com/w/cpp/named_req/CopyConstructible)
  12757. and **not** [DefaultConstructible](https://en.cppreference.com/w/cpp/named_req/DefaultConstructible).
  12758. The value is converted by calling the @ref json_serializer<ValueType>
  12759. `from_json()` method.
  12760. The function is equivalent to executing
  12761. @code {.cpp}
  12762. return JSONSerializer<ValueTypeCV>::from_json(*this);
  12763. @endcode
  12764. This overloads is chosen if:
  12765. - @a ValueType is not @ref basic_json and
  12766. - @ref json_serializer<ValueType> has a `from_json()` method of the form
  12767. `ValueType from_json(const basic_json&)`
  12768. @note If @ref json_serializer<ValueType> has both overloads of
  12769. `from_json()`, this one is chosen.
  12770. @tparam ValueTypeCV the provided value type
  12771. @tparam ValueType the returned value type
  12772. @return copy of the JSON value, converted to @a ValueType
  12773. @throw what @ref json_serializer<ValueType> `from_json()` method throws
  12774. @since version 2.1.0
  12775. */
  12776. template<typename ValueTypeCV, typename ValueType = detail::uncvref_t<ValueTypeCV>,
  12777. detail::enable_if_t<not std::is_same<basic_json_t, ValueType>::value and
  12778. detail::has_non_default_from_json<basic_json_t, ValueType>::value,
  12779. int> = 0>
  12780. ValueType get() const noexcept(noexcept(
  12781. JSONSerializer<ValueTypeCV>::from_json(std::declval<const basic_json_t&>())))
  12782. {
  12783. static_assert(not std::is_reference<ValueTypeCV>::value,
  12784. "get() cannot be used with reference types, you might want to use get_ref()");
  12785. return JSONSerializer<ValueTypeCV>::from_json(*this);
  12786. }
  12787. /*!
  12788. @brief get a value (explicit)
  12789. Explicit type conversion between the JSON value and a compatible value.
  12790. The value is filled into the input parameter by calling the @ref json_serializer<ValueType>
  12791. `from_json()` method.
  12792. The function is equivalent to executing
  12793. @code {.cpp}
  12794. ValueType v;
  12795. JSONSerializer<ValueType>::from_json(*this, v);
  12796. @endcode
  12797. This overloads is chosen if:
  12798. - @a ValueType is not @ref basic_json,
  12799. - @ref json_serializer<ValueType> has a `from_json()` method of the form
  12800. `void from_json(const basic_json&, ValueType&)`, and
  12801. @tparam ValueType the input parameter type.
  12802. @return the input parameter, allowing chaining calls.
  12803. @throw what @ref json_serializer<ValueType> `from_json()` method throws
  12804. @liveexample{The example below shows several conversions from JSON values
  12805. to other types. There a few things to note: (1) Floating-point numbers can
  12806. be converted to integers\, (2) A JSON array can be converted to a standard
  12807. `std::vector<short>`\, (3) A JSON object can be converted to C++
  12808. associative containers such as `std::unordered_map<std::string\,
  12809. json>`.,get_to}
  12810. @since version 3.3.0
  12811. */
  12812. template<typename ValueType,
  12813. detail::enable_if_t <
  12814. not detail::is_basic_json<ValueType>::value and
  12815. detail::has_from_json<basic_json_t, ValueType>::value,
  12816. int> = 0>
  12817. ValueType & get_to(ValueType& v) const noexcept(noexcept(
  12818. JSONSerializer<ValueType>::from_json(std::declval<const basic_json_t&>(), v)))
  12819. {
  12820. JSONSerializer<ValueType>::from_json(*this, v);
  12821. return v;
  12822. }
  12823. /*!
  12824. @brief get a pointer value (implicit)
  12825. Implicit pointer access to the internally stored JSON value. No copies are
  12826. made.
  12827. @warning Writing data to the pointee of the result yields an undefined
  12828. state.
  12829. @tparam PointerType pointer type; must be a pointer to @ref array_t, @ref
  12830. object_t, @ref string_t, @ref boolean_t, @ref number_integer_t,
  12831. @ref number_unsigned_t, or @ref number_float_t. Enforced by a static
  12832. assertion.
  12833. @return pointer to the internally stored JSON value if the requested
  12834. pointer type @a PointerType fits to the JSON value; `nullptr` otherwise
  12835. @complexity Constant.
  12836. @liveexample{The example below shows how pointers to internal values of a
  12837. JSON value can be requested. Note that no type conversions are made and a
  12838. `nullptr` is returned if the value and the requested pointer type does not
  12839. match.,get_ptr}
  12840. @since version 1.0.0
  12841. */
  12842. template<typename PointerType, typename std::enable_if<
  12843. std::is_pointer<PointerType>::value, int>::type = 0>
  12844. auto get_ptr() noexcept -> decltype(std::declval<basic_json_t&>().get_impl_ptr(std::declval<PointerType>()))
  12845. {
  12846. // delegate the call to get_impl_ptr<>()
  12847. return get_impl_ptr(static_cast<PointerType>(nullptr));
  12848. }
  12849. /*!
  12850. @brief get a pointer value (implicit)
  12851. @copydoc get_ptr()
  12852. */
  12853. template<typename PointerType, typename std::enable_if<
  12854. std::is_pointer<PointerType>::value and
  12855. std::is_const<typename std::remove_pointer<PointerType>::type>::value, int>::type = 0>
  12856. constexpr auto get_ptr() const noexcept -> decltype(std::declval<const basic_json_t&>().get_impl_ptr(std::declval<PointerType>()))
  12857. {
  12858. // delegate the call to get_impl_ptr<>() const
  12859. return get_impl_ptr(static_cast<PointerType>(nullptr));
  12860. }
  12861. /*!
  12862. @brief get a pointer value (explicit)
  12863. Explicit pointer access to the internally stored JSON value. No copies are
  12864. made.
  12865. @warning The pointer becomes invalid if the underlying JSON object
  12866. changes.
  12867. @tparam PointerType pointer type; must be a pointer to @ref array_t, @ref
  12868. object_t, @ref string_t, @ref boolean_t, @ref number_integer_t,
  12869. @ref number_unsigned_t, or @ref number_float_t.
  12870. @return pointer to the internally stored JSON value if the requested
  12871. pointer type @a PointerType fits to the JSON value; `nullptr` otherwise
  12872. @complexity Constant.
  12873. @liveexample{The example below shows how pointers to internal values of a
  12874. JSON value can be requested. Note that no type conversions are made and a
  12875. `nullptr` is returned if the value and the requested pointer type does not
  12876. match.,get__PointerType}
  12877. @sa @ref get_ptr() for explicit pointer-member access
  12878. @since version 1.0.0
  12879. */
  12880. template<typename PointerType, typename std::enable_if<
  12881. std::is_pointer<PointerType>::value, int>::type = 0>
  12882. auto get() noexcept -> decltype(std::declval<basic_json_t&>().template get_ptr<PointerType>())
  12883. {
  12884. // delegate the call to get_ptr
  12885. return get_ptr<PointerType>();
  12886. }
  12887. /*!
  12888. @brief get a pointer value (explicit)
  12889. @copydoc get()
  12890. */
  12891. template<typename PointerType, typename std::enable_if<
  12892. std::is_pointer<PointerType>::value, int>::type = 0>
  12893. constexpr auto get() const noexcept -> decltype(std::declval<const basic_json_t&>().template get_ptr<PointerType>())
  12894. {
  12895. // delegate the call to get_ptr
  12896. return get_ptr<PointerType>();
  12897. }
  12898. /*!
  12899. @brief get a reference value (implicit)
  12900. Implicit reference access to the internally stored JSON value. No copies
  12901. are made.
  12902. @warning Writing data to the referee of the result yields an undefined
  12903. state.
  12904. @tparam ReferenceType reference type; must be a reference to @ref array_t,
  12905. @ref object_t, @ref string_t, @ref boolean_t, @ref number_integer_t, or
  12906. @ref number_float_t. Enforced by static assertion.
  12907. @return reference to the internally stored JSON value if the requested
  12908. reference type @a ReferenceType fits to the JSON value; throws
  12909. type_error.303 otherwise
  12910. @throw type_error.303 in case passed type @a ReferenceType is incompatible
  12911. with the stored JSON value; see example below
  12912. @complexity Constant.
  12913. @liveexample{The example shows several calls to `get_ref()`.,get_ref}
  12914. @since version 1.1.0
  12915. */
  12916. template<typename ReferenceType, typename std::enable_if<
  12917. std::is_reference<ReferenceType>::value, int>::type = 0>
  12918. ReferenceType get_ref()
  12919. {
  12920. // delegate call to get_ref_impl
  12921. return get_ref_impl<ReferenceType>(*this);
  12922. }
  12923. /*!
  12924. @brief get a reference value (implicit)
  12925. @copydoc get_ref()
  12926. */
  12927. template<typename ReferenceType, typename std::enable_if<
  12928. std::is_reference<ReferenceType>::value and
  12929. std::is_const<typename std::remove_reference<ReferenceType>::type>::value, int>::type = 0>
  12930. ReferenceType get_ref() const
  12931. {
  12932. // delegate call to get_ref_impl
  12933. return get_ref_impl<ReferenceType>(*this);
  12934. }
  12935. /*!
  12936. @brief get a value (implicit)
  12937. Implicit type conversion between the JSON value and a compatible value.
  12938. The call is realized by calling @ref get() const.
  12939. @tparam ValueType non-pointer type compatible to the JSON value, for
  12940. instance `int` for JSON integer numbers, `bool` for JSON booleans, or
  12941. `std::vector` types for JSON arrays. The character type of @ref string_t
  12942. as well as an initializer list of this type is excluded to avoid
  12943. ambiguities as these types implicitly convert to `std::string`.
  12944. @return copy of the JSON value, converted to type @a ValueType
  12945. @throw type_error.302 in case passed type @a ValueType is incompatible
  12946. to the JSON value type (e.g., the JSON value is of type boolean, but a
  12947. string is requested); see example below
  12948. @complexity Linear in the size of the JSON value.
  12949. @liveexample{The example below shows several conversions from JSON values
  12950. to other types. There a few things to note: (1) Floating-point numbers can
  12951. be converted to integers\, (2) A JSON array can be converted to a standard
  12952. `std::vector<short>`\, (3) A JSON object can be converted to C++
  12953. associative containers such as `std::unordered_map<std::string\,
  12954. json>`.,operator__ValueType}
  12955. @since version 1.0.0
  12956. */
  12957. template < typename ValueType, typename std::enable_if <
  12958. not std::is_pointer<ValueType>::value and
  12959. not std::is_same<ValueType, detail::json_ref<basic_json>>::value and
  12960. not std::is_same<ValueType, typename string_t::value_type>::value and
  12961. not detail::is_basic_json<ValueType>::value
  12962. #ifndef _MSC_VER // fix for issue #167 operator<< ambiguity under VS2015
  12963. and not std::is_same<ValueType, std::initializer_list<typename string_t::value_type>>::value
  12964. #if defined(JSON_HAS_CPP_17) && defined(_MSC_VER) and _MSC_VER <= 1914
  12965. and not std::is_same<ValueType, typename std::string_view>::value
  12966. #endif
  12967. #endif
  12968. and detail::is_detected<detail::get_template_function, const basic_json_t&, ValueType>::value
  12969. , int >::type = 0 >
  12970. operator ValueType() const
  12971. {
  12972. // delegate the call to get<>() const
  12973. return get<ValueType>();
  12974. }
  12975. /// @}
  12976. ////////////////////
  12977. // element access //
  12978. ////////////////////
  12979. /// @name element access
  12980. /// Access to the JSON value.
  12981. /// @{
  12982. /*!
  12983. @brief access specified array element with bounds checking
  12984. Returns a reference to the element at specified location @a idx, with
  12985. bounds checking.
  12986. @param[in] idx index of the element to access
  12987. @return reference to the element at index @a idx
  12988. @throw type_error.304 if the JSON value is not an array; in this case,
  12989. calling `at` with an index makes no sense. See example below.
  12990. @throw out_of_range.401 if the index @a idx is out of range of the array;
  12991. that is, `idx >= size()`. See example below.
  12992. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  12993. changes in the JSON value.
  12994. @complexity Constant.
  12995. @since version 1.0.0
  12996. @liveexample{The example below shows how array elements can be read and
  12997. written using `at()`. It also demonstrates the different exceptions that
  12998. can be thrown.,at__size_type}
  12999. */
  13000. reference at(size_type idx)
  13001. {
  13002. // at only works for arrays
  13003. if (JSON_LIKELY(is_array()))
  13004. {
  13005. JSON_TRY
  13006. {
  13007. return m_value.array->at(idx);
  13008. }
  13009. JSON_CATCH (std::out_of_range&)
  13010. {
  13011. // create better exception explanation
  13012. JSON_THROW(out_of_range::create(401, "array index " + std::to_string(idx) + " is out of range"));
  13013. }
  13014. }
  13015. else
  13016. {
  13017. JSON_THROW(type_error::create(304, "cannot use at() with " + std::string(type_name())));
  13018. }
  13019. }
  13020. /*!
  13021. @brief access specified array element with bounds checking
  13022. Returns a const reference to the element at specified location @a idx,
  13023. with bounds checking.
  13024. @param[in] idx index of the element to access
  13025. @return const reference to the element at index @a idx
  13026. @throw type_error.304 if the JSON value is not an array; in this case,
  13027. calling `at` with an index makes no sense. See example below.
  13028. @throw out_of_range.401 if the index @a idx is out of range of the array;
  13029. that is, `idx >= size()`. See example below.
  13030. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  13031. changes in the JSON value.
  13032. @complexity Constant.
  13033. @since version 1.0.0
  13034. @liveexample{The example below shows how array elements can be read using
  13035. `at()`. It also demonstrates the different exceptions that can be thrown.,
  13036. at__size_type_const}
  13037. */
  13038. const_reference at(size_type idx) const
  13039. {
  13040. // at only works for arrays
  13041. if (JSON_LIKELY(is_array()))
  13042. {
  13043. JSON_TRY
  13044. {
  13045. return m_value.array->at(idx);
  13046. }
  13047. JSON_CATCH (std::out_of_range&)
  13048. {
  13049. // create better exception explanation
  13050. JSON_THROW(out_of_range::create(401, "array index " + std::to_string(idx) + " is out of range"));
  13051. }
  13052. }
  13053. else
  13054. {
  13055. JSON_THROW(type_error::create(304, "cannot use at() with " + std::string(type_name())));
  13056. }
  13057. }
  13058. /*!
  13059. @brief access specified object element with bounds checking
  13060. Returns a reference to the element at with specified key @a key, with
  13061. bounds checking.
  13062. @param[in] key key of the element to access
  13063. @return reference to the element at key @a key
  13064. @throw type_error.304 if the JSON value is not an object; in this case,
  13065. calling `at` with a key makes no sense. See example below.
  13066. @throw out_of_range.403 if the key @a key is is not stored in the object;
  13067. that is, `find(key) == end()`. See example below.
  13068. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  13069. changes in the JSON value.
  13070. @complexity Logarithmic in the size of the container.
  13071. @sa @ref operator[](const typename object_t::key_type&) for unchecked
  13072. access by reference
  13073. @sa @ref value() for access by value with a default value
  13074. @since version 1.0.0
  13075. @liveexample{The example below shows how object elements can be read and
  13076. written using `at()`. It also demonstrates the different exceptions that
  13077. can be thrown.,at__object_t_key_type}
  13078. */
  13079. reference at(const typename object_t::key_type& key)
  13080. {
  13081. // at only works for objects
  13082. if (JSON_LIKELY(is_object()))
  13083. {
  13084. JSON_TRY
  13085. {
  13086. return m_value.object->at(key);
  13087. }
  13088. JSON_CATCH (std::out_of_range&)
  13089. {
  13090. // create better exception explanation
  13091. JSON_THROW(out_of_range::create(403, "key '" + key + "' not found"));
  13092. }
  13093. }
  13094. else
  13095. {
  13096. JSON_THROW(type_error::create(304, "cannot use at() with " + std::string(type_name())));
  13097. }
  13098. }
  13099. /*!
  13100. @brief access specified object element with bounds checking
  13101. Returns a const reference to the element at with specified key @a key,
  13102. with bounds checking.
  13103. @param[in] key key of the element to access
  13104. @return const reference to the element at key @a key
  13105. @throw type_error.304 if the JSON value is not an object; in this case,
  13106. calling `at` with a key makes no sense. See example below.
  13107. @throw out_of_range.403 if the key @a key is is not stored in the object;
  13108. that is, `find(key) == end()`. See example below.
  13109. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  13110. changes in the JSON value.
  13111. @complexity Logarithmic in the size of the container.
  13112. @sa @ref operator[](const typename object_t::key_type&) for unchecked
  13113. access by reference
  13114. @sa @ref value() for access by value with a default value
  13115. @since version 1.0.0
  13116. @liveexample{The example below shows how object elements can be read using
  13117. `at()`. It also demonstrates the different exceptions that can be thrown.,
  13118. at__object_t_key_type_const}
  13119. */
  13120. const_reference at(const typename object_t::key_type& key) const
  13121. {
  13122. // at only works for objects
  13123. if (JSON_LIKELY(is_object()))
  13124. {
  13125. JSON_TRY
  13126. {
  13127. return m_value.object->at(key);
  13128. }
  13129. JSON_CATCH (std::out_of_range&)
  13130. {
  13131. // create better exception explanation
  13132. JSON_THROW(out_of_range::create(403, "key '" + key + "' not found"));
  13133. }
  13134. }
  13135. else
  13136. {
  13137. JSON_THROW(type_error::create(304, "cannot use at() with " + std::string(type_name())));
  13138. }
  13139. }
  13140. /*!
  13141. @brief access specified array element
  13142. Returns a reference to the element at specified location @a idx.
  13143. @note If @a idx is beyond the range of the array (i.e., `idx >= size()`),
  13144. then the array is silently filled up with `null` values to make `idx` a
  13145. valid reference to the last stored element.
  13146. @param[in] idx index of the element to access
  13147. @return reference to the element at index @a idx
  13148. @throw type_error.305 if the JSON value is not an array or null; in that
  13149. cases, using the [] operator with an index makes no sense.
  13150. @complexity Constant if @a idx is in the range of the array. Otherwise
  13151. linear in `idx - size()`.
  13152. @liveexample{The example below shows how array elements can be read and
  13153. written using `[]` operator. Note the addition of `null`
  13154. values.,operatorarray__size_type}
  13155. @since version 1.0.0
  13156. */
  13157. reference operator[](size_type idx)
  13158. {
  13159. // implicitly convert null value to an empty array
  13160. if (is_null())
  13161. {
  13162. m_type = value_t::array;
  13163. m_value.array = create<array_t>();
  13164. assert_invariant();
  13165. }
  13166. // operator[] only works for arrays
  13167. if (JSON_LIKELY(is_array()))
  13168. {
  13169. // fill up array with null values if given idx is outside range
  13170. if (idx >= m_value.array->size())
  13171. {
  13172. m_value.array->insert(m_value.array->end(),
  13173. idx - m_value.array->size() + 1,
  13174. basic_json());
  13175. }
  13176. return m_value.array->operator[](idx);
  13177. }
  13178. JSON_THROW(type_error::create(305, "cannot use operator[] with a numeric argument with " + std::string(type_name())));
  13179. }
  13180. /*!
  13181. @brief access specified array element
  13182. Returns a const reference to the element at specified location @a idx.
  13183. @param[in] idx index of the element to access
  13184. @return const reference to the element at index @a idx
  13185. @throw type_error.305 if the JSON value is not an array; in that case,
  13186. using the [] operator with an index makes no sense.
  13187. @complexity Constant.
  13188. @liveexample{The example below shows how array elements can be read using
  13189. the `[]` operator.,operatorarray__size_type_const}
  13190. @since version 1.0.0
  13191. */
  13192. const_reference operator[](size_type idx) const
  13193. {
  13194. // const operator[] only works for arrays
  13195. if (JSON_LIKELY(is_array()))
  13196. {
  13197. return m_value.array->operator[](idx);
  13198. }
  13199. JSON_THROW(type_error::create(305, "cannot use operator[] with a numeric argument with " + std::string(type_name())));
  13200. }
  13201. /*!
  13202. @brief access specified object element
  13203. Returns a reference to the element at with specified key @a key.
  13204. @note If @a key is not found in the object, then it is silently added to
  13205. the object and filled with a `null` value to make `key` a valid reference.
  13206. In case the value was `null` before, it is converted to an object.
  13207. @param[in] key key of the element to access
  13208. @return reference to the element at key @a key
  13209. @throw type_error.305 if the JSON value is not an object or null; in that
  13210. cases, using the [] operator with a key makes no sense.
  13211. @complexity Logarithmic in the size of the container.
  13212. @liveexample{The example below shows how object elements can be read and
  13213. written using the `[]` operator.,operatorarray__key_type}
  13214. @sa @ref at(const typename object_t::key_type&) for access by reference
  13215. with range checking
  13216. @sa @ref value() for access by value with a default value
  13217. @since version 1.0.0
  13218. */
  13219. reference operator[](const typename object_t::key_type& key)
  13220. {
  13221. // implicitly convert null value to an empty object
  13222. if (is_null())
  13223. {
  13224. m_type = value_t::object;
  13225. m_value.object = create<object_t>();
  13226. assert_invariant();
  13227. }
  13228. // operator[] only works for objects
  13229. if (JSON_LIKELY(is_object()))
  13230. {
  13231. return m_value.object->operator[](key);
  13232. }
  13233. JSON_THROW(type_error::create(305, "cannot use operator[] with a string argument with " + std::string(type_name())));
  13234. }
  13235. /*!
  13236. @brief read-only access specified object element
  13237. Returns a const reference to the element at with specified key @a key. No
  13238. bounds checking is performed.
  13239. @warning If the element with key @a key does not exist, the behavior is
  13240. undefined.
  13241. @param[in] key key of the element to access
  13242. @return const reference to the element at key @a key
  13243. @pre The element with key @a key must exist. **This precondition is
  13244. enforced with an assertion.**
  13245. @throw type_error.305 if the JSON value is not an object; in that case,
  13246. using the [] operator with a key makes no sense.
  13247. @complexity Logarithmic in the size of the container.
  13248. @liveexample{The example below shows how object elements can be read using
  13249. the `[]` operator.,operatorarray__key_type_const}
  13250. @sa @ref at(const typename object_t::key_type&) for access by reference
  13251. with range checking
  13252. @sa @ref value() for access by value with a default value
  13253. @since version 1.0.0
  13254. */
  13255. const_reference operator[](const typename object_t::key_type& key) const
  13256. {
  13257. // const operator[] only works for objects
  13258. if (JSON_LIKELY(is_object()))
  13259. {
  13260. assert(m_value.object->find(key) != m_value.object->end());
  13261. return m_value.object->find(key)->second;
  13262. }
  13263. JSON_THROW(type_error::create(305, "cannot use operator[] with a string argument with " + std::string(type_name())));
  13264. }
  13265. /*!
  13266. @brief access specified object element
  13267. Returns a reference to the element at with specified key @a key.
  13268. @note If @a key is not found in the object, then it is silently added to
  13269. the object and filled with a `null` value to make `key` a valid reference.
  13270. In case the value was `null` before, it is converted to an object.
  13271. @param[in] key key of the element to access
  13272. @return reference to the element at key @a key
  13273. @throw type_error.305 if the JSON value is not an object or null; in that
  13274. cases, using the [] operator with a key makes no sense.
  13275. @complexity Logarithmic in the size of the container.
  13276. @liveexample{The example below shows how object elements can be read and
  13277. written using the `[]` operator.,operatorarray__key_type}
  13278. @sa @ref at(const typename object_t::key_type&) for access by reference
  13279. with range checking
  13280. @sa @ref value() for access by value with a default value
  13281. @since version 1.1.0
  13282. */
  13283. template<typename T>
  13284. reference operator[](T* key)
  13285. {
  13286. // implicitly convert null to object
  13287. if (is_null())
  13288. {
  13289. m_type = value_t::object;
  13290. m_value = value_t::object;
  13291. assert_invariant();
  13292. }
  13293. // at only works for objects
  13294. if (JSON_LIKELY(is_object()))
  13295. {
  13296. return m_value.object->operator[](key);
  13297. }
  13298. JSON_THROW(type_error::create(305, "cannot use operator[] with a string argument with " + std::string(type_name())));
  13299. }
  13300. /*!
  13301. @brief read-only access specified object element
  13302. Returns a const reference to the element at with specified key @a key. No
  13303. bounds checking is performed.
  13304. @warning If the element with key @a key does not exist, the behavior is
  13305. undefined.
  13306. @param[in] key key of the element to access
  13307. @return const reference to the element at key @a key
  13308. @pre The element with key @a key must exist. **This precondition is
  13309. enforced with an assertion.**
  13310. @throw type_error.305 if the JSON value is not an object; in that case,
  13311. using the [] operator with a key makes no sense.
  13312. @complexity Logarithmic in the size of the container.
  13313. @liveexample{The example below shows how object elements can be read using
  13314. the `[]` operator.,operatorarray__key_type_const}
  13315. @sa @ref at(const typename object_t::key_type&) for access by reference
  13316. with range checking
  13317. @sa @ref value() for access by value with a default value
  13318. @since version 1.1.0
  13319. */
  13320. template<typename T>
  13321. const_reference operator[](T* key) const
  13322. {
  13323. // at only works for objects
  13324. if (JSON_LIKELY(is_object()))
  13325. {
  13326. assert(m_value.object->find(key) != m_value.object->end());
  13327. return m_value.object->find(key)->second;
  13328. }
  13329. JSON_THROW(type_error::create(305, "cannot use operator[] with a string argument with " + std::string(type_name())));
  13330. }
  13331. /*!
  13332. @brief access specified object element with default value
  13333. Returns either a copy of an object's element at the specified key @a key
  13334. or a given default value if no element with key @a key exists.
  13335. The function is basically equivalent to executing
  13336. @code {.cpp}
  13337. try {
  13338. return at(key);
  13339. } catch(out_of_range) {
  13340. return default_value;
  13341. }
  13342. @endcode
  13343. @note Unlike @ref at(const typename object_t::key_type&), this function
  13344. does not throw if the given key @a key was not found.
  13345. @note Unlike @ref operator[](const typename object_t::key_type& key), this
  13346. function does not implicitly add an element to the position defined by @a
  13347. key. This function is furthermore also applicable to const objects.
  13348. @param[in] key key of the element to access
  13349. @param[in] default_value the value to return if @a key is not found
  13350. @tparam ValueType type compatible to JSON values, for instance `int` for
  13351. JSON integer numbers, `bool` for JSON booleans, or `std::vector` types for
  13352. JSON arrays. Note the type of the expected value at @a key and the default
  13353. value @a default_value must be compatible.
  13354. @return copy of the element at key @a key or @a default_value if @a key
  13355. is not found
  13356. @throw type_error.306 if the JSON value is not an object; in that case,
  13357. using `value()` with a key makes no sense.
  13358. @complexity Logarithmic in the size of the container.
  13359. @liveexample{The example below shows how object elements can be queried
  13360. with a default value.,basic_json__value}
  13361. @sa @ref at(const typename object_t::key_type&) for access by reference
  13362. with range checking
  13363. @sa @ref operator[](const typename object_t::key_type&) for unchecked
  13364. access by reference
  13365. @since version 1.0.0
  13366. */
  13367. template<class ValueType, typename std::enable_if<
  13368. std::is_convertible<basic_json_t, ValueType>::value, int>::type = 0>
  13369. ValueType value(const typename object_t::key_type& key, const ValueType& default_value) const
  13370. {
  13371. // at only works for objects
  13372. if (JSON_LIKELY(is_object()))
  13373. {
  13374. // if key is found, return value and given default value otherwise
  13375. const auto it = find(key);
  13376. if (it != end())
  13377. {
  13378. return *it;
  13379. }
  13380. return default_value;
  13381. }
  13382. JSON_THROW(type_error::create(306, "cannot use value() with " + std::string(type_name())));
  13383. }
  13384. /*!
  13385. @brief overload for a default value of type const char*
  13386. @copydoc basic_json::value(const typename object_t::key_type&, const ValueType&) const
  13387. */
  13388. string_t value(const typename object_t::key_type& key, const char* default_value) const
  13389. {
  13390. return value(key, string_t(default_value));
  13391. }
  13392. /*!
  13393. @brief access specified object element via JSON Pointer with default value
  13394. Returns either a copy of an object's element at the specified key @a key
  13395. or a given default value if no element with key @a key exists.
  13396. The function is basically equivalent to executing
  13397. @code {.cpp}
  13398. try {
  13399. return at(ptr);
  13400. } catch(out_of_range) {
  13401. return default_value;
  13402. }
  13403. @endcode
  13404. @note Unlike @ref at(const json_pointer&), this function does not throw
  13405. if the given key @a key was not found.
  13406. @param[in] ptr a JSON pointer to the element to access
  13407. @param[in] default_value the value to return if @a ptr found no value
  13408. @tparam ValueType type compatible to JSON values, for instance `int` for
  13409. JSON integer numbers, `bool` for JSON booleans, or `std::vector` types for
  13410. JSON arrays. Note the type of the expected value at @a key and the default
  13411. value @a default_value must be compatible.
  13412. @return copy of the element at key @a key or @a default_value if @a key
  13413. is not found
  13414. @throw type_error.306 if the JSON value is not an object; in that case,
  13415. using `value()` with a key makes no sense.
  13416. @complexity Logarithmic in the size of the container.
  13417. @liveexample{The example below shows how object elements can be queried
  13418. with a default value.,basic_json__value_ptr}
  13419. @sa @ref operator[](const json_pointer&) for unchecked access by reference
  13420. @since version 2.0.2
  13421. */
  13422. template<class ValueType, typename std::enable_if<
  13423. std::is_convertible<basic_json_t, ValueType>::value, int>::type = 0>
  13424. ValueType value(const json_pointer& ptr, const ValueType& default_value) const
  13425. {
  13426. // at only works for objects
  13427. if (JSON_LIKELY(is_object()))
  13428. {
  13429. // if pointer resolves a value, return it or use default value
  13430. JSON_TRY
  13431. {
  13432. return ptr.get_checked(this);
  13433. }
  13434. JSON_INTERNAL_CATCH (out_of_range&)
  13435. {
  13436. return default_value;
  13437. }
  13438. }
  13439. JSON_THROW(type_error::create(306, "cannot use value() with " + std::string(type_name())));
  13440. }
  13441. /*!
  13442. @brief overload for a default value of type const char*
  13443. @copydoc basic_json::value(const json_pointer&, ValueType) const
  13444. */
  13445. string_t value(const json_pointer& ptr, const char* default_value) const
  13446. {
  13447. return value(ptr, string_t(default_value));
  13448. }
  13449. /*!
  13450. @brief access the first element
  13451. Returns a reference to the first element in the container. For a JSON
  13452. container `c`, the expression `c.front()` is equivalent to `*c.begin()`.
  13453. @return In case of a structured type (array or object), a reference to the
  13454. first element is returned. In case of number, string, or boolean values, a
  13455. reference to the value is returned.
  13456. @complexity Constant.
  13457. @pre The JSON value must not be `null` (would throw `std::out_of_range`)
  13458. or an empty array or object (undefined behavior, **guarded by
  13459. assertions**).
  13460. @post The JSON value remains unchanged.
  13461. @throw invalid_iterator.214 when called on `null` value
  13462. @liveexample{The following code shows an example for `front()`.,front}
  13463. @sa @ref back() -- access the last element
  13464. @since version 1.0.0
  13465. */
  13466. reference front()
  13467. {
  13468. return *begin();
  13469. }
  13470. /*!
  13471. @copydoc basic_json::front()
  13472. */
  13473. const_reference front() const
  13474. {
  13475. return *cbegin();
  13476. }
  13477. /*!
  13478. @brief access the last element
  13479. Returns a reference to the last element in the container. For a JSON
  13480. container `c`, the expression `c.back()` is equivalent to
  13481. @code {.cpp}
  13482. auto tmp = c.end();
  13483. --tmp;
  13484. return *tmp;
  13485. @endcode
  13486. @return In case of a structured type (array or object), a reference to the
  13487. last element is returned. In case of number, string, or boolean values, a
  13488. reference to the value is returned.
  13489. @complexity Constant.
  13490. @pre The JSON value must not be `null` (would throw `std::out_of_range`)
  13491. or an empty array or object (undefined behavior, **guarded by
  13492. assertions**).
  13493. @post The JSON value remains unchanged.
  13494. @throw invalid_iterator.214 when called on a `null` value. See example
  13495. below.
  13496. @liveexample{The following code shows an example for `back()`.,back}
  13497. @sa @ref front() -- access the first element
  13498. @since version 1.0.0
  13499. */
  13500. reference back()
  13501. {
  13502. auto tmp = end();
  13503. --tmp;
  13504. return *tmp;
  13505. }
  13506. /*!
  13507. @copydoc basic_json::back()
  13508. */
  13509. const_reference back() const
  13510. {
  13511. auto tmp = cend();
  13512. --tmp;
  13513. return *tmp;
  13514. }
  13515. /*!
  13516. @brief remove element given an iterator
  13517. Removes the element specified by iterator @a pos. The iterator @a pos must
  13518. be valid and dereferenceable. Thus the `end()` iterator (which is valid,
  13519. but is not dereferenceable) cannot be used as a value for @a pos.
  13520. If called on a primitive type other than `null`, the resulting JSON value
  13521. will be `null`.
  13522. @param[in] pos iterator to the element to remove
  13523. @return Iterator following the last removed element. If the iterator @a
  13524. pos refers to the last element, the `end()` iterator is returned.
  13525. @tparam IteratorType an @ref iterator or @ref const_iterator
  13526. @post Invalidates iterators and references at or after the point of the
  13527. erase, including the `end()` iterator.
  13528. @throw type_error.307 if called on a `null` value; example: `"cannot use
  13529. erase() with null"`
  13530. @throw invalid_iterator.202 if called on an iterator which does not belong
  13531. to the current JSON value; example: `"iterator does not fit current
  13532. value"`
  13533. @throw invalid_iterator.205 if called on a primitive type with invalid
  13534. iterator (i.e., any iterator which is not `begin()`); example: `"iterator
  13535. out of range"`
  13536. @complexity The complexity depends on the type:
  13537. - objects: amortized constant
  13538. - arrays: linear in distance between @a pos and the end of the container
  13539. - strings: linear in the length of the string
  13540. - other types: constant
  13541. @liveexample{The example shows the result of `erase()` for different JSON
  13542. types.,erase__IteratorType}
  13543. @sa @ref erase(IteratorType, IteratorType) -- removes the elements in
  13544. the given range
  13545. @sa @ref erase(const typename object_t::key_type&) -- removes the element
  13546. from an object at the given key
  13547. @sa @ref erase(const size_type) -- removes the element from an array at
  13548. the given index
  13549. @since version 1.0.0
  13550. */
  13551. template<class IteratorType, typename std::enable_if<
  13552. std::is_same<IteratorType, typename basic_json_t::iterator>::value or
  13553. std::is_same<IteratorType, typename basic_json_t::const_iterator>::value, int>::type
  13554. = 0>
  13555. IteratorType erase(IteratorType pos)
  13556. {
  13557. // make sure iterator fits the current value
  13558. if (JSON_UNLIKELY(this != pos.m_object))
  13559. {
  13560. JSON_THROW(invalid_iterator::create(202, "iterator does not fit current value"));
  13561. }
  13562. IteratorType result = end();
  13563. switch (m_type)
  13564. {
  13565. case value_t::boolean:
  13566. case value_t::number_float:
  13567. case value_t::number_integer:
  13568. case value_t::number_unsigned:
  13569. case value_t::string:
  13570. {
  13571. if (JSON_UNLIKELY(not pos.m_it.primitive_iterator.is_begin()))
  13572. {
  13573. JSON_THROW(invalid_iterator::create(205, "iterator out of range"));
  13574. }
  13575. if (is_string())
  13576. {
  13577. AllocatorType<string_t> alloc;
  13578. std::allocator_traits<decltype(alloc)>::destroy(alloc, m_value.string);
  13579. std::allocator_traits<decltype(alloc)>::deallocate(alloc, m_value.string, 1);
  13580. m_value.string = nullptr;
  13581. }
  13582. m_type = value_t::null;
  13583. assert_invariant();
  13584. break;
  13585. }
  13586. case value_t::object:
  13587. {
  13588. result.m_it.object_iterator = m_value.object->erase(pos.m_it.object_iterator);
  13589. break;
  13590. }
  13591. case value_t::array:
  13592. {
  13593. result.m_it.array_iterator = m_value.array->erase(pos.m_it.array_iterator);
  13594. break;
  13595. }
  13596. default:
  13597. JSON_THROW(type_error::create(307, "cannot use erase() with " + std::string(type_name())));
  13598. }
  13599. return result;
  13600. }
  13601. /*!
  13602. @brief remove elements given an iterator range
  13603. Removes the element specified by the range `[first; last)`. The iterator
  13604. @a first does not need to be dereferenceable if `first == last`: erasing
  13605. an empty range is a no-op.
  13606. If called on a primitive type other than `null`, the resulting JSON value
  13607. will be `null`.
  13608. @param[in] first iterator to the beginning of the range to remove
  13609. @param[in] last iterator past the end of the range to remove
  13610. @return Iterator following the last removed element. If the iterator @a
  13611. second refers to the last element, the `end()` iterator is returned.
  13612. @tparam IteratorType an @ref iterator or @ref const_iterator
  13613. @post Invalidates iterators and references at or after the point of the
  13614. erase, including the `end()` iterator.
  13615. @throw type_error.307 if called on a `null` value; example: `"cannot use
  13616. erase() with null"`
  13617. @throw invalid_iterator.203 if called on iterators which does not belong
  13618. to the current JSON value; example: `"iterators do not fit current value"`
  13619. @throw invalid_iterator.204 if called on a primitive type with invalid
  13620. iterators (i.e., if `first != begin()` and `last != end()`); example:
  13621. `"iterators out of range"`
  13622. @complexity The complexity depends on the type:
  13623. - objects: `log(size()) + std::distance(first, last)`
  13624. - arrays: linear in the distance between @a first and @a last, plus linear
  13625. in the distance between @a last and end of the container
  13626. - strings: linear in the length of the string
  13627. - other types: constant
  13628. @liveexample{The example shows the result of `erase()` for different JSON
  13629. types.,erase__IteratorType_IteratorType}
  13630. @sa @ref erase(IteratorType) -- removes the element at a given position
  13631. @sa @ref erase(const typename object_t::key_type&) -- removes the element
  13632. from an object at the given key
  13633. @sa @ref erase(const size_type) -- removes the element from an array at
  13634. the given index
  13635. @since version 1.0.0
  13636. */
  13637. template<class IteratorType, typename std::enable_if<
  13638. std::is_same<IteratorType, typename basic_json_t::iterator>::value or
  13639. std::is_same<IteratorType, typename basic_json_t::const_iterator>::value, int>::type
  13640. = 0>
  13641. IteratorType erase(IteratorType first, IteratorType last)
  13642. {
  13643. // make sure iterator fits the current value
  13644. if (JSON_UNLIKELY(this != first.m_object or this != last.m_object))
  13645. {
  13646. JSON_THROW(invalid_iterator::create(203, "iterators do not fit current value"));
  13647. }
  13648. IteratorType result = end();
  13649. switch (m_type)
  13650. {
  13651. case value_t::boolean:
  13652. case value_t::number_float:
  13653. case value_t::number_integer:
  13654. case value_t::number_unsigned:
  13655. case value_t::string:
  13656. {
  13657. if (JSON_LIKELY(not first.m_it.primitive_iterator.is_begin()
  13658. or not last.m_it.primitive_iterator.is_end()))
  13659. {
  13660. JSON_THROW(invalid_iterator::create(204, "iterators out of range"));
  13661. }
  13662. if (is_string())
  13663. {
  13664. AllocatorType<string_t> alloc;
  13665. std::allocator_traits<decltype(alloc)>::destroy(alloc, m_value.string);
  13666. std::allocator_traits<decltype(alloc)>::deallocate(alloc, m_value.string, 1);
  13667. m_value.string = nullptr;
  13668. }
  13669. m_type = value_t::null;
  13670. assert_invariant();
  13671. break;
  13672. }
  13673. case value_t::object:
  13674. {
  13675. result.m_it.object_iterator = m_value.object->erase(first.m_it.object_iterator,
  13676. last.m_it.object_iterator);
  13677. break;
  13678. }
  13679. case value_t::array:
  13680. {
  13681. result.m_it.array_iterator = m_value.array->erase(first.m_it.array_iterator,
  13682. last.m_it.array_iterator);
  13683. break;
  13684. }
  13685. default:
  13686. JSON_THROW(type_error::create(307, "cannot use erase() with " + std::string(type_name())));
  13687. }
  13688. return result;
  13689. }
  13690. /*!
  13691. @brief remove element from a JSON object given a key
  13692. Removes elements from a JSON object with the key value @a key.
  13693. @param[in] key value of the elements to remove
  13694. @return Number of elements removed. If @a ObjectType is the default
  13695. `std::map` type, the return value will always be `0` (@a key was not
  13696. found) or `1` (@a key was found).
  13697. @post References and iterators to the erased elements are invalidated.
  13698. Other references and iterators are not affected.
  13699. @throw type_error.307 when called on a type other than JSON object;
  13700. example: `"cannot use erase() with null"`
  13701. @complexity `log(size()) + count(key)`
  13702. @liveexample{The example shows the effect of `erase()`.,erase__key_type}
  13703. @sa @ref erase(IteratorType) -- removes the element at a given position
  13704. @sa @ref erase(IteratorType, IteratorType) -- removes the elements in
  13705. the given range
  13706. @sa @ref erase(const size_type) -- removes the element from an array at
  13707. the given index
  13708. @since version 1.0.0
  13709. */
  13710. size_type erase(const typename object_t::key_type& key)
  13711. {
  13712. // this erase only works for objects
  13713. if (JSON_LIKELY(is_object()))
  13714. {
  13715. return m_value.object->erase(key);
  13716. }
  13717. JSON_THROW(type_error::create(307, "cannot use erase() with " + std::string(type_name())));
  13718. }
  13719. /*!
  13720. @brief remove element from a JSON array given an index
  13721. Removes element from a JSON array at the index @a idx.
  13722. @param[in] idx index of the element to remove
  13723. @throw type_error.307 when called on a type other than JSON object;
  13724. example: `"cannot use erase() with null"`
  13725. @throw out_of_range.401 when `idx >= size()`; example: `"array index 17
  13726. is out of range"`
  13727. @complexity Linear in distance between @a idx and the end of the container.
  13728. @liveexample{The example shows the effect of `erase()`.,erase__size_type}
  13729. @sa @ref erase(IteratorType) -- removes the element at a given position
  13730. @sa @ref erase(IteratorType, IteratorType) -- removes the elements in
  13731. the given range
  13732. @sa @ref erase(const typename object_t::key_type&) -- removes the element
  13733. from an object at the given key
  13734. @since version 1.0.0
  13735. */
  13736. void erase(const size_type idx)
  13737. {
  13738. // this erase only works for arrays
  13739. if (JSON_LIKELY(is_array()))
  13740. {
  13741. if (JSON_UNLIKELY(idx >= size()))
  13742. {
  13743. JSON_THROW(out_of_range::create(401, "array index " + std::to_string(idx) + " is out of range"));
  13744. }
  13745. m_value.array->erase(m_value.array->begin() + static_cast<difference_type>(idx));
  13746. }
  13747. else
  13748. {
  13749. JSON_THROW(type_error::create(307, "cannot use erase() with " + std::string(type_name())));
  13750. }
  13751. }
  13752. /// @}
  13753. ////////////
  13754. // lookup //
  13755. ////////////
  13756. /// @name lookup
  13757. /// @{
  13758. /*!
  13759. @brief find an element in a JSON object
  13760. Finds an element in a JSON object with key equivalent to @a key. If the
  13761. element is not found or the JSON value is not an object, end() is
  13762. returned.
  13763. @note This method always returns @ref end() when executed on a JSON type
  13764. that is not an object.
  13765. @param[in] key key value of the element to search for.
  13766. @return Iterator to an element with key equivalent to @a key. If no such
  13767. element is found or the JSON value is not an object, past-the-end (see
  13768. @ref end()) iterator is returned.
  13769. @complexity Logarithmic in the size of the JSON object.
  13770. @liveexample{The example shows how `find()` is used.,find__key_type}
  13771. @since version 1.0.0
  13772. */
  13773. template<typename KeyT>
  13774. iterator find(KeyT&& key)
  13775. {
  13776. auto result = end();
  13777. if (is_object())
  13778. {
  13779. result.m_it.object_iterator = m_value.object->find(std::forward<KeyT>(key));
  13780. }
  13781. return result;
  13782. }
  13783. /*!
  13784. @brief find an element in a JSON object
  13785. @copydoc find(KeyT&&)
  13786. */
  13787. template<typename KeyT>
  13788. const_iterator find(KeyT&& key) const
  13789. {
  13790. auto result = cend();
  13791. if (is_object())
  13792. {
  13793. result.m_it.object_iterator = m_value.object->find(std::forward<KeyT>(key));
  13794. }
  13795. return result;
  13796. }
  13797. /*!
  13798. @brief returns the number of occurrences of a key in a JSON object
  13799. Returns the number of elements with key @a key. If ObjectType is the
  13800. default `std::map` type, the return value will always be `0` (@a key was
  13801. not found) or `1` (@a key was found).
  13802. @note This method always returns `0` when executed on a JSON type that is
  13803. not an object.
  13804. @param[in] key key value of the element to count
  13805. @return Number of elements with key @a key. If the JSON value is not an
  13806. object, the return value will be `0`.
  13807. @complexity Logarithmic in the size of the JSON object.
  13808. @liveexample{The example shows how `count()` is used.,count}
  13809. @since version 1.0.0
  13810. */
  13811. template<typename KeyT>
  13812. size_type count(KeyT&& key) const
  13813. {
  13814. // return 0 for all nonobject types
  13815. return is_object() ? m_value.object->count(std::forward<KeyT>(key)) : 0;
  13816. }
  13817. /// @}
  13818. ///////////////
  13819. // iterators //
  13820. ///////////////
  13821. /// @name iterators
  13822. /// @{
  13823. /*!
  13824. @brief returns an iterator to the first element
  13825. Returns an iterator to the first element.
  13826. @image html range-begin-end.svg "Illustration from cppreference.com"
  13827. @return iterator to the first element
  13828. @complexity Constant.
  13829. @requirement This function helps `basic_json` satisfying the
  13830. [Container](https://en.cppreference.com/w/cpp/named_req/Container)
  13831. requirements:
  13832. - The complexity is constant.
  13833. @liveexample{The following code shows an example for `begin()`.,begin}
  13834. @sa @ref cbegin() -- returns a const iterator to the beginning
  13835. @sa @ref end() -- returns an iterator to the end
  13836. @sa @ref cend() -- returns a const iterator to the end
  13837. @since version 1.0.0
  13838. */
  13839. iterator begin() noexcept
  13840. {
  13841. iterator result(this);
  13842. result.set_begin();
  13843. return result;
  13844. }
  13845. /*!
  13846. @copydoc basic_json::cbegin()
  13847. */
  13848. const_iterator begin() const noexcept
  13849. {
  13850. return cbegin();
  13851. }
  13852. /*!
  13853. @brief returns a const iterator to the first element
  13854. Returns a const iterator to the first element.
  13855. @image html range-begin-end.svg "Illustration from cppreference.com"
  13856. @return const iterator to the first element
  13857. @complexity Constant.
  13858. @requirement This function helps `basic_json` satisfying the
  13859. [Container](https://en.cppreference.com/w/cpp/named_req/Container)
  13860. requirements:
  13861. - The complexity is constant.
  13862. - Has the semantics of `const_cast<const basic_json&>(*this).begin()`.
  13863. @liveexample{The following code shows an example for `cbegin()`.,cbegin}
  13864. @sa @ref begin() -- returns an iterator to the beginning
  13865. @sa @ref end() -- returns an iterator to the end
  13866. @sa @ref cend() -- returns a const iterator to the end
  13867. @since version 1.0.0
  13868. */
  13869. const_iterator cbegin() const noexcept
  13870. {
  13871. const_iterator result(this);
  13872. result.set_begin();
  13873. return result;
  13874. }
  13875. /*!
  13876. @brief returns an iterator to one past the last element
  13877. Returns an iterator to one past the last element.
  13878. @image html range-begin-end.svg "Illustration from cppreference.com"
  13879. @return iterator one past the last element
  13880. @complexity Constant.
  13881. @requirement This function helps `basic_json` satisfying the
  13882. [Container](https://en.cppreference.com/w/cpp/named_req/Container)
  13883. requirements:
  13884. - The complexity is constant.
  13885. @liveexample{The following code shows an example for `end()`.,end}
  13886. @sa @ref cend() -- returns a const iterator to the end
  13887. @sa @ref begin() -- returns an iterator to the beginning
  13888. @sa @ref cbegin() -- returns a const iterator to the beginning
  13889. @since version 1.0.0
  13890. */
  13891. iterator end() noexcept
  13892. {
  13893. iterator result(this);
  13894. result.set_end();
  13895. return result;
  13896. }
  13897. /*!
  13898. @copydoc basic_json::cend()
  13899. */
  13900. const_iterator end() const noexcept
  13901. {
  13902. return cend();
  13903. }
  13904. /*!
  13905. @brief returns a const iterator to one past the last element
  13906. Returns a const iterator to one past the last element.
  13907. @image html range-begin-end.svg "Illustration from cppreference.com"
  13908. @return const iterator one past the last element
  13909. @complexity Constant.
  13910. @requirement This function helps `basic_json` satisfying the
  13911. [Container](https://en.cppreference.com/w/cpp/named_req/Container)
  13912. requirements:
  13913. - The complexity is constant.
  13914. - Has the semantics of `const_cast<const basic_json&>(*this).end()`.
  13915. @liveexample{The following code shows an example for `cend()`.,cend}
  13916. @sa @ref end() -- returns an iterator to the end
  13917. @sa @ref begin() -- returns an iterator to the beginning
  13918. @sa @ref cbegin() -- returns a const iterator to the beginning
  13919. @since version 1.0.0
  13920. */
  13921. const_iterator cend() const noexcept
  13922. {
  13923. const_iterator result(this);
  13924. result.set_end();
  13925. return result;
  13926. }
  13927. /*!
  13928. @brief returns an iterator to the reverse-beginning
  13929. Returns an iterator to the reverse-beginning; that is, the last element.
  13930. @image html range-rbegin-rend.svg "Illustration from cppreference.com"
  13931. @complexity Constant.
  13932. @requirement This function helps `basic_json` satisfying the
  13933. [ReversibleContainer](https://en.cppreference.com/w/cpp/named_req/ReversibleContainer)
  13934. requirements:
  13935. - The complexity is constant.
  13936. - Has the semantics of `reverse_iterator(end())`.
  13937. @liveexample{The following code shows an example for `rbegin()`.,rbegin}
  13938. @sa @ref crbegin() -- returns a const reverse iterator to the beginning
  13939. @sa @ref rend() -- returns a reverse iterator to the end
  13940. @sa @ref crend() -- returns a const reverse iterator to the end
  13941. @since version 1.0.0
  13942. */
  13943. reverse_iterator rbegin() noexcept
  13944. {
  13945. return reverse_iterator(end());
  13946. }
  13947. /*!
  13948. @copydoc basic_json::crbegin()
  13949. */
  13950. const_reverse_iterator rbegin() const noexcept
  13951. {
  13952. return crbegin();
  13953. }
  13954. /*!
  13955. @brief returns an iterator to the reverse-end
  13956. Returns an iterator to the reverse-end; that is, one before the first
  13957. element.
  13958. @image html range-rbegin-rend.svg "Illustration from cppreference.com"
  13959. @complexity Constant.
  13960. @requirement This function helps `basic_json` satisfying the
  13961. [ReversibleContainer](https://en.cppreference.com/w/cpp/named_req/ReversibleContainer)
  13962. requirements:
  13963. - The complexity is constant.
  13964. - Has the semantics of `reverse_iterator(begin())`.
  13965. @liveexample{The following code shows an example for `rend()`.,rend}
  13966. @sa @ref crend() -- returns a const reverse iterator to the end
  13967. @sa @ref rbegin() -- returns a reverse iterator to the beginning
  13968. @sa @ref crbegin() -- returns a const reverse iterator to the beginning
  13969. @since version 1.0.0
  13970. */
  13971. reverse_iterator rend() noexcept
  13972. {
  13973. return reverse_iterator(begin());
  13974. }
  13975. /*!
  13976. @copydoc basic_json::crend()
  13977. */
  13978. const_reverse_iterator rend() const noexcept
  13979. {
  13980. return crend();
  13981. }
  13982. /*!
  13983. @brief returns a const reverse iterator to the last element
  13984. Returns a const iterator to the reverse-beginning; that is, the last
  13985. element.
  13986. @image html range-rbegin-rend.svg "Illustration from cppreference.com"
  13987. @complexity Constant.
  13988. @requirement This function helps `basic_json` satisfying the
  13989. [ReversibleContainer](https://en.cppreference.com/w/cpp/named_req/ReversibleContainer)
  13990. requirements:
  13991. - The complexity is constant.
  13992. - Has the semantics of `const_cast<const basic_json&>(*this).rbegin()`.
  13993. @liveexample{The following code shows an example for `crbegin()`.,crbegin}
  13994. @sa @ref rbegin() -- returns a reverse iterator to the beginning
  13995. @sa @ref rend() -- returns a reverse iterator to the end
  13996. @sa @ref crend() -- returns a const reverse iterator to the end
  13997. @since version 1.0.0
  13998. */
  13999. const_reverse_iterator crbegin() const noexcept
  14000. {
  14001. return const_reverse_iterator(cend());
  14002. }
  14003. /*!
  14004. @brief returns a const reverse iterator to one before the first
  14005. Returns a const reverse iterator to the reverse-end; that is, one before
  14006. the first element.
  14007. @image html range-rbegin-rend.svg "Illustration from cppreference.com"
  14008. @complexity Constant.
  14009. @requirement This function helps `basic_json` satisfying the
  14010. [ReversibleContainer](https://en.cppreference.com/w/cpp/named_req/ReversibleContainer)
  14011. requirements:
  14012. - The complexity is constant.
  14013. - Has the semantics of `const_cast<const basic_json&>(*this).rend()`.
  14014. @liveexample{The following code shows an example for `crend()`.,crend}
  14015. @sa @ref rend() -- returns a reverse iterator to the end
  14016. @sa @ref rbegin() -- returns a reverse iterator to the beginning
  14017. @sa @ref crbegin() -- returns a const reverse iterator to the beginning
  14018. @since version 1.0.0
  14019. */
  14020. const_reverse_iterator crend() const noexcept
  14021. {
  14022. return const_reverse_iterator(cbegin());
  14023. }
  14024. public:
  14025. /*!
  14026. @brief wrapper to access iterator member functions in range-based for
  14027. This function allows to access @ref iterator::key() and @ref
  14028. iterator::value() during range-based for loops. In these loops, a
  14029. reference to the JSON values is returned, so there is no access to the
  14030. underlying iterator.
  14031. For loop without iterator_wrapper:
  14032. @code{cpp}
  14033. for (auto it = j_object.begin(); it != j_object.end(); ++it)
  14034. {
  14035. std::cout << "key: " << it.key() << ", value:" << it.value() << '\n';
  14036. }
  14037. @endcode
  14038. Range-based for loop without iterator proxy:
  14039. @code{cpp}
  14040. for (auto it : j_object)
  14041. {
  14042. // "it" is of type json::reference and has no key() member
  14043. std::cout << "value: " << it << '\n';
  14044. }
  14045. @endcode
  14046. Range-based for loop with iterator proxy:
  14047. @code{cpp}
  14048. for (auto it : json::iterator_wrapper(j_object))
  14049. {
  14050. std::cout << "key: " << it.key() << ", value:" << it.value() << '\n';
  14051. }
  14052. @endcode
  14053. @note When iterating over an array, `key()` will return the index of the
  14054. element as string (see example).
  14055. @param[in] ref reference to a JSON value
  14056. @return iteration proxy object wrapping @a ref with an interface to use in
  14057. range-based for loops
  14058. @liveexample{The following code shows how the wrapper is used,iterator_wrapper}
  14059. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  14060. changes in the JSON value.
  14061. @complexity Constant.
  14062. @note The name of this function is not yet final and may change in the
  14063. future.
  14064. @deprecated This stream operator is deprecated and will be removed in
  14065. future 4.0.0 of the library. Please use @ref items() instead;
  14066. that is, replace `json::iterator_wrapper(j)` with `j.items()`.
  14067. */
  14068. JSON_DEPRECATED
  14069. static iteration_proxy<iterator> iterator_wrapper(reference ref) noexcept
  14070. {
  14071. return ref.items();
  14072. }
  14073. /*!
  14074. @copydoc iterator_wrapper(reference)
  14075. */
  14076. JSON_DEPRECATED
  14077. static iteration_proxy<const_iterator> iterator_wrapper(const_reference ref) noexcept
  14078. {
  14079. return ref.items();
  14080. }
  14081. /*!
  14082. @brief helper to access iterator member functions in range-based for
  14083. This function allows to access @ref iterator::key() and @ref
  14084. iterator::value() during range-based for loops. In these loops, a
  14085. reference to the JSON values is returned, so there is no access to the
  14086. underlying iterator.
  14087. For loop without `items()` function:
  14088. @code{cpp}
  14089. for (auto it = j_object.begin(); it != j_object.end(); ++it)
  14090. {
  14091. std::cout << "key: " << it.key() << ", value:" << it.value() << '\n';
  14092. }
  14093. @endcode
  14094. Range-based for loop without `items()` function:
  14095. @code{cpp}
  14096. for (auto it : j_object)
  14097. {
  14098. // "it" is of type json::reference and has no key() member
  14099. std::cout << "value: " << it << '\n';
  14100. }
  14101. @endcode
  14102. Range-based for loop with `items()` function:
  14103. @code{cpp}
  14104. for (auto& el : j_object.items())
  14105. {
  14106. std::cout << "key: " << el.key() << ", value:" << el.value() << '\n';
  14107. }
  14108. @endcode
  14109. The `items()` function also allows to use
  14110. [structured bindings](https://en.cppreference.com/w/cpp/language/structured_binding)
  14111. (C++17):
  14112. @code{cpp}
  14113. for (auto& [key, val] : j_object.items())
  14114. {
  14115. std::cout << "key: " << key << ", value:" << val << '\n';
  14116. }
  14117. @endcode
  14118. @note When iterating over an array, `key()` will return the index of the
  14119. element as string (see example). For primitive types (e.g., numbers),
  14120. `key()` returns an empty string.
  14121. @return iteration proxy object wrapping @a ref with an interface to use in
  14122. range-based for loops
  14123. @liveexample{The following code shows how the function is used.,items}
  14124. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  14125. changes in the JSON value.
  14126. @complexity Constant.
  14127. @since version 3.1.0, structured bindings support since 3.5.0.
  14128. */
  14129. iteration_proxy<iterator> items() noexcept
  14130. {
  14131. return iteration_proxy<iterator>(*this);
  14132. }
  14133. /*!
  14134. @copydoc items()
  14135. */
  14136. iteration_proxy<const_iterator> items() const noexcept
  14137. {
  14138. return iteration_proxy<const_iterator>(*this);
  14139. }
  14140. /// @}
  14141. //////////////
  14142. // capacity //
  14143. //////////////
  14144. /// @name capacity
  14145. /// @{
  14146. /*!
  14147. @brief checks whether the container is empty.
  14148. Checks if a JSON value has no elements (i.e. whether its @ref size is `0`).
  14149. @return The return value depends on the different types and is
  14150. defined as follows:
  14151. Value type | return value
  14152. ----------- | -------------
  14153. null | `true`
  14154. boolean | `false`
  14155. string | `false`
  14156. number | `false`
  14157. object | result of function `object_t::empty()`
  14158. array | result of function `array_t::empty()`
  14159. @liveexample{The following code uses `empty()` to check if a JSON
  14160. object contains any elements.,empty}
  14161. @complexity Constant, as long as @ref array_t and @ref object_t satisfy
  14162. the Container concept; that is, their `empty()` functions have constant
  14163. complexity.
  14164. @iterators No changes.
  14165. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  14166. @note This function does not return whether a string stored as JSON value
  14167. is empty - it returns whether the JSON container itself is empty which is
  14168. false in the case of a string.
  14169. @requirement This function helps `basic_json` satisfying the
  14170. [Container](https://en.cppreference.com/w/cpp/named_req/Container)
  14171. requirements:
  14172. - The complexity is constant.
  14173. - Has the semantics of `begin() == end()`.
  14174. @sa @ref size() -- returns the number of elements
  14175. @since version 1.0.0
  14176. */
  14177. bool empty() const noexcept
  14178. {
  14179. switch (m_type)
  14180. {
  14181. case value_t::null:
  14182. {
  14183. // null values are empty
  14184. return true;
  14185. }
  14186. case value_t::array:
  14187. {
  14188. // delegate call to array_t::empty()
  14189. return m_value.array->empty();
  14190. }
  14191. case value_t::object:
  14192. {
  14193. // delegate call to object_t::empty()
  14194. return m_value.object->empty();
  14195. }
  14196. default:
  14197. {
  14198. // all other types are nonempty
  14199. return false;
  14200. }
  14201. }
  14202. }
  14203. /*!
  14204. @brief returns the number of elements
  14205. Returns the number of elements in a JSON value.
  14206. @return The return value depends on the different types and is
  14207. defined as follows:
  14208. Value type | return value
  14209. ----------- | -------------
  14210. null | `0`
  14211. boolean | `1`
  14212. string | `1`
  14213. number | `1`
  14214. object | result of function object_t::size()
  14215. array | result of function array_t::size()
  14216. @liveexample{The following code calls `size()` on the different value
  14217. types.,size}
  14218. @complexity Constant, as long as @ref array_t and @ref object_t satisfy
  14219. the Container concept; that is, their size() functions have constant
  14220. complexity.
  14221. @iterators No changes.
  14222. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  14223. @note This function does not return the length of a string stored as JSON
  14224. value - it returns the number of elements in the JSON value which is 1 in
  14225. the case of a string.
  14226. @requirement This function helps `basic_json` satisfying the
  14227. [Container](https://en.cppreference.com/w/cpp/named_req/Container)
  14228. requirements:
  14229. - The complexity is constant.
  14230. - Has the semantics of `std::distance(begin(), end())`.
  14231. @sa @ref empty() -- checks whether the container is empty
  14232. @sa @ref max_size() -- returns the maximal number of elements
  14233. @since version 1.0.0
  14234. */
  14235. size_type size() const noexcept
  14236. {
  14237. switch (m_type)
  14238. {
  14239. case value_t::null:
  14240. {
  14241. // null values are empty
  14242. return 0;
  14243. }
  14244. case value_t::array:
  14245. {
  14246. // delegate call to array_t::size()
  14247. return m_value.array->size();
  14248. }
  14249. case value_t::object:
  14250. {
  14251. // delegate call to object_t::size()
  14252. return m_value.object->size();
  14253. }
  14254. default:
  14255. {
  14256. // all other types have size 1
  14257. return 1;
  14258. }
  14259. }
  14260. }
  14261. /*!
  14262. @brief returns the maximum possible number of elements
  14263. Returns the maximum number of elements a JSON value is able to hold due to
  14264. system or library implementation limitations, i.e. `std::distance(begin(),
  14265. end())` for the JSON value.
  14266. @return The return value depends on the different types and is
  14267. defined as follows:
  14268. Value type | return value
  14269. ----------- | -------------
  14270. null | `0` (same as `size()`)
  14271. boolean | `1` (same as `size()`)
  14272. string | `1` (same as `size()`)
  14273. number | `1` (same as `size()`)
  14274. object | result of function `object_t::max_size()`
  14275. array | result of function `array_t::max_size()`
  14276. @liveexample{The following code calls `max_size()` on the different value
  14277. types. Note the output is implementation specific.,max_size}
  14278. @complexity Constant, as long as @ref array_t and @ref object_t satisfy
  14279. the Container concept; that is, their `max_size()` functions have constant
  14280. complexity.
  14281. @iterators No changes.
  14282. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  14283. @requirement This function helps `basic_json` satisfying the
  14284. [Container](https://en.cppreference.com/w/cpp/named_req/Container)
  14285. requirements:
  14286. - The complexity is constant.
  14287. - Has the semantics of returning `b.size()` where `b` is the largest
  14288. possible JSON value.
  14289. @sa @ref size() -- returns the number of elements
  14290. @since version 1.0.0
  14291. */
  14292. size_type max_size() const noexcept
  14293. {
  14294. switch (m_type)
  14295. {
  14296. case value_t::array:
  14297. {
  14298. // delegate call to array_t::max_size()
  14299. return m_value.array->max_size();
  14300. }
  14301. case value_t::object:
  14302. {
  14303. // delegate call to object_t::max_size()
  14304. return m_value.object->max_size();
  14305. }
  14306. default:
  14307. {
  14308. // all other types have max_size() == size()
  14309. return size();
  14310. }
  14311. }
  14312. }
  14313. /// @}
  14314. ///////////////
  14315. // modifiers //
  14316. ///////////////
  14317. /// @name modifiers
  14318. /// @{
  14319. /*!
  14320. @brief clears the contents
  14321. Clears the content of a JSON value and resets it to the default value as
  14322. if @ref basic_json(value_t) would have been called with the current value
  14323. type from @ref type():
  14324. Value type | initial value
  14325. ----------- | -------------
  14326. null | `null`
  14327. boolean | `false`
  14328. string | `""`
  14329. number | `0`
  14330. object | `{}`
  14331. array | `[]`
  14332. @post Has the same effect as calling
  14333. @code {.cpp}
  14334. *this = basic_json(type());
  14335. @endcode
  14336. @liveexample{The example below shows the effect of `clear()` to different
  14337. JSON types.,clear}
  14338. @complexity Linear in the size of the JSON value.
  14339. @iterators All iterators, pointers and references related to this container
  14340. are invalidated.
  14341. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  14342. @sa @ref basic_json(value_t) -- constructor that creates an object with the
  14343. same value than calling `clear()`
  14344. @since version 1.0.0
  14345. */
  14346. void clear() noexcept
  14347. {
  14348. switch (m_type)
  14349. {
  14350. case value_t::number_integer:
  14351. {
  14352. m_value.number_integer = 0;
  14353. break;
  14354. }
  14355. case value_t::number_unsigned:
  14356. {
  14357. m_value.number_unsigned = 0;
  14358. break;
  14359. }
  14360. case value_t::number_float:
  14361. {
  14362. m_value.number_float = 0.0;
  14363. break;
  14364. }
  14365. case value_t::boolean:
  14366. {
  14367. m_value.boolean = false;
  14368. break;
  14369. }
  14370. case value_t::string:
  14371. {
  14372. m_value.string->clear();
  14373. break;
  14374. }
  14375. case value_t::array:
  14376. {
  14377. m_value.array->clear();
  14378. break;
  14379. }
  14380. case value_t::object:
  14381. {
  14382. m_value.object->clear();
  14383. break;
  14384. }
  14385. default:
  14386. break;
  14387. }
  14388. }
  14389. /*!
  14390. @brief add an object to an array
  14391. Appends the given element @a val to the end of the JSON value. If the
  14392. function is called on a JSON null value, an empty array is created before
  14393. appending @a val.
  14394. @param[in] val the value to add to the JSON array
  14395. @throw type_error.308 when called on a type other than JSON array or
  14396. null; example: `"cannot use push_back() with number"`
  14397. @complexity Amortized constant.
  14398. @liveexample{The example shows how `push_back()` and `+=` can be used to
  14399. add elements to a JSON array. Note how the `null` value was silently
  14400. converted to a JSON array.,push_back}
  14401. @since version 1.0.0
  14402. */
  14403. void push_back(basic_json&& val)
  14404. {
  14405. // push_back only works for null objects or arrays
  14406. if (JSON_UNLIKELY(not(is_null() or is_array())))
  14407. {
  14408. JSON_THROW(type_error::create(308, "cannot use push_back() with " + std::string(type_name())));
  14409. }
  14410. // transform null object into an array
  14411. if (is_null())
  14412. {
  14413. m_type = value_t::array;
  14414. m_value = value_t::array;
  14415. assert_invariant();
  14416. }
  14417. // add element to array (move semantics)
  14418. m_value.array->push_back(std::move(val));
  14419. // invalidate object
  14420. val.m_type = value_t::null;
  14421. }
  14422. /*!
  14423. @brief add an object to an array
  14424. @copydoc push_back(basic_json&&)
  14425. */
  14426. reference operator+=(basic_json&& val)
  14427. {
  14428. push_back(std::move(val));
  14429. return *this;
  14430. }
  14431. /*!
  14432. @brief add an object to an array
  14433. @copydoc push_back(basic_json&&)
  14434. */
  14435. void push_back(const basic_json& val)
  14436. {
  14437. // push_back only works for null objects or arrays
  14438. if (JSON_UNLIKELY(not(is_null() or is_array())))
  14439. {
  14440. JSON_THROW(type_error::create(308, "cannot use push_back() with " + std::string(type_name())));
  14441. }
  14442. // transform null object into an array
  14443. if (is_null())
  14444. {
  14445. m_type = value_t::array;
  14446. m_value = value_t::array;
  14447. assert_invariant();
  14448. }
  14449. // add element to array
  14450. m_value.array->push_back(val);
  14451. }
  14452. /*!
  14453. @brief add an object to an array
  14454. @copydoc push_back(basic_json&&)
  14455. */
  14456. reference operator+=(const basic_json& val)
  14457. {
  14458. push_back(val);
  14459. return *this;
  14460. }
  14461. /*!
  14462. @brief add an object to an object
  14463. Inserts the given element @a val to the JSON object. If the function is
  14464. called on a JSON null value, an empty object is created before inserting
  14465. @a val.
  14466. @param[in] val the value to add to the JSON object
  14467. @throw type_error.308 when called on a type other than JSON object or
  14468. null; example: `"cannot use push_back() with number"`
  14469. @complexity Logarithmic in the size of the container, O(log(`size()`)).
  14470. @liveexample{The example shows how `push_back()` and `+=` can be used to
  14471. add elements to a JSON object. Note how the `null` value was silently
  14472. converted to a JSON object.,push_back__object_t__value}
  14473. @since version 1.0.0
  14474. */
  14475. void push_back(const typename object_t::value_type& val)
  14476. {
  14477. // push_back only works for null objects or objects
  14478. if (JSON_UNLIKELY(not(is_null() or is_object())))
  14479. {
  14480. JSON_THROW(type_error::create(308, "cannot use push_back() with " + std::string(type_name())));
  14481. }
  14482. // transform null object into an object
  14483. if (is_null())
  14484. {
  14485. m_type = value_t::object;
  14486. m_value = value_t::object;
  14487. assert_invariant();
  14488. }
  14489. // add element to array
  14490. m_value.object->insert(val);
  14491. }
  14492. /*!
  14493. @brief add an object to an object
  14494. @copydoc push_back(const typename object_t::value_type&)
  14495. */
  14496. reference operator+=(const typename object_t::value_type& val)
  14497. {
  14498. push_back(val);
  14499. return *this;
  14500. }
  14501. /*!
  14502. @brief add an object to an object
  14503. This function allows to use `push_back` with an initializer list. In case
  14504. 1. the current value is an object,
  14505. 2. the initializer list @a init contains only two elements, and
  14506. 3. the first element of @a init is a string,
  14507. @a init is converted into an object element and added using
  14508. @ref push_back(const typename object_t::value_type&). Otherwise, @a init
  14509. is converted to a JSON value and added using @ref push_back(basic_json&&).
  14510. @param[in] init an initializer list
  14511. @complexity Linear in the size of the initializer list @a init.
  14512. @note This function is required to resolve an ambiguous overload error,
  14513. because pairs like `{"key", "value"}` can be both interpreted as
  14514. `object_t::value_type` or `std::initializer_list<basic_json>`, see
  14515. https://github.com/nlohmann/json/issues/235 for more information.
  14516. @liveexample{The example shows how initializer lists are treated as
  14517. objects when possible.,push_back__initializer_list}
  14518. */
  14519. void push_back(initializer_list_t init)
  14520. {
  14521. if (is_object() and init.size() == 2 and (*init.begin())->is_string())
  14522. {
  14523. basic_json&& key = init.begin()->moved_or_copied();
  14524. push_back(typename object_t::value_type(
  14525. std::move(key.get_ref<string_t&>()), (init.begin() + 1)->moved_or_copied()));
  14526. }
  14527. else
  14528. {
  14529. push_back(basic_json(init));
  14530. }
  14531. }
  14532. /*!
  14533. @brief add an object to an object
  14534. @copydoc push_back(initializer_list_t)
  14535. */
  14536. reference operator+=(initializer_list_t init)
  14537. {
  14538. push_back(init);
  14539. return *this;
  14540. }
  14541. /*!
  14542. @brief add an object to an array
  14543. Creates a JSON value from the passed parameters @a args to the end of the
  14544. JSON value. If the function is called on a JSON null value, an empty array
  14545. is created before appending the value created from @a args.
  14546. @param[in] args arguments to forward to a constructor of @ref basic_json
  14547. @tparam Args compatible types to create a @ref basic_json object
  14548. @throw type_error.311 when called on a type other than JSON array or
  14549. null; example: `"cannot use emplace_back() with number"`
  14550. @complexity Amortized constant.
  14551. @liveexample{The example shows how `push_back()` can be used to add
  14552. elements to a JSON array. Note how the `null` value was silently converted
  14553. to a JSON array.,emplace_back}
  14554. @since version 2.0.8
  14555. */
  14556. template<class... Args>
  14557. void emplace_back(Args&& ... args)
  14558. {
  14559. // emplace_back only works for null objects or arrays
  14560. if (JSON_UNLIKELY(not(is_null() or is_array())))
  14561. {
  14562. JSON_THROW(type_error::create(311, "cannot use emplace_back() with " + std::string(type_name())));
  14563. }
  14564. // transform null object into an array
  14565. if (is_null())
  14566. {
  14567. m_type = value_t::array;
  14568. m_value = value_t::array;
  14569. assert_invariant();
  14570. }
  14571. // add element to array (perfect forwarding)
  14572. m_value.array->emplace_back(std::forward<Args>(args)...);
  14573. }
  14574. /*!
  14575. @brief add an object to an object if key does not exist
  14576. Inserts a new element into a JSON object constructed in-place with the
  14577. given @a args if there is no element with the key in the container. If the
  14578. function is called on a JSON null value, an empty object is created before
  14579. appending the value created from @a args.
  14580. @param[in] args arguments to forward to a constructor of @ref basic_json
  14581. @tparam Args compatible types to create a @ref basic_json object
  14582. @return a pair consisting of an iterator to the inserted element, or the
  14583. already-existing element if no insertion happened, and a bool
  14584. denoting whether the insertion took place.
  14585. @throw type_error.311 when called on a type other than JSON object or
  14586. null; example: `"cannot use emplace() with number"`
  14587. @complexity Logarithmic in the size of the container, O(log(`size()`)).
  14588. @liveexample{The example shows how `emplace()` can be used to add elements
  14589. to a JSON object. Note how the `null` value was silently converted to a
  14590. JSON object. Further note how no value is added if there was already one
  14591. value stored with the same key.,emplace}
  14592. @since version 2.0.8
  14593. */
  14594. template<class... Args>
  14595. std::pair<iterator, bool> emplace(Args&& ... args)
  14596. {
  14597. // emplace only works for null objects or arrays
  14598. if (JSON_UNLIKELY(not(is_null() or is_object())))
  14599. {
  14600. JSON_THROW(type_error::create(311, "cannot use emplace() with " + std::string(type_name())));
  14601. }
  14602. // transform null object into an object
  14603. if (is_null())
  14604. {
  14605. m_type = value_t::object;
  14606. m_value = value_t::object;
  14607. assert_invariant();
  14608. }
  14609. // add element to array (perfect forwarding)
  14610. auto res = m_value.object->emplace(std::forward<Args>(args)...);
  14611. // create result iterator and set iterator to the result of emplace
  14612. auto it = begin();
  14613. it.m_it.object_iterator = res.first;
  14614. // return pair of iterator and boolean
  14615. return {it, res.second};
  14616. }
  14617. /// Helper for insertion of an iterator
  14618. /// @note: This uses std::distance to support GCC 4.8,
  14619. /// see https://github.com/nlohmann/json/pull/1257
  14620. template<typename... Args>
  14621. iterator insert_iterator(const_iterator pos, Args&& ... args)
  14622. {
  14623. iterator result(this);
  14624. assert(m_value.array != nullptr);
  14625. auto insert_pos = std::distance(m_value.array->begin(), pos.m_it.array_iterator);
  14626. m_value.array->insert(pos.m_it.array_iterator, std::forward<Args>(args)...);
  14627. result.m_it.array_iterator = m_value.array->begin() + insert_pos;
  14628. // This could have been written as:
  14629. // result.m_it.array_iterator = m_value.array->insert(pos.m_it.array_iterator, cnt, val);
  14630. // but the return value of insert is missing in GCC 4.8, so it is written this way instead.
  14631. return result;
  14632. }
  14633. /*!
  14634. @brief inserts element
  14635. Inserts element @a val before iterator @a pos.
  14636. @param[in] pos iterator before which the content will be inserted; may be
  14637. the end() iterator
  14638. @param[in] val element to insert
  14639. @return iterator pointing to the inserted @a val.
  14640. @throw type_error.309 if called on JSON values other than arrays;
  14641. example: `"cannot use insert() with string"`
  14642. @throw invalid_iterator.202 if @a pos is not an iterator of *this;
  14643. example: `"iterator does not fit current value"`
  14644. @complexity Constant plus linear in the distance between @a pos and end of
  14645. the container.
  14646. @liveexample{The example shows how `insert()` is used.,insert}
  14647. @since version 1.0.0
  14648. */
  14649. iterator insert(const_iterator pos, const basic_json& val)
  14650. {
  14651. // insert only works for arrays
  14652. if (JSON_LIKELY(is_array()))
  14653. {
  14654. // check if iterator pos fits to this JSON value
  14655. if (JSON_UNLIKELY(pos.m_object != this))
  14656. {
  14657. JSON_THROW(invalid_iterator::create(202, "iterator does not fit current value"));
  14658. }
  14659. // insert to array and return iterator
  14660. return insert_iterator(pos, val);
  14661. }
  14662. JSON_THROW(type_error::create(309, "cannot use insert() with " + std::string(type_name())));
  14663. }
  14664. /*!
  14665. @brief inserts element
  14666. @copydoc insert(const_iterator, const basic_json&)
  14667. */
  14668. iterator insert(const_iterator pos, basic_json&& val)
  14669. {
  14670. return insert(pos, val);
  14671. }
  14672. /*!
  14673. @brief inserts elements
  14674. Inserts @a cnt copies of @a val before iterator @a pos.
  14675. @param[in] pos iterator before which the content will be inserted; may be
  14676. the end() iterator
  14677. @param[in] cnt number of copies of @a val to insert
  14678. @param[in] val element to insert
  14679. @return iterator pointing to the first element inserted, or @a pos if
  14680. `cnt==0`
  14681. @throw type_error.309 if called on JSON values other than arrays; example:
  14682. `"cannot use insert() with string"`
  14683. @throw invalid_iterator.202 if @a pos is not an iterator of *this;
  14684. example: `"iterator does not fit current value"`
  14685. @complexity Linear in @a cnt plus linear in the distance between @a pos
  14686. and end of the container.
  14687. @liveexample{The example shows how `insert()` is used.,insert__count}
  14688. @since version 1.0.0
  14689. */
  14690. iterator insert(const_iterator pos, size_type cnt, const basic_json& val)
  14691. {
  14692. // insert only works for arrays
  14693. if (JSON_LIKELY(is_array()))
  14694. {
  14695. // check if iterator pos fits to this JSON value
  14696. if (JSON_UNLIKELY(pos.m_object != this))
  14697. {
  14698. JSON_THROW(invalid_iterator::create(202, "iterator does not fit current value"));
  14699. }
  14700. // insert to array and return iterator
  14701. return insert_iterator(pos, cnt, val);
  14702. }
  14703. JSON_THROW(type_error::create(309, "cannot use insert() with " + std::string(type_name())));
  14704. }
  14705. /*!
  14706. @brief inserts elements
  14707. Inserts elements from range `[first, last)` before iterator @a pos.
  14708. @param[in] pos iterator before which the content will be inserted; may be
  14709. the end() iterator
  14710. @param[in] first begin of the range of elements to insert
  14711. @param[in] last end of the range of elements to insert
  14712. @throw type_error.309 if called on JSON values other than arrays; example:
  14713. `"cannot use insert() with string"`
  14714. @throw invalid_iterator.202 if @a pos is not an iterator of *this;
  14715. example: `"iterator does not fit current value"`
  14716. @throw invalid_iterator.210 if @a first and @a last do not belong to the
  14717. same JSON value; example: `"iterators do not fit"`
  14718. @throw invalid_iterator.211 if @a first or @a last are iterators into
  14719. container for which insert is called; example: `"passed iterators may not
  14720. belong to container"`
  14721. @return iterator pointing to the first element inserted, or @a pos if
  14722. `first==last`
  14723. @complexity Linear in `std::distance(first, last)` plus linear in the
  14724. distance between @a pos and end of the container.
  14725. @liveexample{The example shows how `insert()` is used.,insert__range}
  14726. @since version 1.0.0
  14727. */
  14728. iterator insert(const_iterator pos, const_iterator first, const_iterator last)
  14729. {
  14730. // insert only works for arrays
  14731. if (JSON_UNLIKELY(not is_array()))
  14732. {
  14733. JSON_THROW(type_error::create(309, "cannot use insert() with " + std::string(type_name())));
  14734. }
  14735. // check if iterator pos fits to this JSON value
  14736. if (JSON_UNLIKELY(pos.m_object != this))
  14737. {
  14738. JSON_THROW(invalid_iterator::create(202, "iterator does not fit current value"));
  14739. }
  14740. // check if range iterators belong to the same JSON object
  14741. if (JSON_UNLIKELY(first.m_object != last.m_object))
  14742. {
  14743. JSON_THROW(invalid_iterator::create(210, "iterators do not fit"));
  14744. }
  14745. if (JSON_UNLIKELY(first.m_object == this))
  14746. {
  14747. JSON_THROW(invalid_iterator::create(211, "passed iterators may not belong to container"));
  14748. }
  14749. // insert to array and return iterator
  14750. return insert_iterator(pos, first.m_it.array_iterator, last.m_it.array_iterator);
  14751. }
  14752. /*!
  14753. @brief inserts elements
  14754. Inserts elements from initializer list @a ilist before iterator @a pos.
  14755. @param[in] pos iterator before which the content will be inserted; may be
  14756. the end() iterator
  14757. @param[in] ilist initializer list to insert the values from
  14758. @throw type_error.309 if called on JSON values other than arrays; example:
  14759. `"cannot use insert() with string"`
  14760. @throw invalid_iterator.202 if @a pos is not an iterator of *this;
  14761. example: `"iterator does not fit current value"`
  14762. @return iterator pointing to the first element inserted, or @a pos if
  14763. `ilist` is empty
  14764. @complexity Linear in `ilist.size()` plus linear in the distance between
  14765. @a pos and end of the container.
  14766. @liveexample{The example shows how `insert()` is used.,insert__ilist}
  14767. @since version 1.0.0
  14768. */
  14769. iterator insert(const_iterator pos, initializer_list_t ilist)
  14770. {
  14771. // insert only works for arrays
  14772. if (JSON_UNLIKELY(not is_array()))
  14773. {
  14774. JSON_THROW(type_error::create(309, "cannot use insert() with " + std::string(type_name())));
  14775. }
  14776. // check if iterator pos fits to this JSON value
  14777. if (JSON_UNLIKELY(pos.m_object != this))
  14778. {
  14779. JSON_THROW(invalid_iterator::create(202, "iterator does not fit current value"));
  14780. }
  14781. // insert to array and return iterator
  14782. return insert_iterator(pos, ilist.begin(), ilist.end());
  14783. }
  14784. /*!
  14785. @brief inserts elements
  14786. Inserts elements from range `[first, last)`.
  14787. @param[in] first begin of the range of elements to insert
  14788. @param[in] last end of the range of elements to insert
  14789. @throw type_error.309 if called on JSON values other than objects; example:
  14790. `"cannot use insert() with string"`
  14791. @throw invalid_iterator.202 if iterator @a first or @a last does does not
  14792. point to an object; example: `"iterators first and last must point to
  14793. objects"`
  14794. @throw invalid_iterator.210 if @a first and @a last do not belong to the
  14795. same JSON value; example: `"iterators do not fit"`
  14796. @complexity Logarithmic: `O(N*log(size() + N))`, where `N` is the number
  14797. of elements to insert.
  14798. @liveexample{The example shows how `insert()` is used.,insert__range_object}
  14799. @since version 3.0.0
  14800. */
  14801. void insert(const_iterator first, const_iterator last)
  14802. {
  14803. // insert only works for objects
  14804. if (JSON_UNLIKELY(not is_object()))
  14805. {
  14806. JSON_THROW(type_error::create(309, "cannot use insert() with " + std::string(type_name())));
  14807. }
  14808. // check if range iterators belong to the same JSON object
  14809. if (JSON_UNLIKELY(first.m_object != last.m_object))
  14810. {
  14811. JSON_THROW(invalid_iterator::create(210, "iterators do not fit"));
  14812. }
  14813. // passed iterators must belong to objects
  14814. if (JSON_UNLIKELY(not first.m_object->is_object()))
  14815. {
  14816. JSON_THROW(invalid_iterator::create(202, "iterators first and last must point to objects"));
  14817. }
  14818. m_value.object->insert(first.m_it.object_iterator, last.m_it.object_iterator);
  14819. }
  14820. /*!
  14821. @brief updates a JSON object from another object, overwriting existing keys
  14822. Inserts all values from JSON object @a j and overwrites existing keys.
  14823. @param[in] j JSON object to read values from
  14824. @throw type_error.312 if called on JSON values other than objects; example:
  14825. `"cannot use update() with string"`
  14826. @complexity O(N*log(size() + N)), where N is the number of elements to
  14827. insert.
  14828. @liveexample{The example shows how `update()` is used.,update}
  14829. @sa https://docs.python.org/3.6/library/stdtypes.html#dict.update
  14830. @since version 3.0.0
  14831. */
  14832. void update(const_reference j)
  14833. {
  14834. // implicitly convert null value to an empty object
  14835. if (is_null())
  14836. {
  14837. m_type = value_t::object;
  14838. m_value.object = create<object_t>();
  14839. assert_invariant();
  14840. }
  14841. if (JSON_UNLIKELY(not is_object()))
  14842. {
  14843. JSON_THROW(type_error::create(312, "cannot use update() with " + std::string(type_name())));
  14844. }
  14845. if (JSON_UNLIKELY(not j.is_object()))
  14846. {
  14847. JSON_THROW(type_error::create(312, "cannot use update() with " + std::string(j.type_name())));
  14848. }
  14849. for (auto it = j.cbegin(); it != j.cend(); ++it)
  14850. {
  14851. m_value.object->operator[](it.key()) = it.value();
  14852. }
  14853. }
  14854. /*!
  14855. @brief updates a JSON object from another object, overwriting existing keys
  14856. Inserts all values from from range `[first, last)` and overwrites existing
  14857. keys.
  14858. @param[in] first begin of the range of elements to insert
  14859. @param[in] last end of the range of elements to insert
  14860. @throw type_error.312 if called on JSON values other than objects; example:
  14861. `"cannot use update() with string"`
  14862. @throw invalid_iterator.202 if iterator @a first or @a last does does not
  14863. point to an object; example: `"iterators first and last must point to
  14864. objects"`
  14865. @throw invalid_iterator.210 if @a first and @a last do not belong to the
  14866. same JSON value; example: `"iterators do not fit"`
  14867. @complexity O(N*log(size() + N)), where N is the number of elements to
  14868. insert.
  14869. @liveexample{The example shows how `update()` is used__range.,update}
  14870. @sa https://docs.python.org/3.6/library/stdtypes.html#dict.update
  14871. @since version 3.0.0
  14872. */
  14873. void update(const_iterator first, const_iterator last)
  14874. {
  14875. // implicitly convert null value to an empty object
  14876. if (is_null())
  14877. {
  14878. m_type = value_t::object;
  14879. m_value.object = create<object_t>();
  14880. assert_invariant();
  14881. }
  14882. if (JSON_UNLIKELY(not is_object()))
  14883. {
  14884. JSON_THROW(type_error::create(312, "cannot use update() with " + std::string(type_name())));
  14885. }
  14886. // check if range iterators belong to the same JSON object
  14887. if (JSON_UNLIKELY(first.m_object != last.m_object))
  14888. {
  14889. JSON_THROW(invalid_iterator::create(210, "iterators do not fit"));
  14890. }
  14891. // passed iterators must belong to objects
  14892. if (JSON_UNLIKELY(not first.m_object->is_object()
  14893. or not last.m_object->is_object()))
  14894. {
  14895. JSON_THROW(invalid_iterator::create(202, "iterators first and last must point to objects"));
  14896. }
  14897. for (auto it = first; it != last; ++it)
  14898. {
  14899. m_value.object->operator[](it.key()) = it.value();
  14900. }
  14901. }
  14902. /*!
  14903. @brief exchanges the values
  14904. Exchanges the contents of the JSON value with those of @a other. Does not
  14905. invoke any move, copy, or swap operations on individual elements. All
  14906. iterators and references remain valid. The past-the-end iterator is
  14907. invalidated.
  14908. @param[in,out] other JSON value to exchange the contents with
  14909. @complexity Constant.
  14910. @liveexample{The example below shows how JSON values can be swapped with
  14911. `swap()`.,swap__reference}
  14912. @since version 1.0.0
  14913. */
  14914. void swap(reference other) noexcept (
  14915. std::is_nothrow_move_constructible<value_t>::value and
  14916. std::is_nothrow_move_assignable<value_t>::value and
  14917. std::is_nothrow_move_constructible<json_value>::value and
  14918. std::is_nothrow_move_assignable<json_value>::value
  14919. )
  14920. {
  14921. std::swap(m_type, other.m_type);
  14922. std::swap(m_value, other.m_value);
  14923. assert_invariant();
  14924. }
  14925. /*!
  14926. @brief exchanges the values
  14927. Exchanges the contents of a JSON array with those of @a other. Does not
  14928. invoke any move, copy, or swap operations on individual elements. All
  14929. iterators and references remain valid. The past-the-end iterator is
  14930. invalidated.
  14931. @param[in,out] other array to exchange the contents with
  14932. @throw type_error.310 when JSON value is not an array; example: `"cannot
  14933. use swap() with string"`
  14934. @complexity Constant.
  14935. @liveexample{The example below shows how arrays can be swapped with
  14936. `swap()`.,swap__array_t}
  14937. @since version 1.0.0
  14938. */
  14939. void swap(array_t& other)
  14940. {
  14941. // swap only works for arrays
  14942. if (JSON_LIKELY(is_array()))
  14943. {
  14944. std::swap(*(m_value.array), other);
  14945. }
  14946. else
  14947. {
  14948. JSON_THROW(type_error::create(310, "cannot use swap() with " + std::string(type_name())));
  14949. }
  14950. }
  14951. /*!
  14952. @brief exchanges the values
  14953. Exchanges the contents of a JSON object with those of @a other. Does not
  14954. invoke any move, copy, or swap operations on individual elements. All
  14955. iterators and references remain valid. The past-the-end iterator is
  14956. invalidated.
  14957. @param[in,out] other object to exchange the contents with
  14958. @throw type_error.310 when JSON value is not an object; example:
  14959. `"cannot use swap() with string"`
  14960. @complexity Constant.
  14961. @liveexample{The example below shows how objects can be swapped with
  14962. `swap()`.,swap__object_t}
  14963. @since version 1.0.0
  14964. */
  14965. void swap(object_t& other)
  14966. {
  14967. // swap only works for objects
  14968. if (JSON_LIKELY(is_object()))
  14969. {
  14970. std::swap(*(m_value.object), other);
  14971. }
  14972. else
  14973. {
  14974. JSON_THROW(type_error::create(310, "cannot use swap() with " + std::string(type_name())));
  14975. }
  14976. }
  14977. /*!
  14978. @brief exchanges the values
  14979. Exchanges the contents of a JSON string with those of @a other. Does not
  14980. invoke any move, copy, or swap operations on individual elements. All
  14981. iterators and references remain valid. The past-the-end iterator is
  14982. invalidated.
  14983. @param[in,out] other string to exchange the contents with
  14984. @throw type_error.310 when JSON value is not a string; example: `"cannot
  14985. use swap() with boolean"`
  14986. @complexity Constant.
  14987. @liveexample{The example below shows how strings can be swapped with
  14988. `swap()`.,swap__string_t}
  14989. @since version 1.0.0
  14990. */
  14991. void swap(string_t& other)
  14992. {
  14993. // swap only works for strings
  14994. if (JSON_LIKELY(is_string()))
  14995. {
  14996. std::swap(*(m_value.string), other);
  14997. }
  14998. else
  14999. {
  15000. JSON_THROW(type_error::create(310, "cannot use swap() with " + std::string(type_name())));
  15001. }
  15002. }
  15003. /// @}
  15004. public:
  15005. //////////////////////////////////////////
  15006. // lexicographical comparison operators //
  15007. //////////////////////////////////////////
  15008. /// @name lexicographical comparison operators
  15009. /// @{
  15010. /*!
  15011. @brief comparison: equal
  15012. Compares two JSON values for equality according to the following rules:
  15013. - Two JSON values are equal if (1) they are from the same type and (2)
  15014. their stored values are the same according to their respective
  15015. `operator==`.
  15016. - Integer and floating-point numbers are automatically converted before
  15017. comparison. Note than two NaN values are always treated as unequal.
  15018. - Two JSON null values are equal.
  15019. @note Floating-point inside JSON values numbers are compared with
  15020. `json::number_float_t::operator==` which is `double::operator==` by
  15021. default. To compare floating-point while respecting an epsilon, an alternative
  15022. [comparison function](https://github.com/mariokonrad/marnav/blob/master/src/marnav/math/floatingpoint.hpp#L34-#L39)
  15023. could be used, for instance
  15024. @code {.cpp}
  15025. template<typename T, typename = typename std::enable_if<std::is_floating_point<T>::value, T>::type>
  15026. inline bool is_same(T a, T b, T epsilon = std::numeric_limits<T>::epsilon()) noexcept
  15027. {
  15028. return std::abs(a - b) <= epsilon;
  15029. }
  15030. @endcode
  15031. @note NaN values never compare equal to themselves or to other NaN values.
  15032. @param[in] lhs first JSON value to consider
  15033. @param[in] rhs second JSON value to consider
  15034. @return whether the values @a lhs and @a rhs are equal
  15035. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  15036. @complexity Linear.
  15037. @liveexample{The example demonstrates comparing several JSON
  15038. types.,operator__equal}
  15039. @since version 1.0.0
  15040. */
  15041. friend bool operator==(const_reference lhs, const_reference rhs) noexcept
  15042. {
  15043. const auto lhs_type = lhs.type();
  15044. const auto rhs_type = rhs.type();
  15045. if (lhs_type == rhs_type)
  15046. {
  15047. switch (lhs_type)
  15048. {
  15049. case value_t::array:
  15050. return (*lhs.m_value.array == *rhs.m_value.array);
  15051. case value_t::object:
  15052. return (*lhs.m_value.object == *rhs.m_value.object);
  15053. case value_t::null:
  15054. return true;
  15055. case value_t::string:
  15056. return (*lhs.m_value.string == *rhs.m_value.string);
  15057. case value_t::boolean:
  15058. return (lhs.m_value.boolean == rhs.m_value.boolean);
  15059. case value_t::number_integer:
  15060. return (lhs.m_value.number_integer == rhs.m_value.number_integer);
  15061. case value_t::number_unsigned:
  15062. return (lhs.m_value.number_unsigned == rhs.m_value.number_unsigned);
  15063. case value_t::number_float:
  15064. return (lhs.m_value.number_float == rhs.m_value.number_float);
  15065. default:
  15066. return false;
  15067. }
  15068. }
  15069. else if (lhs_type == value_t::number_integer and rhs_type == value_t::number_float)
  15070. {
  15071. return (static_cast<number_float_t>(lhs.m_value.number_integer) == rhs.m_value.number_float);
  15072. }
  15073. else if (lhs_type == value_t::number_float and rhs_type == value_t::number_integer)
  15074. {
  15075. return (lhs.m_value.number_float == static_cast<number_float_t>(rhs.m_value.number_integer));
  15076. }
  15077. else if (lhs_type == value_t::number_unsigned and rhs_type == value_t::number_float)
  15078. {
  15079. return (static_cast<number_float_t>(lhs.m_value.number_unsigned) == rhs.m_value.number_float);
  15080. }
  15081. else if (lhs_type == value_t::number_float and rhs_type == value_t::number_unsigned)
  15082. {
  15083. return (lhs.m_value.number_float == static_cast<number_float_t>(rhs.m_value.number_unsigned));
  15084. }
  15085. else if (lhs_type == value_t::number_unsigned and rhs_type == value_t::number_integer)
  15086. {
  15087. return (static_cast<number_integer_t>(lhs.m_value.number_unsigned) == rhs.m_value.number_integer);
  15088. }
  15089. else if (lhs_type == value_t::number_integer and rhs_type == value_t::number_unsigned)
  15090. {
  15091. return (lhs.m_value.number_integer == static_cast<number_integer_t>(rhs.m_value.number_unsigned));
  15092. }
  15093. return false;
  15094. }
  15095. /*!
  15096. @brief comparison: equal
  15097. @copydoc operator==(const_reference, const_reference)
  15098. */
  15099. template<typename ScalarType, typename std::enable_if<
  15100. std::is_scalar<ScalarType>::value, int>::type = 0>
  15101. friend bool operator==(const_reference lhs, const ScalarType rhs) noexcept
  15102. {
  15103. return (lhs == basic_json(rhs));
  15104. }
  15105. /*!
  15106. @brief comparison: equal
  15107. @copydoc operator==(const_reference, const_reference)
  15108. */
  15109. template<typename ScalarType, typename std::enable_if<
  15110. std::is_scalar<ScalarType>::value, int>::type = 0>
  15111. friend bool operator==(const ScalarType lhs, const_reference rhs) noexcept
  15112. {
  15113. return (basic_json(lhs) == rhs);
  15114. }
  15115. /*!
  15116. @brief comparison: not equal
  15117. Compares two JSON values for inequality by calculating `not (lhs == rhs)`.
  15118. @param[in] lhs first JSON value to consider
  15119. @param[in] rhs second JSON value to consider
  15120. @return whether the values @a lhs and @a rhs are not equal
  15121. @complexity Linear.
  15122. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  15123. @liveexample{The example demonstrates comparing several JSON
  15124. types.,operator__notequal}
  15125. @since version 1.0.0
  15126. */
  15127. friend bool operator!=(const_reference lhs, const_reference rhs) noexcept
  15128. {
  15129. return not (lhs == rhs);
  15130. }
  15131. /*!
  15132. @brief comparison: not equal
  15133. @copydoc operator!=(const_reference, const_reference)
  15134. */
  15135. template<typename ScalarType, typename std::enable_if<
  15136. std::is_scalar<ScalarType>::value, int>::type = 0>
  15137. friend bool operator!=(const_reference lhs, const ScalarType rhs) noexcept
  15138. {
  15139. return (lhs != basic_json(rhs));
  15140. }
  15141. /*!
  15142. @brief comparison: not equal
  15143. @copydoc operator!=(const_reference, const_reference)
  15144. */
  15145. template<typename ScalarType, typename std::enable_if<
  15146. std::is_scalar<ScalarType>::value, int>::type = 0>
  15147. friend bool operator!=(const ScalarType lhs, const_reference rhs) noexcept
  15148. {
  15149. return (basic_json(lhs) != rhs);
  15150. }
  15151. /*!
  15152. @brief comparison: less than
  15153. Compares whether one JSON value @a lhs is less than another JSON value @a
  15154. rhs according to the following rules:
  15155. - If @a lhs and @a rhs have the same type, the values are compared using
  15156. the default `<` operator.
  15157. - Integer and floating-point numbers are automatically converted before
  15158. comparison
  15159. - In case @a lhs and @a rhs have different types, the values are ignored
  15160. and the order of the types is considered, see
  15161. @ref operator<(const value_t, const value_t).
  15162. @param[in] lhs first JSON value to consider
  15163. @param[in] rhs second JSON value to consider
  15164. @return whether @a lhs is less than @a rhs
  15165. @complexity Linear.
  15166. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  15167. @liveexample{The example demonstrates comparing several JSON
  15168. types.,operator__less}
  15169. @since version 1.0.0
  15170. */
  15171. friend bool operator<(const_reference lhs, const_reference rhs) noexcept
  15172. {
  15173. const auto lhs_type = lhs.type();
  15174. const auto rhs_type = rhs.type();
  15175. if (lhs_type == rhs_type)
  15176. {
  15177. switch (lhs_type)
  15178. {
  15179. case value_t::array:
  15180. return (*lhs.m_value.array) < (*rhs.m_value.array);
  15181. case value_t::object:
  15182. return *lhs.m_value.object < *rhs.m_value.object;
  15183. case value_t::null:
  15184. return false;
  15185. case value_t::string:
  15186. return *lhs.m_value.string < *rhs.m_value.string;
  15187. case value_t::boolean:
  15188. return lhs.m_value.boolean < rhs.m_value.boolean;
  15189. case value_t::number_integer:
  15190. return lhs.m_value.number_integer < rhs.m_value.number_integer;
  15191. case value_t::number_unsigned:
  15192. return lhs.m_value.number_unsigned < rhs.m_value.number_unsigned;
  15193. case value_t::number_float:
  15194. return lhs.m_value.number_float < rhs.m_value.number_float;
  15195. default:
  15196. return false;
  15197. }
  15198. }
  15199. else if (lhs_type == value_t::number_integer and rhs_type == value_t::number_float)
  15200. {
  15201. return static_cast<number_float_t>(lhs.m_value.number_integer) < rhs.m_value.number_float;
  15202. }
  15203. else if (lhs_type == value_t::number_float and rhs_type == value_t::number_integer)
  15204. {
  15205. return lhs.m_value.number_float < static_cast<number_float_t>(rhs.m_value.number_integer);
  15206. }
  15207. else if (lhs_type == value_t::number_unsigned and rhs_type == value_t::number_float)
  15208. {
  15209. return static_cast<number_float_t>(lhs.m_value.number_unsigned) < rhs.m_value.number_float;
  15210. }
  15211. else if (lhs_type == value_t::number_float and rhs_type == value_t::number_unsigned)
  15212. {
  15213. return lhs.m_value.number_float < static_cast<number_float_t>(rhs.m_value.number_unsigned);
  15214. }
  15215. else if (lhs_type == value_t::number_integer and rhs_type == value_t::number_unsigned)
  15216. {
  15217. return lhs.m_value.number_integer < static_cast<number_integer_t>(rhs.m_value.number_unsigned);
  15218. }
  15219. else if (lhs_type == value_t::number_unsigned and rhs_type == value_t::number_integer)
  15220. {
  15221. return static_cast<number_integer_t>(lhs.m_value.number_unsigned) < rhs.m_value.number_integer;
  15222. }
  15223. // We only reach this line if we cannot compare values. In that case,
  15224. // we compare types. Note we have to call the operator explicitly,
  15225. // because MSVC has problems otherwise.
  15226. return operator<(lhs_type, rhs_type);
  15227. }
  15228. /*!
  15229. @brief comparison: less than
  15230. @copydoc operator<(const_reference, const_reference)
  15231. */
  15232. template<typename ScalarType, typename std::enable_if<
  15233. std::is_scalar<ScalarType>::value, int>::type = 0>
  15234. friend bool operator<(const_reference lhs, const ScalarType rhs) noexcept
  15235. {
  15236. return (lhs < basic_json(rhs));
  15237. }
  15238. /*!
  15239. @brief comparison: less than
  15240. @copydoc operator<(const_reference, const_reference)
  15241. */
  15242. template<typename ScalarType, typename std::enable_if<
  15243. std::is_scalar<ScalarType>::value, int>::type = 0>
  15244. friend bool operator<(const ScalarType lhs, const_reference rhs) noexcept
  15245. {
  15246. return (basic_json(lhs) < rhs);
  15247. }
  15248. /*!
  15249. @brief comparison: less than or equal
  15250. Compares whether one JSON value @a lhs is less than or equal to another
  15251. JSON value by calculating `not (rhs < lhs)`.
  15252. @param[in] lhs first JSON value to consider
  15253. @param[in] rhs second JSON value to consider
  15254. @return whether @a lhs is less than or equal to @a rhs
  15255. @complexity Linear.
  15256. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  15257. @liveexample{The example demonstrates comparing several JSON
  15258. types.,operator__greater}
  15259. @since version 1.0.0
  15260. */
  15261. friend bool operator<=(const_reference lhs, const_reference rhs) noexcept
  15262. {
  15263. return not (rhs < lhs);
  15264. }
  15265. /*!
  15266. @brief comparison: less than or equal
  15267. @copydoc operator<=(const_reference, const_reference)
  15268. */
  15269. template<typename ScalarType, typename std::enable_if<
  15270. std::is_scalar<ScalarType>::value, int>::type = 0>
  15271. friend bool operator<=(const_reference lhs, const ScalarType rhs) noexcept
  15272. {
  15273. return (lhs <= basic_json(rhs));
  15274. }
  15275. /*!
  15276. @brief comparison: less than or equal
  15277. @copydoc operator<=(const_reference, const_reference)
  15278. */
  15279. template<typename ScalarType, typename std::enable_if<
  15280. std::is_scalar<ScalarType>::value, int>::type = 0>
  15281. friend bool operator<=(const ScalarType lhs, const_reference rhs) noexcept
  15282. {
  15283. return (basic_json(lhs) <= rhs);
  15284. }
  15285. /*!
  15286. @brief comparison: greater than
  15287. Compares whether one JSON value @a lhs is greater than another
  15288. JSON value by calculating `not (lhs <= rhs)`.
  15289. @param[in] lhs first JSON value to consider
  15290. @param[in] rhs second JSON value to consider
  15291. @return whether @a lhs is greater than to @a rhs
  15292. @complexity Linear.
  15293. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  15294. @liveexample{The example demonstrates comparing several JSON
  15295. types.,operator__lessequal}
  15296. @since version 1.0.0
  15297. */
  15298. friend bool operator>(const_reference lhs, const_reference rhs) noexcept
  15299. {
  15300. return not (lhs <= rhs);
  15301. }
  15302. /*!
  15303. @brief comparison: greater than
  15304. @copydoc operator>(const_reference, const_reference)
  15305. */
  15306. template<typename ScalarType, typename std::enable_if<
  15307. std::is_scalar<ScalarType>::value, int>::type = 0>
  15308. friend bool operator>(const_reference lhs, const ScalarType rhs) noexcept
  15309. {
  15310. return (lhs > basic_json(rhs));
  15311. }
  15312. /*!
  15313. @brief comparison: greater than
  15314. @copydoc operator>(const_reference, const_reference)
  15315. */
  15316. template<typename ScalarType, typename std::enable_if<
  15317. std::is_scalar<ScalarType>::value, int>::type = 0>
  15318. friend bool operator>(const ScalarType lhs, const_reference rhs) noexcept
  15319. {
  15320. return (basic_json(lhs) > rhs);
  15321. }
  15322. /*!
  15323. @brief comparison: greater than or equal
  15324. Compares whether one JSON value @a lhs is greater than or equal to another
  15325. JSON value by calculating `not (lhs < rhs)`.
  15326. @param[in] lhs first JSON value to consider
  15327. @param[in] rhs second JSON value to consider
  15328. @return whether @a lhs is greater than or equal to @a rhs
  15329. @complexity Linear.
  15330. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  15331. @liveexample{The example demonstrates comparing several JSON
  15332. types.,operator__greaterequal}
  15333. @since version 1.0.0
  15334. */
  15335. friend bool operator>=(const_reference lhs, const_reference rhs) noexcept
  15336. {
  15337. return not (lhs < rhs);
  15338. }
  15339. /*!
  15340. @brief comparison: greater than or equal
  15341. @copydoc operator>=(const_reference, const_reference)
  15342. */
  15343. template<typename ScalarType, typename std::enable_if<
  15344. std::is_scalar<ScalarType>::value, int>::type = 0>
  15345. friend bool operator>=(const_reference lhs, const ScalarType rhs) noexcept
  15346. {
  15347. return (lhs >= basic_json(rhs));
  15348. }
  15349. /*!
  15350. @brief comparison: greater than or equal
  15351. @copydoc operator>=(const_reference, const_reference)
  15352. */
  15353. template<typename ScalarType, typename std::enable_if<
  15354. std::is_scalar<ScalarType>::value, int>::type = 0>
  15355. friend bool operator>=(const ScalarType lhs, const_reference rhs) noexcept
  15356. {
  15357. return (basic_json(lhs) >= rhs);
  15358. }
  15359. /// @}
  15360. ///////////////////
  15361. // serialization //
  15362. ///////////////////
  15363. /// @name serialization
  15364. /// @{
  15365. /*!
  15366. @brief serialize to stream
  15367. Serialize the given JSON value @a j to the output stream @a o. The JSON
  15368. value will be serialized using the @ref dump member function.
  15369. - The indentation of the output can be controlled with the member variable
  15370. `width` of the output stream @a o. For instance, using the manipulator
  15371. `std::setw(4)` on @a o sets the indentation level to `4` and the
  15372. serialization result is the same as calling `dump(4)`.
  15373. - The indentation character can be controlled with the member variable
  15374. `fill` of the output stream @a o. For instance, the manipulator
  15375. `std::setfill('\\t')` sets indentation to use a tab character rather than
  15376. the default space character.
  15377. @param[in,out] o stream to serialize to
  15378. @param[in] j JSON value to serialize
  15379. @return the stream @a o
  15380. @throw type_error.316 if a string stored inside the JSON value is not
  15381. UTF-8 encoded
  15382. @complexity Linear.
  15383. @liveexample{The example below shows the serialization with different
  15384. parameters to `width` to adjust the indentation level.,operator_serialize}
  15385. @since version 1.0.0; indentation character added in version 3.0.0
  15386. */
  15387. friend std::ostream& operator<<(std::ostream& o, const basic_json& j)
  15388. {
  15389. // read width member and use it as indentation parameter if nonzero
  15390. const bool pretty_print = (o.width() > 0);
  15391. const auto indentation = (pretty_print ? o.width() : 0);
  15392. // reset width to 0 for subsequent calls to this stream
  15393. o.width(0);
  15394. // do the actual serialization
  15395. serializer s(detail::output_adapter<char>(o), o.fill());
  15396. s.dump(j, pretty_print, false, static_cast<unsigned int>(indentation));
  15397. return o;
  15398. }
  15399. /*!
  15400. @brief serialize to stream
  15401. @deprecated This stream operator is deprecated and will be removed in
  15402. future 4.0.0 of the library. Please use
  15403. @ref operator<<(std::ostream&, const basic_json&)
  15404. instead; that is, replace calls like `j >> o;` with `o << j;`.
  15405. @since version 1.0.0; deprecated since version 3.0.0
  15406. */
  15407. JSON_DEPRECATED
  15408. friend std::ostream& operator>>(const basic_json& j, std::ostream& o)
  15409. {
  15410. return o << j;
  15411. }
  15412. /// @}
  15413. /////////////////////
  15414. // deserialization //
  15415. /////////////////////
  15416. /// @name deserialization
  15417. /// @{
  15418. /*!
  15419. @brief deserialize from a compatible input
  15420. This function reads from a compatible input. Examples are:
  15421. - an array of 1-byte values
  15422. - strings with character/literal type with size of 1 byte
  15423. - input streams
  15424. - container with contiguous storage of 1-byte values. Compatible container
  15425. types include `std::vector`, `std::string`, `std::array`,
  15426. `std::valarray`, and `std::initializer_list`. Furthermore, C-style
  15427. arrays can be used with `std::begin()`/`std::end()`. User-defined
  15428. containers can be used as long as they implement random-access iterators
  15429. and a contiguous storage.
  15430. @pre Each element of the container has a size of 1 byte. Violating this
  15431. precondition yields undefined behavior. **This precondition is enforced
  15432. with a static assertion.**
  15433. @pre The container storage is contiguous. Violating this precondition
  15434. yields undefined behavior. **This precondition is enforced with an
  15435. assertion.**
  15436. @pre Each element of the container has a size of 1 byte. Violating this
  15437. precondition yields undefined behavior. **This precondition is enforced
  15438. with a static assertion.**
  15439. @warning There is no way to enforce all preconditions at compile-time. If
  15440. the function is called with a noncompliant container and with
  15441. assertions switched off, the behavior is undefined and will most
  15442. likely yield segmentation violation.
  15443. @param[in] i input to read from
  15444. @param[in] cb a parser callback function of type @ref parser_callback_t
  15445. which is used to control the deserialization by filtering unwanted values
  15446. (optional)
  15447. @param[in] allow_exceptions whether to throw exceptions in case of a
  15448. parse error (optional, true by default)
  15449. @return result of the deserialization
  15450. @throw parse_error.101 if a parse error occurs; example: `""unexpected end
  15451. of input; expected string literal""`
  15452. @throw parse_error.102 if to_unicode fails or surrogate error
  15453. @throw parse_error.103 if to_unicode fails
  15454. @complexity Linear in the length of the input. The parser is a predictive
  15455. LL(1) parser. The complexity can be higher if the parser callback function
  15456. @a cb has a super-linear complexity.
  15457. @note A UTF-8 byte order mark is silently ignored.
  15458. @liveexample{The example below demonstrates the `parse()` function reading
  15459. from an array.,parse__array__parser_callback_t}
  15460. @liveexample{The example below demonstrates the `parse()` function with
  15461. and without callback function.,parse__string__parser_callback_t}
  15462. @liveexample{The example below demonstrates the `parse()` function with
  15463. and without callback function.,parse__istream__parser_callback_t}
  15464. @liveexample{The example below demonstrates the `parse()` function reading
  15465. from a contiguous container.,parse__contiguouscontainer__parser_callback_t}
  15466. @since version 2.0.3 (contiguous containers)
  15467. */
  15468. static basic_json parse(detail::input_adapter&& i,
  15469. const parser_callback_t cb = nullptr,
  15470. const bool allow_exceptions = true)
  15471. {
  15472. basic_json result;
  15473. parser(i, cb, allow_exceptions).parse(true, result);
  15474. return result;
  15475. }
  15476. static bool accept(detail::input_adapter&& i)
  15477. {
  15478. return parser(i).accept(true);
  15479. }
  15480. /*!
  15481. @brief generate SAX events
  15482. The SAX event lister must follow the interface of @ref json_sax.
  15483. This function reads from a compatible input. Examples are:
  15484. - an array of 1-byte values
  15485. - strings with character/literal type with size of 1 byte
  15486. - input streams
  15487. - container with contiguous storage of 1-byte values. Compatible container
  15488. types include `std::vector`, `std::string`, `std::array`,
  15489. `std::valarray`, and `std::initializer_list`. Furthermore, C-style
  15490. arrays can be used with `std::begin()`/`std::end()`. User-defined
  15491. containers can be used as long as they implement random-access iterators
  15492. and a contiguous storage.
  15493. @pre Each element of the container has a size of 1 byte. Violating this
  15494. precondition yields undefined behavior. **This precondition is enforced
  15495. with a static assertion.**
  15496. @pre The container storage is contiguous. Violating this precondition
  15497. yields undefined behavior. **This precondition is enforced with an
  15498. assertion.**
  15499. @pre Each element of the container has a size of 1 byte. Violating this
  15500. precondition yields undefined behavior. **This precondition is enforced
  15501. with a static assertion.**
  15502. @warning There is no way to enforce all preconditions at compile-time. If
  15503. the function is called with a noncompliant container and with
  15504. assertions switched off, the behavior is undefined and will most
  15505. likely yield segmentation violation.
  15506. @param[in] i input to read from
  15507. @param[in,out] sax SAX event listener
  15508. @param[in] format the format to parse (JSON, CBOR, MessagePack, or UBJSON)
  15509. @param[in] strict whether the input has to be consumed completely
  15510. @return return value of the last processed SAX event
  15511. @throw parse_error.101 if a parse error occurs; example: `""unexpected end
  15512. of input; expected string literal""`
  15513. @throw parse_error.102 if to_unicode fails or surrogate error
  15514. @throw parse_error.103 if to_unicode fails
  15515. @complexity Linear in the length of the input. The parser is a predictive
  15516. LL(1) parser. The complexity can be higher if the SAX consumer @a sax has
  15517. a super-linear complexity.
  15518. @note A UTF-8 byte order mark is silently ignored.
  15519. @liveexample{The example below demonstrates the `sax_parse()` function
  15520. reading from string and processing the events with a user-defined SAX
  15521. event consumer.,sax_parse}
  15522. @since version 3.2.0
  15523. */
  15524. template <typename SAX>
  15525. static bool sax_parse(detail::input_adapter&& i, SAX* sax,
  15526. input_format_t format = input_format_t::json,
  15527. const bool strict = true)
  15528. {
  15529. assert(sax);
  15530. switch (format)
  15531. {
  15532. case input_format_t::json:
  15533. return parser(std::move(i)).sax_parse(sax, strict);
  15534. default:
  15535. return detail::binary_reader<basic_json, SAX>(std::move(i)).sax_parse(format, sax, strict);
  15536. }
  15537. }
  15538. /*!
  15539. @brief deserialize from an iterator range with contiguous storage
  15540. This function reads from an iterator range of a container with contiguous
  15541. storage of 1-byte values. Compatible container types include
  15542. `std::vector`, `std::string`, `std::array`, `std::valarray`, and
  15543. `std::initializer_list`. Furthermore, C-style arrays can be used with
  15544. `std::begin()`/`std::end()`. User-defined containers can be used as long
  15545. as they implement random-access iterators and a contiguous storage.
  15546. @pre The iterator range is contiguous. Violating this precondition yields
  15547. undefined behavior. **This precondition is enforced with an assertion.**
  15548. @pre Each element in the range has a size of 1 byte. Violating this
  15549. precondition yields undefined behavior. **This precondition is enforced
  15550. with a static assertion.**
  15551. @warning There is no way to enforce all preconditions at compile-time. If
  15552. the function is called with noncompliant iterators and with
  15553. assertions switched off, the behavior is undefined and will most
  15554. likely yield segmentation violation.
  15555. @tparam IteratorType iterator of container with contiguous storage
  15556. @param[in] first begin of the range to parse (included)
  15557. @param[in] last end of the range to parse (excluded)
  15558. @param[in] cb a parser callback function of type @ref parser_callback_t
  15559. which is used to control the deserialization by filtering unwanted values
  15560. (optional)
  15561. @param[in] allow_exceptions whether to throw exceptions in case of a
  15562. parse error (optional, true by default)
  15563. @return result of the deserialization
  15564. @throw parse_error.101 in case of an unexpected token
  15565. @throw parse_error.102 if to_unicode fails or surrogate error
  15566. @throw parse_error.103 if to_unicode fails
  15567. @complexity Linear in the length of the input. The parser is a predictive
  15568. LL(1) parser. The complexity can be higher if the parser callback function
  15569. @a cb has a super-linear complexity.
  15570. @note A UTF-8 byte order mark is silently ignored.
  15571. @liveexample{The example below demonstrates the `parse()` function reading
  15572. from an iterator range.,parse__iteratortype__parser_callback_t}
  15573. @since version 2.0.3
  15574. */
  15575. template<class IteratorType, typename std::enable_if<
  15576. std::is_base_of<
  15577. std::random_access_iterator_tag,
  15578. typename std::iterator_traits<IteratorType>::iterator_category>::value, int>::type = 0>
  15579. static basic_json parse(IteratorType first, IteratorType last,
  15580. const parser_callback_t cb = nullptr,
  15581. const bool allow_exceptions = true)
  15582. {
  15583. basic_json result;
  15584. parser(detail::input_adapter(first, last), cb, allow_exceptions).parse(true, result);
  15585. return result;
  15586. }
  15587. template<class IteratorType, typename std::enable_if<
  15588. std::is_base_of<
  15589. std::random_access_iterator_tag,
  15590. typename std::iterator_traits<IteratorType>::iterator_category>::value, int>::type = 0>
  15591. static bool accept(IteratorType first, IteratorType last)
  15592. {
  15593. return parser(detail::input_adapter(first, last)).accept(true);
  15594. }
  15595. template<class IteratorType, class SAX, typename std::enable_if<
  15596. std::is_base_of<
  15597. std::random_access_iterator_tag,
  15598. typename std::iterator_traits<IteratorType>::iterator_category>::value, int>::type = 0>
  15599. static bool sax_parse(IteratorType first, IteratorType last, SAX* sax)
  15600. {
  15601. return parser(detail::input_adapter(first, last)).sax_parse(sax);
  15602. }
  15603. /*!
  15604. @brief deserialize from stream
  15605. @deprecated This stream operator is deprecated and will be removed in
  15606. version 4.0.0 of the library. Please use
  15607. @ref operator>>(std::istream&, basic_json&)
  15608. instead; that is, replace calls like `j << i;` with `i >> j;`.
  15609. @since version 1.0.0; deprecated since version 3.0.0
  15610. */
  15611. JSON_DEPRECATED
  15612. friend std::istream& operator<<(basic_json& j, std::istream& i)
  15613. {
  15614. return operator>>(i, j);
  15615. }
  15616. /*!
  15617. @brief deserialize from stream
  15618. Deserializes an input stream to a JSON value.
  15619. @param[in,out] i input stream to read a serialized JSON value from
  15620. @param[in,out] j JSON value to write the deserialized input to
  15621. @throw parse_error.101 in case of an unexpected token
  15622. @throw parse_error.102 if to_unicode fails or surrogate error
  15623. @throw parse_error.103 if to_unicode fails
  15624. @complexity Linear in the length of the input. The parser is a predictive
  15625. LL(1) parser.
  15626. @note A UTF-8 byte order mark is silently ignored.
  15627. @liveexample{The example below shows how a JSON value is constructed by
  15628. reading a serialization from a stream.,operator_deserialize}
  15629. @sa parse(std::istream&, const parser_callback_t) for a variant with a
  15630. parser callback function to filter values while parsing
  15631. @since version 1.0.0
  15632. */
  15633. friend std::istream& operator>>(std::istream& i, basic_json& j)
  15634. {
  15635. parser(detail::input_adapter(i)).parse(false, j);
  15636. return i;
  15637. }
  15638. /// @}
  15639. ///////////////////////////
  15640. // convenience functions //
  15641. ///////////////////////////
  15642. /*!
  15643. @brief return the type as string
  15644. Returns the type name as string to be used in error messages - usually to
  15645. indicate that a function was called on a wrong JSON type.
  15646. @return a string representation of a the @a m_type member:
  15647. Value type | return value
  15648. ----------- | -------------
  15649. null | `"null"`
  15650. boolean | `"boolean"`
  15651. string | `"string"`
  15652. number | `"number"` (for all number types)
  15653. object | `"object"`
  15654. array | `"array"`
  15655. discarded | `"discarded"`
  15656. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  15657. @complexity Constant.
  15658. @liveexample{The following code exemplifies `type_name()` for all JSON
  15659. types.,type_name}
  15660. @sa @ref type() -- return the type of the JSON value
  15661. @sa @ref operator value_t() -- return the type of the JSON value (implicit)
  15662. @since version 1.0.0, public since 2.1.0, `const char*` and `noexcept`
  15663. since 3.0.0
  15664. */
  15665. const char* type_name() const noexcept
  15666. {
  15667. {
  15668. switch (m_type)
  15669. {
  15670. case value_t::null:
  15671. return "null";
  15672. case value_t::object:
  15673. return "object";
  15674. case value_t::array:
  15675. return "array";
  15676. case value_t::string:
  15677. return "string";
  15678. case value_t::boolean:
  15679. return "boolean";
  15680. case value_t::discarded:
  15681. return "discarded";
  15682. default:
  15683. return "number";
  15684. }
  15685. }
  15686. }
  15687. private:
  15688. //////////////////////
  15689. // member variables //
  15690. //////////////////////
  15691. /// the type of the current element
  15692. value_t m_type = value_t::null;
  15693. /// the value of the current element
  15694. json_value m_value = {};
  15695. //////////////////////////////////////////
  15696. // binary serialization/deserialization //
  15697. //////////////////////////////////////////
  15698. /// @name binary serialization/deserialization support
  15699. /// @{
  15700. public:
  15701. /*!
  15702. @brief create a CBOR serialization of a given JSON value
  15703. Serializes a given JSON value @a j to a byte vector using the CBOR (Concise
  15704. Binary Object Representation) serialization format. CBOR is a binary
  15705. serialization format which aims to be more compact than JSON itself, yet
  15706. more efficient to parse.
  15707. The library uses the following mapping from JSON values types to
  15708. CBOR types according to the CBOR specification (RFC 7049):
  15709. JSON value type | value/range | CBOR type | first byte
  15710. --------------- | ------------------------------------------ | ---------------------------------- | ---------------
  15711. null | `null` | Null | 0xF6
  15712. boolean | `true` | True | 0xF5
  15713. boolean | `false` | False | 0xF4
  15714. number_integer | -9223372036854775808..-2147483649 | Negative integer (8 bytes follow) | 0x3B
  15715. number_integer | -2147483648..-32769 | Negative integer (4 bytes follow) | 0x3A
  15716. number_integer | -32768..-129 | Negative integer (2 bytes follow) | 0x39
  15717. number_integer | -128..-25 | Negative integer (1 byte follow) | 0x38
  15718. number_integer | -24..-1 | Negative integer | 0x20..0x37
  15719. number_integer | 0..23 | Integer | 0x00..0x17
  15720. number_integer | 24..255 | Unsigned integer (1 byte follow) | 0x18
  15721. number_integer | 256..65535 | Unsigned integer (2 bytes follow) | 0x19
  15722. number_integer | 65536..4294967295 | Unsigned integer (4 bytes follow) | 0x1A
  15723. number_integer | 4294967296..18446744073709551615 | Unsigned integer (8 bytes follow) | 0x1B
  15724. number_unsigned | 0..23 | Integer | 0x00..0x17
  15725. number_unsigned | 24..255 | Unsigned integer (1 byte follow) | 0x18
  15726. number_unsigned | 256..65535 | Unsigned integer (2 bytes follow) | 0x19
  15727. number_unsigned | 65536..4294967295 | Unsigned integer (4 bytes follow) | 0x1A
  15728. number_unsigned | 4294967296..18446744073709551615 | Unsigned integer (8 bytes follow) | 0x1B
  15729. number_float | *any value* | Double-Precision Float | 0xFB
  15730. string | *length*: 0..23 | UTF-8 string | 0x60..0x77
  15731. string | *length*: 23..255 | UTF-8 string (1 byte follow) | 0x78
  15732. string | *length*: 256..65535 | UTF-8 string (2 bytes follow) | 0x79
  15733. string | *length*: 65536..4294967295 | UTF-8 string (4 bytes follow) | 0x7A
  15734. string | *length*: 4294967296..18446744073709551615 | UTF-8 string (8 bytes follow) | 0x7B
  15735. array | *size*: 0..23 | array | 0x80..0x97
  15736. array | *size*: 23..255 | array (1 byte follow) | 0x98
  15737. array | *size*: 256..65535 | array (2 bytes follow) | 0x99
  15738. array | *size*: 65536..4294967295 | array (4 bytes follow) | 0x9A
  15739. array | *size*: 4294967296..18446744073709551615 | array (8 bytes follow) | 0x9B
  15740. object | *size*: 0..23 | map | 0xA0..0xB7
  15741. object | *size*: 23..255 | map (1 byte follow) | 0xB8
  15742. object | *size*: 256..65535 | map (2 bytes follow) | 0xB9
  15743. object | *size*: 65536..4294967295 | map (4 bytes follow) | 0xBA
  15744. object | *size*: 4294967296..18446744073709551615 | map (8 bytes follow) | 0xBB
  15745. @note The mapping is **complete** in the sense that any JSON value type
  15746. can be converted to a CBOR value.
  15747. @note If NaN or Infinity are stored inside a JSON number, they are
  15748. serialized properly. This behavior differs from the @ref dump()
  15749. function which serializes NaN or Infinity to `null`.
  15750. @note The following CBOR types are not used in the conversion:
  15751. - byte strings (0x40..0x5F)
  15752. - UTF-8 strings terminated by "break" (0x7F)
  15753. - arrays terminated by "break" (0x9F)
  15754. - maps terminated by "break" (0xBF)
  15755. - date/time (0xC0..0xC1)
  15756. - bignum (0xC2..0xC3)
  15757. - decimal fraction (0xC4)
  15758. - bigfloat (0xC5)
  15759. - tagged items (0xC6..0xD4, 0xD8..0xDB)
  15760. - expected conversions (0xD5..0xD7)
  15761. - simple values (0xE0..0xF3, 0xF8)
  15762. - undefined (0xF7)
  15763. - half and single-precision floats (0xF9-0xFA)
  15764. - break (0xFF)
  15765. @param[in] j JSON value to serialize
  15766. @return MessagePack serialization as byte vector
  15767. @complexity Linear in the size of the JSON value @a j.
  15768. @liveexample{The example shows the serialization of a JSON value to a byte
  15769. vector in CBOR format.,to_cbor}
  15770. @sa http://cbor.io
  15771. @sa @ref from_cbor(detail::input_adapter&&, const bool, const bool) for the
  15772. analogous deserialization
  15773. @sa @ref to_msgpack(const basic_json&) for the related MessagePack format
  15774. @sa @ref to_ubjson(const basic_json&, const bool, const bool) for the
  15775. related UBJSON format
  15776. @since version 2.0.9
  15777. */
  15778. static std::vector<uint8_t> to_cbor(const basic_json& j)
  15779. {
  15780. std::vector<uint8_t> result;
  15781. to_cbor(j, result);
  15782. return result;
  15783. }
  15784. static void to_cbor(const basic_json& j, detail::output_adapter<uint8_t> o)
  15785. {
  15786. binary_writer<uint8_t>(o).write_cbor(j);
  15787. }
  15788. static void to_cbor(const basic_json& j, detail::output_adapter<char> o)
  15789. {
  15790. binary_writer<char>(o).write_cbor(j);
  15791. }
  15792. /*!
  15793. @brief create a MessagePack serialization of a given JSON value
  15794. Serializes a given JSON value @a j to a byte vector using the MessagePack
  15795. serialization format. MessagePack is a binary serialization format which
  15796. aims to be more compact than JSON itself, yet more efficient to parse.
  15797. The library uses the following mapping from JSON values types to
  15798. MessagePack types according to the MessagePack specification:
  15799. JSON value type | value/range | MessagePack type | first byte
  15800. --------------- | --------------------------------- | ---------------- | ----------
  15801. null | `null` | nil | 0xC0
  15802. boolean | `true` | true | 0xC3
  15803. boolean | `false` | false | 0xC2
  15804. number_integer | -9223372036854775808..-2147483649 | int64 | 0xD3
  15805. number_integer | -2147483648..-32769 | int32 | 0xD2
  15806. number_integer | -32768..-129 | int16 | 0xD1
  15807. number_integer | -128..-33 | int8 | 0xD0
  15808. number_integer | -32..-1 | negative fixint | 0xE0..0xFF
  15809. number_integer | 0..127 | positive fixint | 0x00..0x7F
  15810. number_integer | 128..255 | uint 8 | 0xCC
  15811. number_integer | 256..65535 | uint 16 | 0xCD
  15812. number_integer | 65536..4294967295 | uint 32 | 0xCE
  15813. number_integer | 4294967296..18446744073709551615 | uint 64 | 0xCF
  15814. number_unsigned | 0..127 | positive fixint | 0x00..0x7F
  15815. number_unsigned | 128..255 | uint 8 | 0xCC
  15816. number_unsigned | 256..65535 | uint 16 | 0xCD
  15817. number_unsigned | 65536..4294967295 | uint 32 | 0xCE
  15818. number_unsigned | 4294967296..18446744073709551615 | uint 64 | 0xCF
  15819. number_float | *any value* | float 64 | 0xCB
  15820. string | *length*: 0..31 | fixstr | 0xA0..0xBF
  15821. string | *length*: 32..255 | str 8 | 0xD9
  15822. string | *length*: 256..65535 | str 16 | 0xDA
  15823. string | *length*: 65536..4294967295 | str 32 | 0xDB
  15824. array | *size*: 0..15 | fixarray | 0x90..0x9F
  15825. array | *size*: 16..65535 | array 16 | 0xDC
  15826. array | *size*: 65536..4294967295 | array 32 | 0xDD
  15827. object | *size*: 0..15 | fix map | 0x80..0x8F
  15828. object | *size*: 16..65535 | map 16 | 0xDE
  15829. object | *size*: 65536..4294967295 | map 32 | 0xDF
  15830. @note The mapping is **complete** in the sense that any JSON value type
  15831. can be converted to a MessagePack value.
  15832. @note The following values can **not** be converted to a MessagePack value:
  15833. - strings with more than 4294967295 bytes
  15834. - arrays with more than 4294967295 elements
  15835. - objects with more than 4294967295 elements
  15836. @note The following MessagePack types are not used in the conversion:
  15837. - bin 8 - bin 32 (0xC4..0xC6)
  15838. - ext 8 - ext 32 (0xC7..0xC9)
  15839. - float 32 (0xCA)
  15840. - fixext 1 - fixext 16 (0xD4..0xD8)
  15841. @note Any MessagePack output created @ref to_msgpack can be successfully
  15842. parsed by @ref from_msgpack.
  15843. @note If NaN or Infinity are stored inside a JSON number, they are
  15844. serialized properly. This behavior differs from the @ref dump()
  15845. function which serializes NaN or Infinity to `null`.
  15846. @param[in] j JSON value to serialize
  15847. @return MessagePack serialization as byte vector
  15848. @complexity Linear in the size of the JSON value @a j.
  15849. @liveexample{The example shows the serialization of a JSON value to a byte
  15850. vector in MessagePack format.,to_msgpack}
  15851. @sa http://msgpack.org
  15852. @sa @ref from_msgpack for the analogous deserialization
  15853. @sa @ref to_cbor(const basic_json& for the related CBOR format
  15854. @sa @ref to_ubjson(const basic_json&, const bool, const bool) for the
  15855. related UBJSON format
  15856. @since version 2.0.9
  15857. */
  15858. static std::vector<uint8_t> to_msgpack(const basic_json& j)
  15859. {
  15860. std::vector<uint8_t> result;
  15861. to_msgpack(j, result);
  15862. return result;
  15863. }
  15864. static void to_msgpack(const basic_json& j, detail::output_adapter<uint8_t> o)
  15865. {
  15866. binary_writer<uint8_t>(o).write_msgpack(j);
  15867. }
  15868. static void to_msgpack(const basic_json& j, detail::output_adapter<char> o)
  15869. {
  15870. binary_writer<char>(o).write_msgpack(j);
  15871. }
  15872. /*!
  15873. @brief create a UBJSON serialization of a given JSON value
  15874. Serializes a given JSON value @a j to a byte vector using the UBJSON
  15875. (Universal Binary JSON) serialization format. UBJSON aims to be more compact
  15876. than JSON itself, yet more efficient to parse.
  15877. The library uses the following mapping from JSON values types to
  15878. UBJSON types according to the UBJSON specification:
  15879. JSON value type | value/range | UBJSON type | marker
  15880. --------------- | --------------------------------- | ----------- | ------
  15881. null | `null` | null | `Z`
  15882. boolean | `true` | true | `T`
  15883. boolean | `false` | false | `F`
  15884. number_integer | -9223372036854775808..-2147483649 | int64 | `L`
  15885. number_integer | -2147483648..-32769 | int32 | `l`
  15886. number_integer | -32768..-129 | int16 | `I`
  15887. number_integer | -128..127 | int8 | `i`
  15888. number_integer | 128..255 | uint8 | `U`
  15889. number_integer | 256..32767 | int16 | `I`
  15890. number_integer | 32768..2147483647 | int32 | `l`
  15891. number_integer | 2147483648..9223372036854775807 | int64 | `L`
  15892. number_unsigned | 0..127 | int8 | `i`
  15893. number_unsigned | 128..255 | uint8 | `U`
  15894. number_unsigned | 256..32767 | int16 | `I`
  15895. number_unsigned | 32768..2147483647 | int32 | `l`
  15896. number_unsigned | 2147483648..9223372036854775807 | int64 | `L`
  15897. number_float | *any value* | float64 | `D`
  15898. string | *with shortest length indicator* | string | `S`
  15899. array | *see notes on optimized format* | array | `[`
  15900. object | *see notes on optimized format* | map | `{`
  15901. @note The mapping is **complete** in the sense that any JSON value type
  15902. can be converted to a UBJSON value.
  15903. @note The following values can **not** be converted to a UBJSON value:
  15904. - strings with more than 9223372036854775807 bytes (theoretical)
  15905. - unsigned integer numbers above 9223372036854775807
  15906. @note The following markers are not used in the conversion:
  15907. - `Z`: no-op values are not created.
  15908. - `C`: single-byte strings are serialized with `S` markers.
  15909. @note Any UBJSON output created @ref to_ubjson can be successfully parsed
  15910. by @ref from_ubjson.
  15911. @note If NaN or Infinity are stored inside a JSON number, they are
  15912. serialized properly. This behavior differs from the @ref dump()
  15913. function which serializes NaN or Infinity to `null`.
  15914. @note The optimized formats for containers are supported: Parameter
  15915. @a use_size adds size information to the beginning of a container and
  15916. removes the closing marker. Parameter @a use_type further checks
  15917. whether all elements of a container have the same type and adds the
  15918. type marker to the beginning of the container. The @a use_type
  15919. parameter must only be used together with @a use_size = true. Note
  15920. that @a use_size = true alone may result in larger representations -
  15921. the benefit of this parameter is that the receiving side is
  15922. immediately informed on the number of elements of the container.
  15923. @param[in] j JSON value to serialize
  15924. @param[in] use_size whether to add size annotations to container types
  15925. @param[in] use_type whether to add type annotations to container types
  15926. (must be combined with @a use_size = true)
  15927. @return UBJSON serialization as byte vector
  15928. @complexity Linear in the size of the JSON value @a j.
  15929. @liveexample{The example shows the serialization of a JSON value to a byte
  15930. vector in UBJSON format.,to_ubjson}
  15931. @sa http://ubjson.org
  15932. @sa @ref from_ubjson(detail::input_adapter&&, const bool, const bool) for the
  15933. analogous deserialization
  15934. @sa @ref to_cbor(const basic_json& for the related CBOR format
  15935. @sa @ref to_msgpack(const basic_json&) for the related MessagePack format
  15936. @since version 3.1.0
  15937. */
  15938. static std::vector<uint8_t> to_ubjson(const basic_json& j,
  15939. const bool use_size = false,
  15940. const bool use_type = false)
  15941. {
  15942. std::vector<uint8_t> result;
  15943. to_ubjson(j, result, use_size, use_type);
  15944. return result;
  15945. }
  15946. static void to_ubjson(const basic_json& j, detail::output_adapter<uint8_t> o,
  15947. const bool use_size = false, const bool use_type = false)
  15948. {
  15949. binary_writer<uint8_t>(o).write_ubjson(j, use_size, use_type);
  15950. }
  15951. static void to_ubjson(const basic_json& j, detail::output_adapter<char> o,
  15952. const bool use_size = false, const bool use_type = false)
  15953. {
  15954. binary_writer<char>(o).write_ubjson(j, use_size, use_type);
  15955. }
  15956. /*!
  15957. @brief Serializes the given JSON object `j` to BSON and returns a vector
  15958. containing the corresponding BSON-representation.
  15959. BSON (Binary JSON) is a binary format in which zero or more ordered key/value pairs are
  15960. stored as a single entity (a so-called document).
  15961. The library uses the following mapping from JSON values types to BSON types:
  15962. JSON value type | value/range | BSON type | marker
  15963. --------------- | --------------------------------- | ----------- | ------
  15964. null | `null` | null | 0x0A
  15965. boolean | `true`, `false` | boolean | 0x08
  15966. number_integer | -9223372036854775808..-2147483649 | int64 | 0x12
  15967. number_integer | -2147483648..2147483647 | int32 | 0x10
  15968. number_integer | 2147483648..9223372036854775807 | int64 | 0x12
  15969. number_unsigned | 0..2147483647 | int32 | 0x10
  15970. number_unsigned | 2147483648..9223372036854775807 | int64 | 0x12
  15971. number_unsigned | 9223372036854775808..18446744073709551615| -- | --
  15972. number_float | *any value* | double | 0x01
  15973. string | *any value* | string | 0x02
  15974. array | *any value* | document | 0x04
  15975. object | *any value* | document | 0x03
  15976. @warning The mapping is **incomplete**, since only JSON-objects (and things
  15977. contained therein) can be serialized to BSON.
  15978. Also, integers larger than 9223372036854775807 cannot be serialized to BSON,
  15979. and the keys may not contain U+0000, since they are serialized a
  15980. zero-terminated c-strings.
  15981. @throw out_of_range.407 if `j.is_number_unsigned() && j.get<std::uint64_t>() > 9223372036854775807`
  15982. @throw out_of_range.409 if a key in `j` contains a NULL (U+0000)
  15983. @throw type_error.317 if `!j.is_object()`
  15984. @pre The input `j` is required to be an object: `j.is_object() == true`.
  15985. @note Any BSON output created via @ref to_bson can be successfully parsed
  15986. by @ref from_bson.
  15987. @param[in] j JSON value to serialize
  15988. @return BSON serialization as byte vector
  15989. @complexity Linear in the size of the JSON value @a j.
  15990. @liveexample{The example shows the serialization of a JSON value to a byte
  15991. vector in BSON format.,to_bson}
  15992. @sa http://bsonspec.org/spec.html
  15993. @sa @ref from_bson(detail::input_adapter&&, const bool strict) for the
  15994. analogous deserialization
  15995. @sa @ref to_ubjson(const basic_json&, const bool, const bool) for the
  15996. related UBJSON format
  15997. @sa @ref to_cbor(const basic_json&) for the related CBOR format
  15998. @sa @ref to_msgpack(const basic_json&) for the related MessagePack format
  15999. */
  16000. static std::vector<uint8_t> to_bson(const basic_json& j)
  16001. {
  16002. std::vector<uint8_t> result;
  16003. to_bson(j, result);
  16004. return result;
  16005. }
  16006. /*!
  16007. @brief Serializes the given JSON object `j` to BSON and forwards the
  16008. corresponding BSON-representation to the given output_adapter `o`.
  16009. @param j The JSON object to convert to BSON.
  16010. @param o The output adapter that receives the binary BSON representation.
  16011. @pre The input `j` shall be an object: `j.is_object() == true`
  16012. @sa @ref to_bson(const basic_json&)
  16013. */
  16014. static void to_bson(const basic_json& j, detail::output_adapter<uint8_t> o)
  16015. {
  16016. binary_writer<uint8_t>(o).write_bson(j);
  16017. }
  16018. /*!
  16019. @copydoc to_bson(const basic_json&, detail::output_adapter<uint8_t>)
  16020. */
  16021. static void to_bson(const basic_json& j, detail::output_adapter<char> o)
  16022. {
  16023. binary_writer<char>(o).write_bson(j);
  16024. }
  16025. /*!
  16026. @brief create a JSON value from an input in CBOR format
  16027. Deserializes a given input @a i to a JSON value using the CBOR (Concise
  16028. Binary Object Representation) serialization format.
  16029. The library maps CBOR types to JSON value types as follows:
  16030. CBOR type | JSON value type | first byte
  16031. ---------------------- | --------------- | ----------
  16032. Integer | number_unsigned | 0x00..0x17
  16033. Unsigned integer | number_unsigned | 0x18
  16034. Unsigned integer | number_unsigned | 0x19
  16035. Unsigned integer | number_unsigned | 0x1A
  16036. Unsigned integer | number_unsigned | 0x1B
  16037. Negative integer | number_integer | 0x20..0x37
  16038. Negative integer | number_integer | 0x38
  16039. Negative integer | number_integer | 0x39
  16040. Negative integer | number_integer | 0x3A
  16041. Negative integer | number_integer | 0x3B
  16042. Negative integer | number_integer | 0x40..0x57
  16043. UTF-8 string | string | 0x60..0x77
  16044. UTF-8 string | string | 0x78
  16045. UTF-8 string | string | 0x79
  16046. UTF-8 string | string | 0x7A
  16047. UTF-8 string | string | 0x7B
  16048. UTF-8 string | string | 0x7F
  16049. array | array | 0x80..0x97
  16050. array | array | 0x98
  16051. array | array | 0x99
  16052. array | array | 0x9A
  16053. array | array | 0x9B
  16054. array | array | 0x9F
  16055. map | object | 0xA0..0xB7
  16056. map | object | 0xB8
  16057. map | object | 0xB9
  16058. map | object | 0xBA
  16059. map | object | 0xBB
  16060. map | object | 0xBF
  16061. False | `false` | 0xF4
  16062. True | `true` | 0xF5
  16063. Null | `null` | 0xF6
  16064. Half-Precision Float | number_float | 0xF9
  16065. Single-Precision Float | number_float | 0xFA
  16066. Double-Precision Float | number_float | 0xFB
  16067. @warning The mapping is **incomplete** in the sense that not all CBOR
  16068. types can be converted to a JSON value. The following CBOR types
  16069. are not supported and will yield parse errors (parse_error.112):
  16070. - byte strings (0x40..0x5F)
  16071. - date/time (0xC0..0xC1)
  16072. - bignum (0xC2..0xC3)
  16073. - decimal fraction (0xC4)
  16074. - bigfloat (0xC5)
  16075. - tagged items (0xC6..0xD4, 0xD8..0xDB)
  16076. - expected conversions (0xD5..0xD7)
  16077. - simple values (0xE0..0xF3, 0xF8)
  16078. - undefined (0xF7)
  16079. @warning CBOR allows map keys of any type, whereas JSON only allows
  16080. strings as keys in object values. Therefore, CBOR maps with keys
  16081. other than UTF-8 strings are rejected (parse_error.113).
  16082. @note Any CBOR output created @ref to_cbor can be successfully parsed by
  16083. @ref from_cbor.
  16084. @param[in] i an input in CBOR format convertible to an input adapter
  16085. @param[in] strict whether to expect the input to be consumed until EOF
  16086. (true by default)
  16087. @param[in] allow_exceptions whether to throw exceptions in case of a
  16088. parse error (optional, true by default)
  16089. @return deserialized JSON value
  16090. @throw parse_error.110 if the given input ends prematurely or the end of
  16091. file was not reached when @a strict was set to true
  16092. @throw parse_error.112 if unsupported features from CBOR were
  16093. used in the given input @a v or if the input is not valid CBOR
  16094. @throw parse_error.113 if a string was expected as map key, but not found
  16095. @complexity Linear in the size of the input @a i.
  16096. @liveexample{The example shows the deserialization of a byte vector in CBOR
  16097. format to a JSON value.,from_cbor}
  16098. @sa http://cbor.io
  16099. @sa @ref to_cbor(const basic_json&) for the analogous serialization
  16100. @sa @ref from_msgpack(detail::input_adapter&&, const bool, const bool) for the
  16101. related MessagePack format
  16102. @sa @ref from_ubjson(detail::input_adapter&&, const bool, const bool) for the
  16103. related UBJSON format
  16104. @since version 2.0.9; parameter @a start_index since 2.1.1; changed to
  16105. consume input adapters, removed start_index parameter, and added
  16106. @a strict parameter since 3.0.0; added @a allow_exceptions parameter
  16107. since 3.2.0
  16108. */
  16109. static basic_json from_cbor(detail::input_adapter&& i,
  16110. const bool strict = true,
  16111. const bool allow_exceptions = true)
  16112. {
  16113. basic_json result;
  16114. detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
  16115. const bool res = binary_reader(detail::input_adapter(i)).sax_parse(input_format_t::cbor, &sdp, strict);
  16116. return res ? result : basic_json(value_t::discarded);
  16117. }
  16118. /*!
  16119. @copydoc from_cbor(detail::input_adapter&&, const bool, const bool)
  16120. */
  16121. template<typename A1, typename A2,
  16122. detail::enable_if_t<std::is_constructible<detail::input_adapter, A1, A2>::value, int> = 0>
  16123. static basic_json from_cbor(A1 && a1, A2 && a2,
  16124. const bool strict = true,
  16125. const bool allow_exceptions = true)
  16126. {
  16127. basic_json result;
  16128. detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
  16129. const bool res = binary_reader(detail::input_adapter(std::forward<A1>(a1), std::forward<A2>(a2))).sax_parse(input_format_t::cbor, &sdp, strict);
  16130. return res ? result : basic_json(value_t::discarded);
  16131. }
  16132. /*!
  16133. @brief create a JSON value from an input in MessagePack format
  16134. Deserializes a given input @a i to a JSON value using the MessagePack
  16135. serialization format.
  16136. The library maps MessagePack types to JSON value types as follows:
  16137. MessagePack type | JSON value type | first byte
  16138. ---------------- | --------------- | ----------
  16139. positive fixint | number_unsigned | 0x00..0x7F
  16140. fixmap | object | 0x80..0x8F
  16141. fixarray | array | 0x90..0x9F
  16142. fixstr | string | 0xA0..0xBF
  16143. nil | `null` | 0xC0
  16144. false | `false` | 0xC2
  16145. true | `true` | 0xC3
  16146. float 32 | number_float | 0xCA
  16147. float 64 | number_float | 0xCB
  16148. uint 8 | number_unsigned | 0xCC
  16149. uint 16 | number_unsigned | 0xCD
  16150. uint 32 | number_unsigned | 0xCE
  16151. uint 64 | number_unsigned | 0xCF
  16152. int 8 | number_integer | 0xD0
  16153. int 16 | number_integer | 0xD1
  16154. int 32 | number_integer | 0xD2
  16155. int 64 | number_integer | 0xD3
  16156. str 8 | string | 0xD9
  16157. str 16 | string | 0xDA
  16158. str 32 | string | 0xDB
  16159. array 16 | array | 0xDC
  16160. array 32 | array | 0xDD
  16161. map 16 | object | 0xDE
  16162. map 32 | object | 0xDF
  16163. negative fixint | number_integer | 0xE0-0xFF
  16164. @warning The mapping is **incomplete** in the sense that not all
  16165. MessagePack types can be converted to a JSON value. The following
  16166. MessagePack types are not supported and will yield parse errors:
  16167. - bin 8 - bin 32 (0xC4..0xC6)
  16168. - ext 8 - ext 32 (0xC7..0xC9)
  16169. - fixext 1 - fixext 16 (0xD4..0xD8)
  16170. @note Any MessagePack output created @ref to_msgpack can be successfully
  16171. parsed by @ref from_msgpack.
  16172. @param[in] i an input in MessagePack format convertible to an input
  16173. adapter
  16174. @param[in] strict whether to expect the input to be consumed until EOF
  16175. (true by default)
  16176. @param[in] allow_exceptions whether to throw exceptions in case of a
  16177. parse error (optional, true by default)
  16178. @return deserialized JSON value
  16179. @throw parse_error.110 if the given input ends prematurely or the end of
  16180. file was not reached when @a strict was set to true
  16181. @throw parse_error.112 if unsupported features from MessagePack were
  16182. used in the given input @a i or if the input is not valid MessagePack
  16183. @throw parse_error.113 if a string was expected as map key, but not found
  16184. @complexity Linear in the size of the input @a i.
  16185. @liveexample{The example shows the deserialization of a byte vector in
  16186. MessagePack format to a JSON value.,from_msgpack}
  16187. @sa http://msgpack.org
  16188. @sa @ref to_msgpack(const basic_json&) for the analogous serialization
  16189. @sa @ref from_cbor(detail::input_adapter&&, const bool, const bool) for the
  16190. related CBOR format
  16191. @sa @ref from_ubjson(detail::input_adapter&&, const bool, const bool) for
  16192. the related UBJSON format
  16193. @sa @ref from_bson(detail::input_adapter&&, const bool, const bool) for
  16194. the related BSON format
  16195. @since version 2.0.9; parameter @a start_index since 2.1.1; changed to
  16196. consume input adapters, removed start_index parameter, and added
  16197. @a strict parameter since 3.0.0; added @a allow_exceptions parameter
  16198. since 3.2.0
  16199. */
  16200. static basic_json from_msgpack(detail::input_adapter&& i,
  16201. const bool strict = true,
  16202. const bool allow_exceptions = true)
  16203. {
  16204. basic_json result;
  16205. detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
  16206. const bool res = binary_reader(detail::input_adapter(i)).sax_parse(input_format_t::msgpack, &sdp, strict);
  16207. return res ? result : basic_json(value_t::discarded);
  16208. }
  16209. /*!
  16210. @copydoc from_msgpack(detail::input_adapter&&, const bool, const bool)
  16211. */
  16212. template<typename A1, typename A2,
  16213. detail::enable_if_t<std::is_constructible<detail::input_adapter, A1, A2>::value, int> = 0>
  16214. static basic_json from_msgpack(A1 && a1, A2 && a2,
  16215. const bool strict = true,
  16216. const bool allow_exceptions = true)
  16217. {
  16218. basic_json result;
  16219. detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
  16220. const bool res = binary_reader(detail::input_adapter(std::forward<A1>(a1), std::forward<A2>(a2))).sax_parse(input_format_t::msgpack, &sdp, strict);
  16221. return res ? result : basic_json(value_t::discarded);
  16222. }
  16223. /*!
  16224. @brief create a JSON value from an input in UBJSON format
  16225. Deserializes a given input @a i to a JSON value using the UBJSON (Universal
  16226. Binary JSON) serialization format.
  16227. The library maps UBJSON types to JSON value types as follows:
  16228. UBJSON type | JSON value type | marker
  16229. ----------- | --------------------------------------- | ------
  16230. no-op | *no value, next value is read* | `N`
  16231. null | `null` | `Z`
  16232. false | `false` | `F`
  16233. true | `true` | `T`
  16234. float32 | number_float | `d`
  16235. float64 | number_float | `D`
  16236. uint8 | number_unsigned | `U`
  16237. int8 | number_integer | `i`
  16238. int16 | number_integer | `I`
  16239. int32 | number_integer | `l`
  16240. int64 | number_integer | `L`
  16241. string | string | `S`
  16242. char | string | `C`
  16243. array | array (optimized values are supported) | `[`
  16244. object | object (optimized values are supported) | `{`
  16245. @note The mapping is **complete** in the sense that any UBJSON value can
  16246. be converted to a JSON value.
  16247. @param[in] i an input in UBJSON format convertible to an input adapter
  16248. @param[in] strict whether to expect the input to be consumed until EOF
  16249. (true by default)
  16250. @param[in] allow_exceptions whether to throw exceptions in case of a
  16251. parse error (optional, true by default)
  16252. @return deserialized JSON value
  16253. @throw parse_error.110 if the given input ends prematurely or the end of
  16254. file was not reached when @a strict was set to true
  16255. @throw parse_error.112 if a parse error occurs
  16256. @throw parse_error.113 if a string could not be parsed successfully
  16257. @complexity Linear in the size of the input @a i.
  16258. @liveexample{The example shows the deserialization of a byte vector in
  16259. UBJSON format to a JSON value.,from_ubjson}
  16260. @sa http://ubjson.org
  16261. @sa @ref to_ubjson(const basic_json&, const bool, const bool) for the
  16262. analogous serialization
  16263. @sa @ref from_cbor(detail::input_adapter&&, const bool, const bool) for the
  16264. related CBOR format
  16265. @sa @ref from_msgpack(detail::input_adapter&&, const bool, const bool) for
  16266. the related MessagePack format
  16267. @sa @ref from_bson(detail::input_adapter&&, const bool, const bool) for
  16268. the related BSON format
  16269. @since version 3.1.0; added @a allow_exceptions parameter since 3.2.0
  16270. */
  16271. static basic_json from_ubjson(detail::input_adapter&& i,
  16272. const bool strict = true,
  16273. const bool allow_exceptions = true)
  16274. {
  16275. basic_json result;
  16276. detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
  16277. const bool res = binary_reader(detail::input_adapter(i)).sax_parse(input_format_t::ubjson, &sdp, strict);
  16278. return res ? result : basic_json(value_t::discarded);
  16279. }
  16280. /*!
  16281. @copydoc from_ubjson(detail::input_adapter&&, const bool, const bool)
  16282. */
  16283. template<typename A1, typename A2,
  16284. detail::enable_if_t<std::is_constructible<detail::input_adapter, A1, A2>::value, int> = 0>
  16285. static basic_json from_ubjson(A1 && a1, A2 && a2,
  16286. const bool strict = true,
  16287. const bool allow_exceptions = true)
  16288. {
  16289. basic_json result;
  16290. detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
  16291. const bool res = binary_reader(detail::input_adapter(std::forward<A1>(a1), std::forward<A2>(a2))).sax_parse(input_format_t::ubjson, &sdp, strict);
  16292. return res ? result : basic_json(value_t::discarded);
  16293. }
  16294. /*!
  16295. @brief Create a JSON value from an input in BSON format
  16296. Deserializes a given input @a i to a JSON value using the BSON (Binary JSON)
  16297. serialization format.
  16298. The library maps BSON record types to JSON value types as follows:
  16299. BSON type | BSON marker byte | JSON value type
  16300. --------------- | ---------------- | ---------------------------
  16301. double | 0x01 | number_float
  16302. string | 0x02 | string
  16303. document | 0x03 | object
  16304. array | 0x04 | array
  16305. binary | 0x05 | still unsupported
  16306. undefined | 0x06 | still unsupported
  16307. ObjectId | 0x07 | still unsupported
  16308. boolean | 0x08 | boolean
  16309. UTC Date-Time | 0x09 | still unsupported
  16310. null | 0x0A | null
  16311. Regular Expr. | 0x0B | still unsupported
  16312. DB Pointer | 0x0C | still unsupported
  16313. JavaScript Code | 0x0D | still unsupported
  16314. Symbol | 0x0E | still unsupported
  16315. JavaScript Code | 0x0F | still unsupported
  16316. int32 | 0x10 | number_integer
  16317. Timestamp | 0x11 | still unsupported
  16318. 128-bit decimal float | 0x13 | still unsupported
  16319. Max Key | 0x7F | still unsupported
  16320. Min Key | 0xFF | still unsupported
  16321. @warning The mapping is **incomplete**. The unsupported mappings
  16322. are indicated in the table above.
  16323. @param[in] i an input in BSON format convertible to an input adapter
  16324. @param[in] strict whether to expect the input to be consumed until EOF
  16325. (true by default)
  16326. @param[in] allow_exceptions whether to throw exceptions in case of a
  16327. parse error (optional, true by default)
  16328. @return deserialized JSON value
  16329. @throw parse_error.114 if an unsupported BSON record type is encountered
  16330. @complexity Linear in the size of the input @a i.
  16331. @liveexample{The example shows the deserialization of a byte vector in
  16332. BSON format to a JSON value.,from_bson}
  16333. @sa http://bsonspec.org/spec.html
  16334. @sa @ref to_bson(const basic_json&) for the analogous serialization
  16335. @sa @ref from_cbor(detail::input_adapter&&, const bool, const bool) for the
  16336. related CBOR format
  16337. @sa @ref from_msgpack(detail::input_adapter&&, const bool, const bool) for
  16338. the related MessagePack format
  16339. @sa @ref from_ubjson(detail::input_adapter&&, const bool, const bool) for the
  16340. related UBJSON format
  16341. */
  16342. static basic_json from_bson(detail::input_adapter&& i,
  16343. const bool strict = true,
  16344. const bool allow_exceptions = true)
  16345. {
  16346. basic_json result;
  16347. detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
  16348. const bool res = binary_reader(detail::input_adapter(i)).sax_parse(input_format_t::bson, &sdp, strict);
  16349. return res ? result : basic_json(value_t::discarded);
  16350. }
  16351. /*!
  16352. @copydoc from_bson(detail::input_adapter&&, const bool, const bool)
  16353. */
  16354. template<typename A1, typename A2,
  16355. detail::enable_if_t<std::is_constructible<detail::input_adapter, A1, A2>::value, int> = 0>
  16356. static basic_json from_bson(A1 && a1, A2 && a2,
  16357. const bool strict = true,
  16358. const bool allow_exceptions = true)
  16359. {
  16360. basic_json result;
  16361. detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
  16362. const bool res = binary_reader(detail::input_adapter(std::forward<A1>(a1), std::forward<A2>(a2))).sax_parse(input_format_t::bson, &sdp, strict);
  16363. return res ? result : basic_json(value_t::discarded);
  16364. }
  16365. /// @}
  16366. //////////////////////////
  16367. // JSON Pointer support //
  16368. //////////////////////////
  16369. /// @name JSON Pointer functions
  16370. /// @{
  16371. /*!
  16372. @brief access specified element via JSON Pointer
  16373. Uses a JSON pointer to retrieve a reference to the respective JSON value.
  16374. No bound checking is performed. Similar to @ref operator[](const typename
  16375. object_t::key_type&), `null` values are created in arrays and objects if
  16376. necessary.
  16377. In particular:
  16378. - If the JSON pointer points to an object key that does not exist, it
  16379. is created an filled with a `null` value before a reference to it
  16380. is returned.
  16381. - If the JSON pointer points to an array index that does not exist, it
  16382. is created an filled with a `null` value before a reference to it
  16383. is returned. All indices between the current maximum and the given
  16384. index are also filled with `null`.
  16385. - The special value `-` is treated as a synonym for the index past the
  16386. end.
  16387. @param[in] ptr a JSON pointer
  16388. @return reference to the element pointed to by @a ptr
  16389. @complexity Constant.
  16390. @throw parse_error.106 if an array index begins with '0'
  16391. @throw parse_error.109 if an array index was not a number
  16392. @throw out_of_range.404 if the JSON pointer can not be resolved
  16393. @liveexample{The behavior is shown in the example.,operatorjson_pointer}
  16394. @since version 2.0.0
  16395. */
  16396. reference operator[](const json_pointer& ptr)
  16397. {
  16398. return ptr.get_unchecked(this);
  16399. }
  16400. /*!
  16401. @brief access specified element via JSON Pointer
  16402. Uses a JSON pointer to retrieve a reference to the respective JSON value.
  16403. No bound checking is performed. The function does not change the JSON
  16404. value; no `null` values are created. In particular, the the special value
  16405. `-` yields an exception.
  16406. @param[in] ptr JSON pointer to the desired element
  16407. @return const reference to the element pointed to by @a ptr
  16408. @complexity Constant.
  16409. @throw parse_error.106 if an array index begins with '0'
  16410. @throw parse_error.109 if an array index was not a number
  16411. @throw out_of_range.402 if the array index '-' is used
  16412. @throw out_of_range.404 if the JSON pointer can not be resolved
  16413. @liveexample{The behavior is shown in the example.,operatorjson_pointer_const}
  16414. @since version 2.0.0
  16415. */
  16416. const_reference operator[](const json_pointer& ptr) const
  16417. {
  16418. return ptr.get_unchecked(this);
  16419. }
  16420. /*!
  16421. @brief access specified element via JSON Pointer
  16422. Returns a reference to the element at with specified JSON pointer @a ptr,
  16423. with bounds checking.
  16424. @param[in] ptr JSON pointer to the desired element
  16425. @return reference to the element pointed to by @a ptr
  16426. @throw parse_error.106 if an array index in the passed JSON pointer @a ptr
  16427. begins with '0'. See example below.
  16428. @throw parse_error.109 if an array index in the passed JSON pointer @a ptr
  16429. is not a number. See example below.
  16430. @throw out_of_range.401 if an array index in the passed JSON pointer @a ptr
  16431. is out of range. See example below.
  16432. @throw out_of_range.402 if the array index '-' is used in the passed JSON
  16433. pointer @a ptr. As `at` provides checked access (and no elements are
  16434. implicitly inserted), the index '-' is always invalid. See example below.
  16435. @throw out_of_range.403 if the JSON pointer describes a key of an object
  16436. which cannot be found. See example below.
  16437. @throw out_of_range.404 if the JSON pointer @a ptr can not be resolved.
  16438. See example below.
  16439. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  16440. changes in the JSON value.
  16441. @complexity Constant.
  16442. @since version 2.0.0
  16443. @liveexample{The behavior is shown in the example.,at_json_pointer}
  16444. */
  16445. reference at(const json_pointer& ptr)
  16446. {
  16447. return ptr.get_checked(this);
  16448. }
  16449. /*!
  16450. @brief access specified element via JSON Pointer
  16451. Returns a const reference to the element at with specified JSON pointer @a
  16452. ptr, with bounds checking.
  16453. @param[in] ptr JSON pointer to the desired element
  16454. @return reference to the element pointed to by @a ptr
  16455. @throw parse_error.106 if an array index in the passed JSON pointer @a ptr
  16456. begins with '0'. See example below.
  16457. @throw parse_error.109 if an array index in the passed JSON pointer @a ptr
  16458. is not a number. See example below.
  16459. @throw out_of_range.401 if an array index in the passed JSON pointer @a ptr
  16460. is out of range. See example below.
  16461. @throw out_of_range.402 if the array index '-' is used in the passed JSON
  16462. pointer @a ptr. As `at` provides checked access (and no elements are
  16463. implicitly inserted), the index '-' is always invalid. See example below.
  16464. @throw out_of_range.403 if the JSON pointer describes a key of an object
  16465. which cannot be found. See example below.
  16466. @throw out_of_range.404 if the JSON pointer @a ptr can not be resolved.
  16467. See example below.
  16468. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  16469. changes in the JSON value.
  16470. @complexity Constant.
  16471. @since version 2.0.0
  16472. @liveexample{The behavior is shown in the example.,at_json_pointer_const}
  16473. */
  16474. const_reference at(const json_pointer& ptr) const
  16475. {
  16476. return ptr.get_checked(this);
  16477. }
  16478. /*!
  16479. @brief return flattened JSON value
  16480. The function creates a JSON object whose keys are JSON pointers (see [RFC
  16481. 6901](https://tools.ietf.org/html/rfc6901)) and whose values are all
  16482. primitive. The original JSON value can be restored using the @ref
  16483. unflatten() function.
  16484. @return an object that maps JSON pointers to primitive values
  16485. @note Empty objects and arrays are flattened to `null` and will not be
  16486. reconstructed correctly by the @ref unflatten() function.
  16487. @complexity Linear in the size the JSON value.
  16488. @liveexample{The following code shows how a JSON object is flattened to an
  16489. object whose keys consist of JSON pointers.,flatten}
  16490. @sa @ref unflatten() for the reverse function
  16491. @since version 2.0.0
  16492. */
  16493. basic_json flatten() const
  16494. {
  16495. basic_json result(value_t::object);
  16496. json_pointer::flatten("", *this, result);
  16497. return result;
  16498. }
  16499. /*!
  16500. @brief unflatten a previously flattened JSON value
  16501. The function restores the arbitrary nesting of a JSON value that has been
  16502. flattened before using the @ref flatten() function. The JSON value must
  16503. meet certain constraints:
  16504. 1. The value must be an object.
  16505. 2. The keys must be JSON pointers (see
  16506. [RFC 6901](https://tools.ietf.org/html/rfc6901))
  16507. 3. The mapped values must be primitive JSON types.
  16508. @return the original JSON from a flattened version
  16509. @note Empty objects and arrays are flattened by @ref flatten() to `null`
  16510. values and can not unflattened to their original type. Apart from
  16511. this example, for a JSON value `j`, the following is always true:
  16512. `j == j.flatten().unflatten()`.
  16513. @complexity Linear in the size the JSON value.
  16514. @throw type_error.314 if value is not an object
  16515. @throw type_error.315 if object values are not primitive
  16516. @liveexample{The following code shows how a flattened JSON object is
  16517. unflattened into the original nested JSON object.,unflatten}
  16518. @sa @ref flatten() for the reverse function
  16519. @since version 2.0.0
  16520. */
  16521. basic_json unflatten() const
  16522. {
  16523. return json_pointer::unflatten(*this);
  16524. }
  16525. /// @}
  16526. //////////////////////////
  16527. // JSON Patch functions //
  16528. //////////////////////////
  16529. /// @name JSON Patch functions
  16530. /// @{
  16531. /*!
  16532. @brief applies a JSON patch
  16533. [JSON Patch](http://jsonpatch.com) defines a JSON document structure for
  16534. expressing a sequence of operations to apply to a JSON) document. With
  16535. this function, a JSON Patch is applied to the current JSON value by
  16536. executing all operations from the patch.
  16537. @param[in] json_patch JSON patch document
  16538. @return patched document
  16539. @note The application of a patch is atomic: Either all operations succeed
  16540. and the patched document is returned or an exception is thrown. In
  16541. any case, the original value is not changed: the patch is applied
  16542. to a copy of the value.
  16543. @throw parse_error.104 if the JSON patch does not consist of an array of
  16544. objects
  16545. @throw parse_error.105 if the JSON patch is malformed (e.g., mandatory
  16546. attributes are missing); example: `"operation add must have member path"`
  16547. @throw out_of_range.401 if an array index is out of range.
  16548. @throw out_of_range.403 if a JSON pointer inside the patch could not be
  16549. resolved successfully in the current JSON value; example: `"key baz not
  16550. found"`
  16551. @throw out_of_range.405 if JSON pointer has no parent ("add", "remove",
  16552. "move")
  16553. @throw other_error.501 if "test" operation was unsuccessful
  16554. @complexity Linear in the size of the JSON value and the length of the
  16555. JSON patch. As usually only a fraction of the JSON value is affected by
  16556. the patch, the complexity can usually be neglected.
  16557. @liveexample{The following code shows how a JSON patch is applied to a
  16558. value.,patch}
  16559. @sa @ref diff -- create a JSON patch by comparing two JSON values
  16560. @sa [RFC 6902 (JSON Patch)](https://tools.ietf.org/html/rfc6902)
  16561. @sa [RFC 6901 (JSON Pointer)](https://tools.ietf.org/html/rfc6901)
  16562. @since version 2.0.0
  16563. */
  16564. basic_json patch(const basic_json& json_patch) const
  16565. {
  16566. // make a working copy to apply the patch to
  16567. basic_json result = *this;
  16568. // the valid JSON Patch operations
  16569. enum class patch_operations {add, remove, replace, move, copy, test, invalid};
  16570. const auto get_op = [](const std::string & op)
  16571. {
  16572. if (op == "add")
  16573. {
  16574. return patch_operations::add;
  16575. }
  16576. if (op == "remove")
  16577. {
  16578. return patch_operations::remove;
  16579. }
  16580. if (op == "replace")
  16581. {
  16582. return patch_operations::replace;
  16583. }
  16584. if (op == "move")
  16585. {
  16586. return patch_operations::move;
  16587. }
  16588. if (op == "copy")
  16589. {
  16590. return patch_operations::copy;
  16591. }
  16592. if (op == "test")
  16593. {
  16594. return patch_operations::test;
  16595. }
  16596. return patch_operations::invalid;
  16597. };
  16598. // wrapper for "add" operation; add value at ptr
  16599. const auto operation_add = [&result](json_pointer & ptr, basic_json val)
  16600. {
  16601. // adding to the root of the target document means replacing it
  16602. if (ptr.is_root())
  16603. {
  16604. result = val;
  16605. }
  16606. else
  16607. {
  16608. // make sure the top element of the pointer exists
  16609. json_pointer top_pointer = ptr.top();
  16610. if (top_pointer != ptr)
  16611. {
  16612. result.at(top_pointer);
  16613. }
  16614. // get reference to parent of JSON pointer ptr
  16615. const auto last_path = ptr.pop_back();
  16616. basic_json& parent = result[ptr];
  16617. switch (parent.m_type)
  16618. {
  16619. case value_t::null:
  16620. case value_t::object:
  16621. {
  16622. // use operator[] to add value
  16623. parent[last_path] = val;
  16624. break;
  16625. }
  16626. case value_t::array:
  16627. {
  16628. if (last_path == "-")
  16629. {
  16630. // special case: append to back
  16631. parent.push_back(val);
  16632. }
  16633. else
  16634. {
  16635. const auto idx = json_pointer::array_index(last_path);
  16636. if (JSON_UNLIKELY(static_cast<size_type>(idx) > parent.size()))
  16637. {
  16638. // avoid undefined behavior
  16639. JSON_THROW(out_of_range::create(401, "array index " + std::to_string(idx) + " is out of range"));
  16640. }
  16641. // default case: insert add offset
  16642. parent.insert(parent.begin() + static_cast<difference_type>(idx), val);
  16643. }
  16644. break;
  16645. }
  16646. // LCOV_EXCL_START
  16647. default:
  16648. {
  16649. // if there exists a parent it cannot be primitive
  16650. assert(false);
  16651. }
  16652. // LCOV_EXCL_STOP
  16653. }
  16654. }
  16655. };
  16656. // wrapper for "remove" operation; remove value at ptr
  16657. const auto operation_remove = [&result](json_pointer & ptr)
  16658. {
  16659. // get reference to parent of JSON pointer ptr
  16660. const auto last_path = ptr.pop_back();
  16661. basic_json& parent = result.at(ptr);
  16662. // remove child
  16663. if (parent.is_object())
  16664. {
  16665. // perform range check
  16666. auto it = parent.find(last_path);
  16667. if (JSON_LIKELY(it != parent.end()))
  16668. {
  16669. parent.erase(it);
  16670. }
  16671. else
  16672. {
  16673. JSON_THROW(out_of_range::create(403, "key '" + last_path + "' not found"));
  16674. }
  16675. }
  16676. else if (parent.is_array())
  16677. {
  16678. // note erase performs range check
  16679. parent.erase(static_cast<size_type>(json_pointer::array_index(last_path)));
  16680. }
  16681. };
  16682. // type check: top level value must be an array
  16683. if (JSON_UNLIKELY(not json_patch.is_array()))
  16684. {
  16685. JSON_THROW(parse_error::create(104, 0, "JSON patch must be an array of objects"));
  16686. }
  16687. // iterate and apply the operations
  16688. for (const auto& val : json_patch)
  16689. {
  16690. // wrapper to get a value for an operation
  16691. const auto get_value = [&val](const std::string & op,
  16692. const std::string & member,
  16693. bool string_type) -> basic_json &
  16694. {
  16695. // find value
  16696. auto it = val.m_value.object->find(member);
  16697. // context-sensitive error message
  16698. const auto error_msg = (op == "op") ? "operation" : "operation '" + op + "'";
  16699. // check if desired value is present
  16700. if (JSON_UNLIKELY(it == val.m_value.object->end()))
  16701. {
  16702. JSON_THROW(parse_error::create(105, 0, error_msg + " must have member '" + member + "'"));
  16703. }
  16704. // check if result is of type string
  16705. if (JSON_UNLIKELY(string_type and not it->second.is_string()))
  16706. {
  16707. JSON_THROW(parse_error::create(105, 0, error_msg + " must have string member '" + member + "'"));
  16708. }
  16709. // no error: return value
  16710. return it->second;
  16711. };
  16712. // type check: every element of the array must be an object
  16713. if (JSON_UNLIKELY(not val.is_object()))
  16714. {
  16715. JSON_THROW(parse_error::create(104, 0, "JSON patch must be an array of objects"));
  16716. }
  16717. // collect mandatory members
  16718. const std::string op = get_value("op", "op", true);
  16719. const std::string path = get_value(op, "path", true);
  16720. json_pointer ptr(path);
  16721. switch (get_op(op))
  16722. {
  16723. case patch_operations::add:
  16724. {
  16725. operation_add(ptr, get_value("add", "value", false));
  16726. break;
  16727. }
  16728. case patch_operations::remove:
  16729. {
  16730. operation_remove(ptr);
  16731. break;
  16732. }
  16733. case patch_operations::replace:
  16734. {
  16735. // the "path" location must exist - use at()
  16736. result.at(ptr) = get_value("replace", "value", false);
  16737. break;
  16738. }
  16739. case patch_operations::move:
  16740. {
  16741. const std::string from_path = get_value("move", "from", true);
  16742. json_pointer from_ptr(from_path);
  16743. // the "from" location must exist - use at()
  16744. basic_json v = result.at(from_ptr);
  16745. // The move operation is functionally identical to a
  16746. // "remove" operation on the "from" location, followed
  16747. // immediately by an "add" operation at the target
  16748. // location with the value that was just removed.
  16749. operation_remove(from_ptr);
  16750. operation_add(ptr, v);
  16751. break;
  16752. }
  16753. case patch_operations::copy:
  16754. {
  16755. const std::string from_path = get_value("copy", "from", true);
  16756. const json_pointer from_ptr(from_path);
  16757. // the "from" location must exist - use at()
  16758. basic_json v = result.at(from_ptr);
  16759. // The copy is functionally identical to an "add"
  16760. // operation at the target location using the value
  16761. // specified in the "from" member.
  16762. operation_add(ptr, v);
  16763. break;
  16764. }
  16765. case patch_operations::test:
  16766. {
  16767. bool success = false;
  16768. JSON_TRY
  16769. {
  16770. // check if "value" matches the one at "path"
  16771. // the "path" location must exist - use at()
  16772. success = (result.at(ptr) == get_value("test", "value", false));
  16773. }
  16774. JSON_INTERNAL_CATCH (out_of_range&)
  16775. {
  16776. // ignore out of range errors: success remains false
  16777. }
  16778. // throw an exception if test fails
  16779. if (JSON_UNLIKELY(not success))
  16780. {
  16781. JSON_THROW(other_error::create(501, "unsuccessful: " + val.dump()));
  16782. }
  16783. break;
  16784. }
  16785. case patch_operations::invalid:
  16786. {
  16787. // op must be "add", "remove", "replace", "move", "copy", or
  16788. // "test"
  16789. JSON_THROW(parse_error::create(105, 0, "operation value '" + op + "' is invalid"));
  16790. }
  16791. }
  16792. }
  16793. return result;
  16794. }
  16795. /*!
  16796. @brief creates a diff as a JSON patch
  16797. Creates a [JSON Patch](http://jsonpatch.com) so that value @a source can
  16798. be changed into the value @a target by calling @ref patch function.
  16799. @invariant For two JSON values @a source and @a target, the following code
  16800. yields always `true`:
  16801. @code {.cpp}
  16802. source.patch(diff(source, target)) == target;
  16803. @endcode
  16804. @note Currently, only `remove`, `add`, and `replace` operations are
  16805. generated.
  16806. @param[in] source JSON value to compare from
  16807. @param[in] target JSON value to compare against
  16808. @param[in] path helper value to create JSON pointers
  16809. @return a JSON patch to convert the @a source to @a target
  16810. @complexity Linear in the lengths of @a source and @a target.
  16811. @liveexample{The following code shows how a JSON patch is created as a
  16812. diff for two JSON values.,diff}
  16813. @sa @ref patch -- apply a JSON patch
  16814. @sa @ref merge_patch -- apply a JSON Merge Patch
  16815. @sa [RFC 6902 (JSON Patch)](https://tools.ietf.org/html/rfc6902)
  16816. @since version 2.0.0
  16817. */
  16818. static basic_json diff(const basic_json& source, const basic_json& target,
  16819. const std::string& path = "")
  16820. {
  16821. // the patch
  16822. basic_json result(value_t::array);
  16823. // if the values are the same, return empty patch
  16824. if (source == target)
  16825. {
  16826. return result;
  16827. }
  16828. if (source.type() != target.type())
  16829. {
  16830. // different types: replace value
  16831. result.push_back(
  16832. {
  16833. {"op", "replace"}, {"path", path}, {"value", target}
  16834. });
  16835. }
  16836. else
  16837. {
  16838. switch (source.type())
  16839. {
  16840. case value_t::array:
  16841. {
  16842. // first pass: traverse common elements
  16843. std::size_t i = 0;
  16844. while (i < source.size() and i < target.size())
  16845. {
  16846. // recursive call to compare array values at index i
  16847. auto temp_diff = diff(source[i], target[i], path + "/" + std::to_string(i));
  16848. result.insert(result.end(), temp_diff.begin(), temp_diff.end());
  16849. ++i;
  16850. }
  16851. // i now reached the end of at least one array
  16852. // in a second pass, traverse the remaining elements
  16853. // remove my remaining elements
  16854. const auto end_index = static_cast<difference_type>(result.size());
  16855. while (i < source.size())
  16856. {
  16857. // add operations in reverse order to avoid invalid
  16858. // indices
  16859. result.insert(result.begin() + end_index, object(
  16860. {
  16861. {"op", "remove"},
  16862. {"path", path + "/" + std::to_string(i)}
  16863. }));
  16864. ++i;
  16865. }
  16866. // add other remaining elements
  16867. while (i < target.size())
  16868. {
  16869. result.push_back(
  16870. {
  16871. {"op", "add"},
  16872. {"path", path + "/" + std::to_string(i)},
  16873. {"value", target[i]}
  16874. });
  16875. ++i;
  16876. }
  16877. break;
  16878. }
  16879. case value_t::object:
  16880. {
  16881. // first pass: traverse this object's elements
  16882. for (auto it = source.cbegin(); it != source.cend(); ++it)
  16883. {
  16884. // escape the key name to be used in a JSON patch
  16885. const auto key = json_pointer::escape(it.key());
  16886. if (target.find(it.key()) != target.end())
  16887. {
  16888. // recursive call to compare object values at key it
  16889. auto temp_diff = diff(it.value(), target[it.key()], path + "/" + key);
  16890. result.insert(result.end(), temp_diff.begin(), temp_diff.end());
  16891. }
  16892. else
  16893. {
  16894. // found a key that is not in o -> remove it
  16895. result.push_back(object(
  16896. {
  16897. {"op", "remove"}, {"path", path + "/" + key}
  16898. }));
  16899. }
  16900. }
  16901. // second pass: traverse other object's elements
  16902. for (auto it = target.cbegin(); it != target.cend(); ++it)
  16903. {
  16904. if (source.find(it.key()) == source.end())
  16905. {
  16906. // found a key that is not in this -> add it
  16907. const auto key = json_pointer::escape(it.key());
  16908. result.push_back(
  16909. {
  16910. {"op", "add"}, {"path", path + "/" + key},
  16911. {"value", it.value()}
  16912. });
  16913. }
  16914. }
  16915. break;
  16916. }
  16917. default:
  16918. {
  16919. // both primitive type: replace value
  16920. result.push_back(
  16921. {
  16922. {"op", "replace"}, {"path", path}, {"value", target}
  16923. });
  16924. break;
  16925. }
  16926. }
  16927. }
  16928. return result;
  16929. }
  16930. /// @}
  16931. ////////////////////////////////
  16932. // JSON Merge Patch functions //
  16933. ////////////////////////////////
  16934. /// @name JSON Merge Patch functions
  16935. /// @{
  16936. /*!
  16937. @brief applies a JSON Merge Patch
  16938. The merge patch format is primarily intended for use with the HTTP PATCH
  16939. method as a means of describing a set of modifications to a target
  16940. resource's content. This function applies a merge patch to the current
  16941. JSON value.
  16942. The function implements the following algorithm from Section 2 of
  16943. [RFC 7396 (JSON Merge Patch)](https://tools.ietf.org/html/rfc7396):
  16944. ```
  16945. define MergePatch(Target, Patch):
  16946. if Patch is an Object:
  16947. if Target is not an Object:
  16948. Target = {} // Ignore the contents and set it to an empty Object
  16949. for each Name/Value pair in Patch:
  16950. if Value is null:
  16951. if Name exists in Target:
  16952. remove the Name/Value pair from Target
  16953. else:
  16954. Target[Name] = MergePatch(Target[Name], Value)
  16955. return Target
  16956. else:
  16957. return Patch
  16958. ```
  16959. Thereby, `Target` is the current object; that is, the patch is applied to
  16960. the current value.
  16961. @param[in] apply_patch the patch to apply
  16962. @complexity Linear in the lengths of @a patch.
  16963. @liveexample{The following code shows how a JSON Merge Patch is applied to
  16964. a JSON document.,merge_patch}
  16965. @sa @ref patch -- apply a JSON patch
  16966. @sa [RFC 7396 (JSON Merge Patch)](https://tools.ietf.org/html/rfc7396)
  16967. @since version 3.0.0
  16968. */
  16969. void merge_patch(const basic_json& apply_patch)
  16970. {
  16971. if (apply_patch.is_object())
  16972. {
  16973. if (not is_object())
  16974. {
  16975. *this = object();
  16976. }
  16977. for (auto it = apply_patch.begin(); it != apply_patch.end(); ++it)
  16978. {
  16979. if (it.value().is_null())
  16980. {
  16981. erase(it.key());
  16982. }
  16983. else
  16984. {
  16985. operator[](it.key()).merge_patch(it.value());
  16986. }
  16987. }
  16988. }
  16989. else
  16990. {
  16991. *this = apply_patch;
  16992. }
  16993. }
  16994. /// @}
  16995. };
  16996. } // namespace nlohmann
  16997. ///////////////////////
  16998. // nonmember support //
  16999. ///////////////////////
  17000. // specialization of std::swap, and std::hash
  17001. namespace std
  17002. {
  17003. /// hash value for JSON objects
  17004. template<>
  17005. struct hash<nlohmann::json>
  17006. {
  17007. /*!
  17008. @brief return a hash value for a JSON object
  17009. @since version 1.0.0
  17010. */
  17011. std::size_t operator()(const nlohmann::json& j) const
  17012. {
  17013. // a naive hashing via the string representation
  17014. const auto& h = hash<nlohmann::json::string_t>();
  17015. return h(j.dump());
  17016. }
  17017. };
  17018. /// specialization for std::less<value_t>
  17019. /// @note: do not remove the space after '<',
  17020. /// see https://github.com/nlohmann/json/pull/679
  17021. template<>
  17022. struct less< ::nlohmann::detail::value_t>
  17023. {
  17024. /*!
  17025. @brief compare two value_t enum values
  17026. @since version 3.0.0
  17027. */
  17028. bool operator()(nlohmann::detail::value_t lhs,
  17029. nlohmann::detail::value_t rhs) const noexcept
  17030. {
  17031. return nlohmann::detail::operator<(lhs, rhs);
  17032. }
  17033. };
  17034. /*!
  17035. @brief exchanges the values of two JSON objects
  17036. @since version 1.0.0
  17037. */
  17038. template<>
  17039. inline void swap<nlohmann::json>(nlohmann::json& j1, nlohmann::json& j2) noexcept(
  17040. is_nothrow_move_constructible<nlohmann::json>::value and
  17041. is_nothrow_move_assignable<nlohmann::json>::value
  17042. )
  17043. {
  17044. j1.swap(j2);
  17045. }
  17046. } // namespace std
  17047. /*!
  17048. @brief user-defined string literal for JSON values
  17049. This operator implements a user-defined string literal for JSON objects. It
  17050. can be used by adding `"_json"` to a string literal and returns a JSON object
  17051. if no parse error occurred.
  17052. @param[in] s a string representation of a JSON object
  17053. @param[in] n the length of string @a s
  17054. @return a JSON object
  17055. @since version 1.0.0
  17056. */
  17057. inline nlohmann::json operator "" _json(const char* s, std::size_t n)
  17058. {
  17059. return nlohmann::json::parse(s, s + n);
  17060. }
  17061. /*!
  17062. @brief user-defined string literal for JSON pointer
  17063. This operator implements a user-defined string literal for JSON Pointers. It
  17064. can be used by adding `"_json_pointer"` to a string literal and returns a JSON pointer
  17065. object if no parse error occurred.
  17066. @param[in] s a string representation of a JSON Pointer
  17067. @param[in] n the length of string @a s
  17068. @return a JSON pointer object
  17069. @since version 2.0.0
  17070. */
  17071. inline nlohmann::json::json_pointer operator "" _json_pointer(const char* s, std::size_t n)
  17072. {
  17073. return nlohmann::json::json_pointer(std::string(s, n));
  17074. }
  17075. // #include <nlohmann/detail/macro_unscope.hpp>
  17076. // restore GCC/clang diagnostic settings
  17077. #if defined(__clang__) || defined(__GNUC__) || defined(__GNUG__)
  17078. #pragma GCC diagnostic pop
  17079. #endif
  17080. #if defined(__clang__)
  17081. #pragma GCC diagnostic pop
  17082. #endif
  17083. // clean up
  17084. #undef JSON_INTERNAL_CATCH
  17085. #undef JSON_CATCH
  17086. #undef JSON_THROW
  17087. #undef JSON_TRY
  17088. #undef JSON_LIKELY
  17089. #undef JSON_UNLIKELY
  17090. #undef JSON_DEPRECATED
  17091. #undef JSON_HAS_CPP_14
  17092. #undef JSON_HAS_CPP_17
  17093. #undef NLOHMANN_BASIC_JSON_TPL_DECLARATION
  17094. #undef NLOHMANN_BASIC_JSON_TPL
  17095. #endif