json.hpp 960 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753
  1. /*
  2. __ _____ _____ _____
  3. __| | __| | | | JSON for Modern C++
  4. | | |__ | | | | | | version 3.10.4
  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-2019 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 INCLUDE_NLOHMANN_JSON_HPP_
  26. #define INCLUDE_NLOHMANN_JSON_HPP_
  27. #define NLOHMANN_JSON_VERSION_MAJOR 3
  28. #define NLOHMANN_JSON_VERSION_MINOR 10
  29. #define NLOHMANN_JSON_VERSION_PATCH 4
  30. #include <algorithm> // all_of, find, for_each
  31. #include <cstddef> // nullptr_t, ptrdiff_t, size_t
  32. #include <functional> // hash, less
  33. #include <initializer_list> // initializer_list
  34. #ifndef JSON_NO_IO
  35. #include <iosfwd> // istream, ostream
  36. #endif // JSON_NO_IO
  37. #include <iterator> // random_access_iterator_tag
  38. #include <memory> // unique_ptr
  39. #include <numeric> // accumulate
  40. #include <string> // string, stoi, to_string
  41. #include <utility> // declval, forward, move, pair, swap
  42. #include <vector> // vector
  43. // #include <nlohmann/adl_serializer.hpp>
  44. #include <type_traits>
  45. #include <utility>
  46. // #include <nlohmann/detail/conversions/from_json.hpp>
  47. #include <algorithm> // transform
  48. #include <array> // array
  49. #include <forward_list> // forward_list
  50. #include <iterator> // inserter, front_inserter, end
  51. #include <map> // map
  52. #include <string> // string
  53. #include <tuple> // tuple, make_tuple
  54. #include <type_traits> // is_arithmetic, is_same, is_enum, underlying_type, is_convertible
  55. #include <unordered_map> // unordered_map
  56. #include <utility> // pair, declval
  57. #include <valarray> // valarray
  58. // #include <nlohmann/detail/exceptions.hpp>
  59. #include <exception> // exception
  60. #include <stdexcept> // runtime_error
  61. #include <string> // to_string
  62. #include <vector> // vector
  63. // #include <nlohmann/detail/value_t.hpp>
  64. #include <array> // array
  65. #include <cstddef> // size_t
  66. #include <cstdint> // uint8_t
  67. #include <string> // string
  68. namespace nlohmann
  69. {
  70. namespace detail
  71. {
  72. ///////////////////////////
  73. // JSON type enumeration //
  74. ///////////////////////////
  75. /*!
  76. @brief the JSON type enumeration
  77. This enumeration collects the different JSON types. It is internally used to
  78. distinguish the stored values, and the functions @ref basic_json::is_null(),
  79. @ref basic_json::is_object(), @ref basic_json::is_array(),
  80. @ref basic_json::is_string(), @ref basic_json::is_boolean(),
  81. @ref basic_json::is_number() (with @ref basic_json::is_number_integer(),
  82. @ref basic_json::is_number_unsigned(), and @ref basic_json::is_number_float()),
  83. @ref basic_json::is_discarded(), @ref basic_json::is_primitive(), and
  84. @ref basic_json::is_structured() rely on it.
  85. @note There are three enumeration entries (number_integer, number_unsigned, and
  86. number_float), because the library distinguishes these three types for numbers:
  87. @ref basic_json::number_unsigned_t is used for unsigned integers,
  88. @ref basic_json::number_integer_t is used for signed integers, and
  89. @ref basic_json::number_float_t is used for floating-point numbers or to
  90. approximate integers which do not fit in the limits of their respective type.
  91. @sa see @ref basic_json::basic_json(const value_t value_type) -- create a JSON
  92. value with the default value for a given type
  93. @since version 1.0.0
  94. */
  95. enum class value_t : std::uint8_t
  96. {
  97. null, ///< null value
  98. object, ///< object (unordered set of name/value pairs)
  99. array, ///< array (ordered collection of values)
  100. string, ///< string value
  101. boolean, ///< boolean value
  102. number_integer, ///< number value (signed integer)
  103. number_unsigned, ///< number value (unsigned integer)
  104. number_float, ///< number value (floating-point)
  105. binary, ///< binary array (ordered collection of bytes)
  106. discarded ///< discarded by the parser callback function
  107. };
  108. /*!
  109. @brief comparison operator for JSON types
  110. Returns an ordering that is similar to Python:
  111. - order: null < boolean < number < object < array < string < binary
  112. - furthermore, each type is not smaller than itself
  113. - discarded values are not comparable
  114. - binary is represented as a b"" string in python and directly comparable to a
  115. string; however, making a binary array directly comparable with a string would
  116. be surprising behavior in a JSON file.
  117. @since version 1.0.0
  118. */
  119. inline bool operator<(const value_t lhs, const value_t rhs) noexcept
  120. {
  121. static constexpr std::array<std::uint8_t, 9> order = {{
  122. 0 /* null */, 3 /* object */, 4 /* array */, 5 /* string */,
  123. 1 /* boolean */, 2 /* integer */, 2 /* unsigned */, 2 /* float */,
  124. 6 /* binary */
  125. }
  126. };
  127. const auto l_index = static_cast<std::size_t>(lhs);
  128. const auto r_index = static_cast<std::size_t>(rhs);
  129. return l_index < order.size() && r_index < order.size() && order[l_index] < order[r_index];
  130. }
  131. } // namespace detail
  132. } // namespace nlohmann
  133. // #include <nlohmann/detail/string_escape.hpp>
  134. #include <string>
  135. // #include <nlohmann/detail/macro_scope.hpp>
  136. #include <utility> // declval, pair
  137. // #include <nlohmann/thirdparty/hedley/hedley.hpp>
  138. /* Hedley - https://nemequ.github.io/hedley
  139. * Created by Evan Nemerson <[email protected]>
  140. *
  141. * To the extent possible under law, the author(s) have dedicated all
  142. * copyright and related and neighboring rights to this software to
  143. * the public domain worldwide. This software is distributed without
  144. * any warranty.
  145. *
  146. * For details, see <http://creativecommons.org/publicdomain/zero/1.0/>.
  147. * SPDX-License-Identifier: CC0-1.0
  148. */
  149. #if !defined(JSON_HEDLEY_VERSION) || (JSON_HEDLEY_VERSION < 15)
  150. #if defined(JSON_HEDLEY_VERSION)
  151. #undef JSON_HEDLEY_VERSION
  152. #endif
  153. #define JSON_HEDLEY_VERSION 15
  154. #if defined(JSON_HEDLEY_STRINGIFY_EX)
  155. #undef JSON_HEDLEY_STRINGIFY_EX
  156. #endif
  157. #define JSON_HEDLEY_STRINGIFY_EX(x) #x
  158. #if defined(JSON_HEDLEY_STRINGIFY)
  159. #undef JSON_HEDLEY_STRINGIFY
  160. #endif
  161. #define JSON_HEDLEY_STRINGIFY(x) JSON_HEDLEY_STRINGIFY_EX(x)
  162. #if defined(JSON_HEDLEY_CONCAT_EX)
  163. #undef JSON_HEDLEY_CONCAT_EX
  164. #endif
  165. #define JSON_HEDLEY_CONCAT_EX(a,b) a##b
  166. #if defined(JSON_HEDLEY_CONCAT)
  167. #undef JSON_HEDLEY_CONCAT
  168. #endif
  169. #define JSON_HEDLEY_CONCAT(a,b) JSON_HEDLEY_CONCAT_EX(a,b)
  170. #if defined(JSON_HEDLEY_CONCAT3_EX)
  171. #undef JSON_HEDLEY_CONCAT3_EX
  172. #endif
  173. #define JSON_HEDLEY_CONCAT3_EX(a,b,c) a##b##c
  174. #if defined(JSON_HEDLEY_CONCAT3)
  175. #undef JSON_HEDLEY_CONCAT3
  176. #endif
  177. #define JSON_HEDLEY_CONCAT3(a,b,c) JSON_HEDLEY_CONCAT3_EX(a,b,c)
  178. #if defined(JSON_HEDLEY_VERSION_ENCODE)
  179. #undef JSON_HEDLEY_VERSION_ENCODE
  180. #endif
  181. #define JSON_HEDLEY_VERSION_ENCODE(major,minor,revision) (((major) * 1000000) + ((minor) * 1000) + (revision))
  182. #if defined(JSON_HEDLEY_VERSION_DECODE_MAJOR)
  183. #undef JSON_HEDLEY_VERSION_DECODE_MAJOR
  184. #endif
  185. #define JSON_HEDLEY_VERSION_DECODE_MAJOR(version) ((version) / 1000000)
  186. #if defined(JSON_HEDLEY_VERSION_DECODE_MINOR)
  187. #undef JSON_HEDLEY_VERSION_DECODE_MINOR
  188. #endif
  189. #define JSON_HEDLEY_VERSION_DECODE_MINOR(version) (((version) % 1000000) / 1000)
  190. #if defined(JSON_HEDLEY_VERSION_DECODE_REVISION)
  191. #undef JSON_HEDLEY_VERSION_DECODE_REVISION
  192. #endif
  193. #define JSON_HEDLEY_VERSION_DECODE_REVISION(version) ((version) % 1000)
  194. #if defined(JSON_HEDLEY_GNUC_VERSION)
  195. #undef JSON_HEDLEY_GNUC_VERSION
  196. #endif
  197. #if defined(__GNUC__) && defined(__GNUC_PATCHLEVEL__)
  198. #define JSON_HEDLEY_GNUC_VERSION JSON_HEDLEY_VERSION_ENCODE(__GNUC__, __GNUC_MINOR__, __GNUC_PATCHLEVEL__)
  199. #elif defined(__GNUC__)
  200. #define JSON_HEDLEY_GNUC_VERSION JSON_HEDLEY_VERSION_ENCODE(__GNUC__, __GNUC_MINOR__, 0)
  201. #endif
  202. #if defined(JSON_HEDLEY_GNUC_VERSION_CHECK)
  203. #undef JSON_HEDLEY_GNUC_VERSION_CHECK
  204. #endif
  205. #if defined(JSON_HEDLEY_GNUC_VERSION)
  206. #define JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_GNUC_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
  207. #else
  208. #define JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch) (0)
  209. #endif
  210. #if defined(JSON_HEDLEY_MSVC_VERSION)
  211. #undef JSON_HEDLEY_MSVC_VERSION
  212. #endif
  213. #if defined(_MSC_FULL_VER) && (_MSC_FULL_VER >= 140000000) && !defined(__ICL)
  214. #define JSON_HEDLEY_MSVC_VERSION JSON_HEDLEY_VERSION_ENCODE(_MSC_FULL_VER / 10000000, (_MSC_FULL_VER % 10000000) / 100000, (_MSC_FULL_VER % 100000) / 100)
  215. #elif defined(_MSC_FULL_VER) && !defined(__ICL)
  216. #define JSON_HEDLEY_MSVC_VERSION JSON_HEDLEY_VERSION_ENCODE(_MSC_FULL_VER / 1000000, (_MSC_FULL_VER % 1000000) / 10000, (_MSC_FULL_VER % 10000) / 10)
  217. #elif defined(_MSC_VER) && !defined(__ICL)
  218. #define JSON_HEDLEY_MSVC_VERSION JSON_HEDLEY_VERSION_ENCODE(_MSC_VER / 100, _MSC_VER % 100, 0)
  219. #endif
  220. #if defined(JSON_HEDLEY_MSVC_VERSION_CHECK)
  221. #undef JSON_HEDLEY_MSVC_VERSION_CHECK
  222. #endif
  223. #if !defined(JSON_HEDLEY_MSVC_VERSION)
  224. #define JSON_HEDLEY_MSVC_VERSION_CHECK(major,minor,patch) (0)
  225. #elif defined(_MSC_VER) && (_MSC_VER >= 1400)
  226. #define JSON_HEDLEY_MSVC_VERSION_CHECK(major,minor,patch) (_MSC_FULL_VER >= ((major * 10000000) + (minor * 100000) + (patch)))
  227. #elif defined(_MSC_VER) && (_MSC_VER >= 1200)
  228. #define JSON_HEDLEY_MSVC_VERSION_CHECK(major,minor,patch) (_MSC_FULL_VER >= ((major * 1000000) + (minor * 10000) + (patch)))
  229. #else
  230. #define JSON_HEDLEY_MSVC_VERSION_CHECK(major,minor,patch) (_MSC_VER >= ((major * 100) + (minor)))
  231. #endif
  232. #if defined(JSON_HEDLEY_INTEL_VERSION)
  233. #undef JSON_HEDLEY_INTEL_VERSION
  234. #endif
  235. #if defined(__INTEL_COMPILER) && defined(__INTEL_COMPILER_UPDATE) && !defined(__ICL)
  236. #define JSON_HEDLEY_INTEL_VERSION JSON_HEDLEY_VERSION_ENCODE(__INTEL_COMPILER / 100, __INTEL_COMPILER % 100, __INTEL_COMPILER_UPDATE)
  237. #elif defined(__INTEL_COMPILER) && !defined(__ICL)
  238. #define JSON_HEDLEY_INTEL_VERSION JSON_HEDLEY_VERSION_ENCODE(__INTEL_COMPILER / 100, __INTEL_COMPILER % 100, 0)
  239. #endif
  240. #if defined(JSON_HEDLEY_INTEL_VERSION_CHECK)
  241. #undef JSON_HEDLEY_INTEL_VERSION_CHECK
  242. #endif
  243. #if defined(JSON_HEDLEY_INTEL_VERSION)
  244. #define JSON_HEDLEY_INTEL_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_INTEL_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
  245. #else
  246. #define JSON_HEDLEY_INTEL_VERSION_CHECK(major,minor,patch) (0)
  247. #endif
  248. #if defined(JSON_HEDLEY_INTEL_CL_VERSION)
  249. #undef JSON_HEDLEY_INTEL_CL_VERSION
  250. #endif
  251. #if defined(__INTEL_COMPILER) && defined(__INTEL_COMPILER_UPDATE) && defined(__ICL)
  252. #define JSON_HEDLEY_INTEL_CL_VERSION JSON_HEDLEY_VERSION_ENCODE(__INTEL_COMPILER, __INTEL_COMPILER_UPDATE, 0)
  253. #endif
  254. #if defined(JSON_HEDLEY_INTEL_CL_VERSION_CHECK)
  255. #undef JSON_HEDLEY_INTEL_CL_VERSION_CHECK
  256. #endif
  257. #if defined(JSON_HEDLEY_INTEL_CL_VERSION)
  258. #define JSON_HEDLEY_INTEL_CL_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_INTEL_CL_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
  259. #else
  260. #define JSON_HEDLEY_INTEL_CL_VERSION_CHECK(major,minor,patch) (0)
  261. #endif
  262. #if defined(JSON_HEDLEY_PGI_VERSION)
  263. #undef JSON_HEDLEY_PGI_VERSION
  264. #endif
  265. #if defined(__PGI) && defined(__PGIC__) && defined(__PGIC_MINOR__) && defined(__PGIC_PATCHLEVEL__)
  266. #define JSON_HEDLEY_PGI_VERSION JSON_HEDLEY_VERSION_ENCODE(__PGIC__, __PGIC_MINOR__, __PGIC_PATCHLEVEL__)
  267. #endif
  268. #if defined(JSON_HEDLEY_PGI_VERSION_CHECK)
  269. #undef JSON_HEDLEY_PGI_VERSION_CHECK
  270. #endif
  271. #if defined(JSON_HEDLEY_PGI_VERSION)
  272. #define JSON_HEDLEY_PGI_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_PGI_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
  273. #else
  274. #define JSON_HEDLEY_PGI_VERSION_CHECK(major,minor,patch) (0)
  275. #endif
  276. #if defined(JSON_HEDLEY_SUNPRO_VERSION)
  277. #undef JSON_HEDLEY_SUNPRO_VERSION
  278. #endif
  279. #if defined(__SUNPRO_C) && (__SUNPRO_C > 0x1000)
  280. #define JSON_HEDLEY_SUNPRO_VERSION JSON_HEDLEY_VERSION_ENCODE((((__SUNPRO_C >> 16) & 0xf) * 10) + ((__SUNPRO_C >> 12) & 0xf), (((__SUNPRO_C >> 8) & 0xf) * 10) + ((__SUNPRO_C >> 4) & 0xf), (__SUNPRO_C & 0xf) * 10)
  281. #elif defined(__SUNPRO_C)
  282. #define JSON_HEDLEY_SUNPRO_VERSION JSON_HEDLEY_VERSION_ENCODE((__SUNPRO_C >> 8) & 0xf, (__SUNPRO_C >> 4) & 0xf, (__SUNPRO_C) & 0xf)
  283. #elif defined(__SUNPRO_CC) && (__SUNPRO_CC > 0x1000)
  284. #define JSON_HEDLEY_SUNPRO_VERSION JSON_HEDLEY_VERSION_ENCODE((((__SUNPRO_CC >> 16) & 0xf) * 10) + ((__SUNPRO_CC >> 12) & 0xf), (((__SUNPRO_CC >> 8) & 0xf) * 10) + ((__SUNPRO_CC >> 4) & 0xf), (__SUNPRO_CC & 0xf) * 10)
  285. #elif defined(__SUNPRO_CC)
  286. #define JSON_HEDLEY_SUNPRO_VERSION JSON_HEDLEY_VERSION_ENCODE((__SUNPRO_CC >> 8) & 0xf, (__SUNPRO_CC >> 4) & 0xf, (__SUNPRO_CC) & 0xf)
  287. #endif
  288. #if defined(JSON_HEDLEY_SUNPRO_VERSION_CHECK)
  289. #undef JSON_HEDLEY_SUNPRO_VERSION_CHECK
  290. #endif
  291. #if defined(JSON_HEDLEY_SUNPRO_VERSION)
  292. #define JSON_HEDLEY_SUNPRO_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_SUNPRO_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
  293. #else
  294. #define JSON_HEDLEY_SUNPRO_VERSION_CHECK(major,minor,patch) (0)
  295. #endif
  296. #if defined(JSON_HEDLEY_EMSCRIPTEN_VERSION)
  297. #undef JSON_HEDLEY_EMSCRIPTEN_VERSION
  298. #endif
  299. #if defined(__EMSCRIPTEN__)
  300. #define JSON_HEDLEY_EMSCRIPTEN_VERSION JSON_HEDLEY_VERSION_ENCODE(__EMSCRIPTEN_major__, __EMSCRIPTEN_minor__, __EMSCRIPTEN_tiny__)
  301. #endif
  302. #if defined(JSON_HEDLEY_EMSCRIPTEN_VERSION_CHECK)
  303. #undef JSON_HEDLEY_EMSCRIPTEN_VERSION_CHECK
  304. #endif
  305. #if defined(JSON_HEDLEY_EMSCRIPTEN_VERSION)
  306. #define JSON_HEDLEY_EMSCRIPTEN_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_EMSCRIPTEN_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
  307. #else
  308. #define JSON_HEDLEY_EMSCRIPTEN_VERSION_CHECK(major,minor,patch) (0)
  309. #endif
  310. #if defined(JSON_HEDLEY_ARM_VERSION)
  311. #undef JSON_HEDLEY_ARM_VERSION
  312. #endif
  313. #if defined(__CC_ARM) && defined(__ARMCOMPILER_VERSION)
  314. #define JSON_HEDLEY_ARM_VERSION JSON_HEDLEY_VERSION_ENCODE(__ARMCOMPILER_VERSION / 1000000, (__ARMCOMPILER_VERSION % 1000000) / 10000, (__ARMCOMPILER_VERSION % 10000) / 100)
  315. #elif defined(__CC_ARM) && defined(__ARMCC_VERSION)
  316. #define JSON_HEDLEY_ARM_VERSION JSON_HEDLEY_VERSION_ENCODE(__ARMCC_VERSION / 1000000, (__ARMCC_VERSION % 1000000) / 10000, (__ARMCC_VERSION % 10000) / 100)
  317. #endif
  318. #if defined(JSON_HEDLEY_ARM_VERSION_CHECK)
  319. #undef JSON_HEDLEY_ARM_VERSION_CHECK
  320. #endif
  321. #if defined(JSON_HEDLEY_ARM_VERSION)
  322. #define JSON_HEDLEY_ARM_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_ARM_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
  323. #else
  324. #define JSON_HEDLEY_ARM_VERSION_CHECK(major,minor,patch) (0)
  325. #endif
  326. #if defined(JSON_HEDLEY_IBM_VERSION)
  327. #undef JSON_HEDLEY_IBM_VERSION
  328. #endif
  329. #if defined(__ibmxl__)
  330. #define JSON_HEDLEY_IBM_VERSION JSON_HEDLEY_VERSION_ENCODE(__ibmxl_version__, __ibmxl_release__, __ibmxl_modification__)
  331. #elif defined(__xlC__) && defined(__xlC_ver__)
  332. #define JSON_HEDLEY_IBM_VERSION JSON_HEDLEY_VERSION_ENCODE(__xlC__ >> 8, __xlC__ & 0xff, (__xlC_ver__ >> 8) & 0xff)
  333. #elif defined(__xlC__)
  334. #define JSON_HEDLEY_IBM_VERSION JSON_HEDLEY_VERSION_ENCODE(__xlC__ >> 8, __xlC__ & 0xff, 0)
  335. #endif
  336. #if defined(JSON_HEDLEY_IBM_VERSION_CHECK)
  337. #undef JSON_HEDLEY_IBM_VERSION_CHECK
  338. #endif
  339. #if defined(JSON_HEDLEY_IBM_VERSION)
  340. #define JSON_HEDLEY_IBM_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_IBM_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
  341. #else
  342. #define JSON_HEDLEY_IBM_VERSION_CHECK(major,minor,patch) (0)
  343. #endif
  344. #if defined(JSON_HEDLEY_TI_VERSION)
  345. #undef JSON_HEDLEY_TI_VERSION
  346. #endif
  347. #if \
  348. defined(__TI_COMPILER_VERSION__) && \
  349. ( \
  350. defined(__TMS470__) || defined(__TI_ARM__) || \
  351. defined(__MSP430__) || \
  352. defined(__TMS320C2000__) \
  353. )
  354. #if (__TI_COMPILER_VERSION__ >= 16000000)
  355. #define JSON_HEDLEY_TI_VERSION JSON_HEDLEY_VERSION_ENCODE(__TI_COMPILER_VERSION__ / 1000000, (__TI_COMPILER_VERSION__ % 1000000) / 1000, (__TI_COMPILER_VERSION__ % 1000))
  356. #endif
  357. #endif
  358. #if defined(JSON_HEDLEY_TI_VERSION_CHECK)
  359. #undef JSON_HEDLEY_TI_VERSION_CHECK
  360. #endif
  361. #if defined(JSON_HEDLEY_TI_VERSION)
  362. #define JSON_HEDLEY_TI_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_TI_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
  363. #else
  364. #define JSON_HEDLEY_TI_VERSION_CHECK(major,minor,patch) (0)
  365. #endif
  366. #if defined(JSON_HEDLEY_TI_CL2000_VERSION)
  367. #undef JSON_HEDLEY_TI_CL2000_VERSION
  368. #endif
  369. #if defined(__TI_COMPILER_VERSION__) && defined(__TMS320C2000__)
  370. #define JSON_HEDLEY_TI_CL2000_VERSION JSON_HEDLEY_VERSION_ENCODE(__TI_COMPILER_VERSION__ / 1000000, (__TI_COMPILER_VERSION__ % 1000000) / 1000, (__TI_COMPILER_VERSION__ % 1000))
  371. #endif
  372. #if defined(JSON_HEDLEY_TI_CL2000_VERSION_CHECK)
  373. #undef JSON_HEDLEY_TI_CL2000_VERSION_CHECK
  374. #endif
  375. #if defined(JSON_HEDLEY_TI_CL2000_VERSION)
  376. #define JSON_HEDLEY_TI_CL2000_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_TI_CL2000_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
  377. #else
  378. #define JSON_HEDLEY_TI_CL2000_VERSION_CHECK(major,minor,patch) (0)
  379. #endif
  380. #if defined(JSON_HEDLEY_TI_CL430_VERSION)
  381. #undef JSON_HEDLEY_TI_CL430_VERSION
  382. #endif
  383. #if defined(__TI_COMPILER_VERSION__) && defined(__MSP430__)
  384. #define JSON_HEDLEY_TI_CL430_VERSION JSON_HEDLEY_VERSION_ENCODE(__TI_COMPILER_VERSION__ / 1000000, (__TI_COMPILER_VERSION__ % 1000000) / 1000, (__TI_COMPILER_VERSION__ % 1000))
  385. #endif
  386. #if defined(JSON_HEDLEY_TI_CL430_VERSION_CHECK)
  387. #undef JSON_HEDLEY_TI_CL430_VERSION_CHECK
  388. #endif
  389. #if defined(JSON_HEDLEY_TI_CL430_VERSION)
  390. #define JSON_HEDLEY_TI_CL430_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_TI_CL430_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
  391. #else
  392. #define JSON_HEDLEY_TI_CL430_VERSION_CHECK(major,minor,patch) (0)
  393. #endif
  394. #if defined(JSON_HEDLEY_TI_ARMCL_VERSION)
  395. #undef JSON_HEDLEY_TI_ARMCL_VERSION
  396. #endif
  397. #if defined(__TI_COMPILER_VERSION__) && (defined(__TMS470__) || defined(__TI_ARM__))
  398. #define JSON_HEDLEY_TI_ARMCL_VERSION JSON_HEDLEY_VERSION_ENCODE(__TI_COMPILER_VERSION__ / 1000000, (__TI_COMPILER_VERSION__ % 1000000) / 1000, (__TI_COMPILER_VERSION__ % 1000))
  399. #endif
  400. #if defined(JSON_HEDLEY_TI_ARMCL_VERSION_CHECK)
  401. #undef JSON_HEDLEY_TI_ARMCL_VERSION_CHECK
  402. #endif
  403. #if defined(JSON_HEDLEY_TI_ARMCL_VERSION)
  404. #define JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_TI_ARMCL_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
  405. #else
  406. #define JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(major,minor,patch) (0)
  407. #endif
  408. #if defined(JSON_HEDLEY_TI_CL6X_VERSION)
  409. #undef JSON_HEDLEY_TI_CL6X_VERSION
  410. #endif
  411. #if defined(__TI_COMPILER_VERSION__) && defined(__TMS320C6X__)
  412. #define JSON_HEDLEY_TI_CL6X_VERSION JSON_HEDLEY_VERSION_ENCODE(__TI_COMPILER_VERSION__ / 1000000, (__TI_COMPILER_VERSION__ % 1000000) / 1000, (__TI_COMPILER_VERSION__ % 1000))
  413. #endif
  414. #if defined(JSON_HEDLEY_TI_CL6X_VERSION_CHECK)
  415. #undef JSON_HEDLEY_TI_CL6X_VERSION_CHECK
  416. #endif
  417. #if defined(JSON_HEDLEY_TI_CL6X_VERSION)
  418. #define JSON_HEDLEY_TI_CL6X_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_TI_CL6X_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
  419. #else
  420. #define JSON_HEDLEY_TI_CL6X_VERSION_CHECK(major,minor,patch) (0)
  421. #endif
  422. #if defined(JSON_HEDLEY_TI_CL7X_VERSION)
  423. #undef JSON_HEDLEY_TI_CL7X_VERSION
  424. #endif
  425. #if defined(__TI_COMPILER_VERSION__) && defined(__C7000__)
  426. #define JSON_HEDLEY_TI_CL7X_VERSION JSON_HEDLEY_VERSION_ENCODE(__TI_COMPILER_VERSION__ / 1000000, (__TI_COMPILER_VERSION__ % 1000000) / 1000, (__TI_COMPILER_VERSION__ % 1000))
  427. #endif
  428. #if defined(JSON_HEDLEY_TI_CL7X_VERSION_CHECK)
  429. #undef JSON_HEDLEY_TI_CL7X_VERSION_CHECK
  430. #endif
  431. #if defined(JSON_HEDLEY_TI_CL7X_VERSION)
  432. #define JSON_HEDLEY_TI_CL7X_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_TI_CL7X_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
  433. #else
  434. #define JSON_HEDLEY_TI_CL7X_VERSION_CHECK(major,minor,patch) (0)
  435. #endif
  436. #if defined(JSON_HEDLEY_TI_CLPRU_VERSION)
  437. #undef JSON_HEDLEY_TI_CLPRU_VERSION
  438. #endif
  439. #if defined(__TI_COMPILER_VERSION__) && defined(__PRU__)
  440. #define JSON_HEDLEY_TI_CLPRU_VERSION JSON_HEDLEY_VERSION_ENCODE(__TI_COMPILER_VERSION__ / 1000000, (__TI_COMPILER_VERSION__ % 1000000) / 1000, (__TI_COMPILER_VERSION__ % 1000))
  441. #endif
  442. #if defined(JSON_HEDLEY_TI_CLPRU_VERSION_CHECK)
  443. #undef JSON_HEDLEY_TI_CLPRU_VERSION_CHECK
  444. #endif
  445. #if defined(JSON_HEDLEY_TI_CLPRU_VERSION)
  446. #define JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_TI_CLPRU_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
  447. #else
  448. #define JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(major,minor,patch) (0)
  449. #endif
  450. #if defined(JSON_HEDLEY_CRAY_VERSION)
  451. #undef JSON_HEDLEY_CRAY_VERSION
  452. #endif
  453. #if defined(_CRAYC)
  454. #if defined(_RELEASE_PATCHLEVEL)
  455. #define JSON_HEDLEY_CRAY_VERSION JSON_HEDLEY_VERSION_ENCODE(_RELEASE_MAJOR, _RELEASE_MINOR, _RELEASE_PATCHLEVEL)
  456. #else
  457. #define JSON_HEDLEY_CRAY_VERSION JSON_HEDLEY_VERSION_ENCODE(_RELEASE_MAJOR, _RELEASE_MINOR, 0)
  458. #endif
  459. #endif
  460. #if defined(JSON_HEDLEY_CRAY_VERSION_CHECK)
  461. #undef JSON_HEDLEY_CRAY_VERSION_CHECK
  462. #endif
  463. #if defined(JSON_HEDLEY_CRAY_VERSION)
  464. #define JSON_HEDLEY_CRAY_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_CRAY_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
  465. #else
  466. #define JSON_HEDLEY_CRAY_VERSION_CHECK(major,minor,patch) (0)
  467. #endif
  468. #if defined(JSON_HEDLEY_IAR_VERSION)
  469. #undef JSON_HEDLEY_IAR_VERSION
  470. #endif
  471. #if defined(__IAR_SYSTEMS_ICC__)
  472. #if __VER__ > 1000
  473. #define JSON_HEDLEY_IAR_VERSION JSON_HEDLEY_VERSION_ENCODE((__VER__ / 1000000), ((__VER__ / 1000) % 1000), (__VER__ % 1000))
  474. #else
  475. #define JSON_HEDLEY_IAR_VERSION JSON_HEDLEY_VERSION_ENCODE(__VER__ / 100, __VER__ % 100, 0)
  476. #endif
  477. #endif
  478. #if defined(JSON_HEDLEY_IAR_VERSION_CHECK)
  479. #undef JSON_HEDLEY_IAR_VERSION_CHECK
  480. #endif
  481. #if defined(JSON_HEDLEY_IAR_VERSION)
  482. #define JSON_HEDLEY_IAR_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_IAR_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
  483. #else
  484. #define JSON_HEDLEY_IAR_VERSION_CHECK(major,minor,patch) (0)
  485. #endif
  486. #if defined(JSON_HEDLEY_TINYC_VERSION)
  487. #undef JSON_HEDLEY_TINYC_VERSION
  488. #endif
  489. #if defined(__TINYC__)
  490. #define JSON_HEDLEY_TINYC_VERSION JSON_HEDLEY_VERSION_ENCODE(__TINYC__ / 1000, (__TINYC__ / 100) % 10, __TINYC__ % 100)
  491. #endif
  492. #if defined(JSON_HEDLEY_TINYC_VERSION_CHECK)
  493. #undef JSON_HEDLEY_TINYC_VERSION_CHECK
  494. #endif
  495. #if defined(JSON_HEDLEY_TINYC_VERSION)
  496. #define JSON_HEDLEY_TINYC_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_TINYC_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
  497. #else
  498. #define JSON_HEDLEY_TINYC_VERSION_CHECK(major,minor,patch) (0)
  499. #endif
  500. #if defined(JSON_HEDLEY_DMC_VERSION)
  501. #undef JSON_HEDLEY_DMC_VERSION
  502. #endif
  503. #if defined(__DMC__)
  504. #define JSON_HEDLEY_DMC_VERSION JSON_HEDLEY_VERSION_ENCODE(__DMC__ >> 8, (__DMC__ >> 4) & 0xf, __DMC__ & 0xf)
  505. #endif
  506. #if defined(JSON_HEDLEY_DMC_VERSION_CHECK)
  507. #undef JSON_HEDLEY_DMC_VERSION_CHECK
  508. #endif
  509. #if defined(JSON_HEDLEY_DMC_VERSION)
  510. #define JSON_HEDLEY_DMC_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_DMC_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
  511. #else
  512. #define JSON_HEDLEY_DMC_VERSION_CHECK(major,minor,patch) (0)
  513. #endif
  514. #if defined(JSON_HEDLEY_COMPCERT_VERSION)
  515. #undef JSON_HEDLEY_COMPCERT_VERSION
  516. #endif
  517. #if defined(__COMPCERT_VERSION__)
  518. #define JSON_HEDLEY_COMPCERT_VERSION JSON_HEDLEY_VERSION_ENCODE(__COMPCERT_VERSION__ / 10000, (__COMPCERT_VERSION__ / 100) % 100, __COMPCERT_VERSION__ % 100)
  519. #endif
  520. #if defined(JSON_HEDLEY_COMPCERT_VERSION_CHECK)
  521. #undef JSON_HEDLEY_COMPCERT_VERSION_CHECK
  522. #endif
  523. #if defined(JSON_HEDLEY_COMPCERT_VERSION)
  524. #define JSON_HEDLEY_COMPCERT_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_COMPCERT_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
  525. #else
  526. #define JSON_HEDLEY_COMPCERT_VERSION_CHECK(major,minor,patch) (0)
  527. #endif
  528. #if defined(JSON_HEDLEY_PELLES_VERSION)
  529. #undef JSON_HEDLEY_PELLES_VERSION
  530. #endif
  531. #if defined(__POCC__)
  532. #define JSON_HEDLEY_PELLES_VERSION JSON_HEDLEY_VERSION_ENCODE(__POCC__ / 100, __POCC__ % 100, 0)
  533. #endif
  534. #if defined(JSON_HEDLEY_PELLES_VERSION_CHECK)
  535. #undef JSON_HEDLEY_PELLES_VERSION_CHECK
  536. #endif
  537. #if defined(JSON_HEDLEY_PELLES_VERSION)
  538. #define JSON_HEDLEY_PELLES_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_PELLES_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
  539. #else
  540. #define JSON_HEDLEY_PELLES_VERSION_CHECK(major,minor,patch) (0)
  541. #endif
  542. #if defined(JSON_HEDLEY_MCST_LCC_VERSION)
  543. #undef JSON_HEDLEY_MCST_LCC_VERSION
  544. #endif
  545. #if defined(__LCC__) && defined(__LCC_MINOR__)
  546. #define JSON_HEDLEY_MCST_LCC_VERSION JSON_HEDLEY_VERSION_ENCODE(__LCC__ / 100, __LCC__ % 100, __LCC_MINOR__)
  547. #endif
  548. #if defined(JSON_HEDLEY_MCST_LCC_VERSION_CHECK)
  549. #undef JSON_HEDLEY_MCST_LCC_VERSION_CHECK
  550. #endif
  551. #if defined(JSON_HEDLEY_MCST_LCC_VERSION)
  552. #define JSON_HEDLEY_MCST_LCC_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_MCST_LCC_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
  553. #else
  554. #define JSON_HEDLEY_MCST_LCC_VERSION_CHECK(major,minor,patch) (0)
  555. #endif
  556. #if defined(JSON_HEDLEY_GCC_VERSION)
  557. #undef JSON_HEDLEY_GCC_VERSION
  558. #endif
  559. #if \
  560. defined(JSON_HEDLEY_GNUC_VERSION) && \
  561. !defined(__clang__) && \
  562. !defined(JSON_HEDLEY_INTEL_VERSION) && \
  563. !defined(JSON_HEDLEY_PGI_VERSION) && \
  564. !defined(JSON_HEDLEY_ARM_VERSION) && \
  565. !defined(JSON_HEDLEY_CRAY_VERSION) && \
  566. !defined(JSON_HEDLEY_TI_VERSION) && \
  567. !defined(JSON_HEDLEY_TI_ARMCL_VERSION) && \
  568. !defined(JSON_HEDLEY_TI_CL430_VERSION) && \
  569. !defined(JSON_HEDLEY_TI_CL2000_VERSION) && \
  570. !defined(JSON_HEDLEY_TI_CL6X_VERSION) && \
  571. !defined(JSON_HEDLEY_TI_CL7X_VERSION) && \
  572. !defined(JSON_HEDLEY_TI_CLPRU_VERSION) && \
  573. !defined(__COMPCERT__) && \
  574. !defined(JSON_HEDLEY_MCST_LCC_VERSION)
  575. #define JSON_HEDLEY_GCC_VERSION JSON_HEDLEY_GNUC_VERSION
  576. #endif
  577. #if defined(JSON_HEDLEY_GCC_VERSION_CHECK)
  578. #undef JSON_HEDLEY_GCC_VERSION_CHECK
  579. #endif
  580. #if defined(JSON_HEDLEY_GCC_VERSION)
  581. #define JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_GCC_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
  582. #else
  583. #define JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch) (0)
  584. #endif
  585. #if defined(JSON_HEDLEY_HAS_ATTRIBUTE)
  586. #undef JSON_HEDLEY_HAS_ATTRIBUTE
  587. #endif
  588. #if \
  589. defined(__has_attribute) && \
  590. ( \
  591. (!defined(JSON_HEDLEY_IAR_VERSION) || JSON_HEDLEY_IAR_VERSION_CHECK(8,5,9)) \
  592. )
  593. # define JSON_HEDLEY_HAS_ATTRIBUTE(attribute) __has_attribute(attribute)
  594. #else
  595. # define JSON_HEDLEY_HAS_ATTRIBUTE(attribute) (0)
  596. #endif
  597. #if defined(JSON_HEDLEY_GNUC_HAS_ATTRIBUTE)
  598. #undef JSON_HEDLEY_GNUC_HAS_ATTRIBUTE
  599. #endif
  600. #if defined(__has_attribute)
  601. #define JSON_HEDLEY_GNUC_HAS_ATTRIBUTE(attribute,major,minor,patch) JSON_HEDLEY_HAS_ATTRIBUTE(attribute)
  602. #else
  603. #define JSON_HEDLEY_GNUC_HAS_ATTRIBUTE(attribute,major,minor,patch) JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch)
  604. #endif
  605. #if defined(JSON_HEDLEY_GCC_HAS_ATTRIBUTE)
  606. #undef JSON_HEDLEY_GCC_HAS_ATTRIBUTE
  607. #endif
  608. #if defined(__has_attribute)
  609. #define JSON_HEDLEY_GCC_HAS_ATTRIBUTE(attribute,major,minor,patch) JSON_HEDLEY_HAS_ATTRIBUTE(attribute)
  610. #else
  611. #define JSON_HEDLEY_GCC_HAS_ATTRIBUTE(attribute,major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch)
  612. #endif
  613. #if defined(JSON_HEDLEY_HAS_CPP_ATTRIBUTE)
  614. #undef JSON_HEDLEY_HAS_CPP_ATTRIBUTE
  615. #endif
  616. #if \
  617. defined(__has_cpp_attribute) && \
  618. defined(__cplusplus) && \
  619. (!defined(JSON_HEDLEY_SUNPRO_VERSION) || JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,15,0))
  620. #define JSON_HEDLEY_HAS_CPP_ATTRIBUTE(attribute) __has_cpp_attribute(attribute)
  621. #else
  622. #define JSON_HEDLEY_HAS_CPP_ATTRIBUTE(attribute) (0)
  623. #endif
  624. #if defined(JSON_HEDLEY_HAS_CPP_ATTRIBUTE_NS)
  625. #undef JSON_HEDLEY_HAS_CPP_ATTRIBUTE_NS
  626. #endif
  627. #if !defined(__cplusplus) || !defined(__has_cpp_attribute)
  628. #define JSON_HEDLEY_HAS_CPP_ATTRIBUTE_NS(ns,attribute) (0)
  629. #elif \
  630. !defined(JSON_HEDLEY_PGI_VERSION) && \
  631. !defined(JSON_HEDLEY_IAR_VERSION) && \
  632. (!defined(JSON_HEDLEY_SUNPRO_VERSION) || JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,15,0)) && \
  633. (!defined(JSON_HEDLEY_MSVC_VERSION) || JSON_HEDLEY_MSVC_VERSION_CHECK(19,20,0))
  634. #define JSON_HEDLEY_HAS_CPP_ATTRIBUTE_NS(ns,attribute) JSON_HEDLEY_HAS_CPP_ATTRIBUTE(ns::attribute)
  635. #else
  636. #define JSON_HEDLEY_HAS_CPP_ATTRIBUTE_NS(ns,attribute) (0)
  637. #endif
  638. #if defined(JSON_HEDLEY_GNUC_HAS_CPP_ATTRIBUTE)
  639. #undef JSON_HEDLEY_GNUC_HAS_CPP_ATTRIBUTE
  640. #endif
  641. #if defined(__has_cpp_attribute) && defined(__cplusplus)
  642. #define JSON_HEDLEY_GNUC_HAS_CPP_ATTRIBUTE(attribute,major,minor,patch) __has_cpp_attribute(attribute)
  643. #else
  644. #define JSON_HEDLEY_GNUC_HAS_CPP_ATTRIBUTE(attribute,major,minor,patch) JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch)
  645. #endif
  646. #if defined(JSON_HEDLEY_GCC_HAS_CPP_ATTRIBUTE)
  647. #undef JSON_HEDLEY_GCC_HAS_CPP_ATTRIBUTE
  648. #endif
  649. #if defined(__has_cpp_attribute) && defined(__cplusplus)
  650. #define JSON_HEDLEY_GCC_HAS_CPP_ATTRIBUTE(attribute,major,minor,patch) __has_cpp_attribute(attribute)
  651. #else
  652. #define JSON_HEDLEY_GCC_HAS_CPP_ATTRIBUTE(attribute,major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch)
  653. #endif
  654. #if defined(JSON_HEDLEY_HAS_BUILTIN)
  655. #undef JSON_HEDLEY_HAS_BUILTIN
  656. #endif
  657. #if defined(__has_builtin)
  658. #define JSON_HEDLEY_HAS_BUILTIN(builtin) __has_builtin(builtin)
  659. #else
  660. #define JSON_HEDLEY_HAS_BUILTIN(builtin) (0)
  661. #endif
  662. #if defined(JSON_HEDLEY_GNUC_HAS_BUILTIN)
  663. #undef JSON_HEDLEY_GNUC_HAS_BUILTIN
  664. #endif
  665. #if defined(__has_builtin)
  666. #define JSON_HEDLEY_GNUC_HAS_BUILTIN(builtin,major,minor,patch) __has_builtin(builtin)
  667. #else
  668. #define JSON_HEDLEY_GNUC_HAS_BUILTIN(builtin,major,minor,patch) JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch)
  669. #endif
  670. #if defined(JSON_HEDLEY_GCC_HAS_BUILTIN)
  671. #undef JSON_HEDLEY_GCC_HAS_BUILTIN
  672. #endif
  673. #if defined(__has_builtin)
  674. #define JSON_HEDLEY_GCC_HAS_BUILTIN(builtin,major,minor,patch) __has_builtin(builtin)
  675. #else
  676. #define JSON_HEDLEY_GCC_HAS_BUILTIN(builtin,major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch)
  677. #endif
  678. #if defined(JSON_HEDLEY_HAS_FEATURE)
  679. #undef JSON_HEDLEY_HAS_FEATURE
  680. #endif
  681. #if defined(__has_feature)
  682. #define JSON_HEDLEY_HAS_FEATURE(feature) __has_feature(feature)
  683. #else
  684. #define JSON_HEDLEY_HAS_FEATURE(feature) (0)
  685. #endif
  686. #if defined(JSON_HEDLEY_GNUC_HAS_FEATURE)
  687. #undef JSON_HEDLEY_GNUC_HAS_FEATURE
  688. #endif
  689. #if defined(__has_feature)
  690. #define JSON_HEDLEY_GNUC_HAS_FEATURE(feature,major,minor,patch) __has_feature(feature)
  691. #else
  692. #define JSON_HEDLEY_GNUC_HAS_FEATURE(feature,major,minor,patch) JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch)
  693. #endif
  694. #if defined(JSON_HEDLEY_GCC_HAS_FEATURE)
  695. #undef JSON_HEDLEY_GCC_HAS_FEATURE
  696. #endif
  697. #if defined(__has_feature)
  698. #define JSON_HEDLEY_GCC_HAS_FEATURE(feature,major,minor,patch) __has_feature(feature)
  699. #else
  700. #define JSON_HEDLEY_GCC_HAS_FEATURE(feature,major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch)
  701. #endif
  702. #if defined(JSON_HEDLEY_HAS_EXTENSION)
  703. #undef JSON_HEDLEY_HAS_EXTENSION
  704. #endif
  705. #if defined(__has_extension)
  706. #define JSON_HEDLEY_HAS_EXTENSION(extension) __has_extension(extension)
  707. #else
  708. #define JSON_HEDLEY_HAS_EXTENSION(extension) (0)
  709. #endif
  710. #if defined(JSON_HEDLEY_GNUC_HAS_EXTENSION)
  711. #undef JSON_HEDLEY_GNUC_HAS_EXTENSION
  712. #endif
  713. #if defined(__has_extension)
  714. #define JSON_HEDLEY_GNUC_HAS_EXTENSION(extension,major,minor,patch) __has_extension(extension)
  715. #else
  716. #define JSON_HEDLEY_GNUC_HAS_EXTENSION(extension,major,minor,patch) JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch)
  717. #endif
  718. #if defined(JSON_HEDLEY_GCC_HAS_EXTENSION)
  719. #undef JSON_HEDLEY_GCC_HAS_EXTENSION
  720. #endif
  721. #if defined(__has_extension)
  722. #define JSON_HEDLEY_GCC_HAS_EXTENSION(extension,major,minor,patch) __has_extension(extension)
  723. #else
  724. #define JSON_HEDLEY_GCC_HAS_EXTENSION(extension,major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch)
  725. #endif
  726. #if defined(JSON_HEDLEY_HAS_DECLSPEC_ATTRIBUTE)
  727. #undef JSON_HEDLEY_HAS_DECLSPEC_ATTRIBUTE
  728. #endif
  729. #if defined(__has_declspec_attribute)
  730. #define JSON_HEDLEY_HAS_DECLSPEC_ATTRIBUTE(attribute) __has_declspec_attribute(attribute)
  731. #else
  732. #define JSON_HEDLEY_HAS_DECLSPEC_ATTRIBUTE(attribute) (0)
  733. #endif
  734. #if defined(JSON_HEDLEY_GNUC_HAS_DECLSPEC_ATTRIBUTE)
  735. #undef JSON_HEDLEY_GNUC_HAS_DECLSPEC_ATTRIBUTE
  736. #endif
  737. #if defined(__has_declspec_attribute)
  738. #define JSON_HEDLEY_GNUC_HAS_DECLSPEC_ATTRIBUTE(attribute,major,minor,patch) __has_declspec_attribute(attribute)
  739. #else
  740. #define JSON_HEDLEY_GNUC_HAS_DECLSPEC_ATTRIBUTE(attribute,major,minor,patch) JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch)
  741. #endif
  742. #if defined(JSON_HEDLEY_GCC_HAS_DECLSPEC_ATTRIBUTE)
  743. #undef JSON_HEDLEY_GCC_HAS_DECLSPEC_ATTRIBUTE
  744. #endif
  745. #if defined(__has_declspec_attribute)
  746. #define JSON_HEDLEY_GCC_HAS_DECLSPEC_ATTRIBUTE(attribute,major,minor,patch) __has_declspec_attribute(attribute)
  747. #else
  748. #define JSON_HEDLEY_GCC_HAS_DECLSPEC_ATTRIBUTE(attribute,major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch)
  749. #endif
  750. #if defined(JSON_HEDLEY_HAS_WARNING)
  751. #undef JSON_HEDLEY_HAS_WARNING
  752. #endif
  753. #if defined(__has_warning)
  754. #define JSON_HEDLEY_HAS_WARNING(warning) __has_warning(warning)
  755. #else
  756. #define JSON_HEDLEY_HAS_WARNING(warning) (0)
  757. #endif
  758. #if defined(JSON_HEDLEY_GNUC_HAS_WARNING)
  759. #undef JSON_HEDLEY_GNUC_HAS_WARNING
  760. #endif
  761. #if defined(__has_warning)
  762. #define JSON_HEDLEY_GNUC_HAS_WARNING(warning,major,minor,patch) __has_warning(warning)
  763. #else
  764. #define JSON_HEDLEY_GNUC_HAS_WARNING(warning,major,minor,patch) JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch)
  765. #endif
  766. #if defined(JSON_HEDLEY_GCC_HAS_WARNING)
  767. #undef JSON_HEDLEY_GCC_HAS_WARNING
  768. #endif
  769. #if defined(__has_warning)
  770. #define JSON_HEDLEY_GCC_HAS_WARNING(warning,major,minor,patch) __has_warning(warning)
  771. #else
  772. #define JSON_HEDLEY_GCC_HAS_WARNING(warning,major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch)
  773. #endif
  774. #if \
  775. (defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L)) || \
  776. defined(__clang__) || \
  777. JSON_HEDLEY_GCC_VERSION_CHECK(3,0,0) || \
  778. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
  779. JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0) || \
  780. JSON_HEDLEY_PGI_VERSION_CHECK(18,4,0) || \
  781. JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \
  782. JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \
  783. JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,7,0) || \
  784. JSON_HEDLEY_TI_CL430_VERSION_CHECK(2,0,1) || \
  785. JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,1,0) || \
  786. JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,0,0) || \
  787. JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \
  788. JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \
  789. JSON_HEDLEY_CRAY_VERSION_CHECK(5,0,0) || \
  790. JSON_HEDLEY_TINYC_VERSION_CHECK(0,9,17) || \
  791. JSON_HEDLEY_SUNPRO_VERSION_CHECK(8,0,0) || \
  792. (JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) && defined(__C99_PRAGMA_OPERATOR))
  793. #define JSON_HEDLEY_PRAGMA(value) _Pragma(#value)
  794. #elif JSON_HEDLEY_MSVC_VERSION_CHECK(15,0,0)
  795. #define JSON_HEDLEY_PRAGMA(value) __pragma(value)
  796. #else
  797. #define JSON_HEDLEY_PRAGMA(value)
  798. #endif
  799. #if defined(JSON_HEDLEY_DIAGNOSTIC_PUSH)
  800. #undef JSON_HEDLEY_DIAGNOSTIC_PUSH
  801. #endif
  802. #if defined(JSON_HEDLEY_DIAGNOSTIC_POP)
  803. #undef JSON_HEDLEY_DIAGNOSTIC_POP
  804. #endif
  805. #if defined(__clang__)
  806. #define JSON_HEDLEY_DIAGNOSTIC_PUSH _Pragma("clang diagnostic push")
  807. #define JSON_HEDLEY_DIAGNOSTIC_POP _Pragma("clang diagnostic pop")
  808. #elif JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0)
  809. #define JSON_HEDLEY_DIAGNOSTIC_PUSH _Pragma("warning(push)")
  810. #define JSON_HEDLEY_DIAGNOSTIC_POP _Pragma("warning(pop)")
  811. #elif JSON_HEDLEY_GCC_VERSION_CHECK(4,6,0)
  812. #define JSON_HEDLEY_DIAGNOSTIC_PUSH _Pragma("GCC diagnostic push")
  813. #define JSON_HEDLEY_DIAGNOSTIC_POP _Pragma("GCC diagnostic pop")
  814. #elif \
  815. JSON_HEDLEY_MSVC_VERSION_CHECK(15,0,0) || \
  816. JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0)
  817. #define JSON_HEDLEY_DIAGNOSTIC_PUSH __pragma(warning(push))
  818. #define JSON_HEDLEY_DIAGNOSTIC_POP __pragma(warning(pop))
  819. #elif JSON_HEDLEY_ARM_VERSION_CHECK(5,6,0)
  820. #define JSON_HEDLEY_DIAGNOSTIC_PUSH _Pragma("push")
  821. #define JSON_HEDLEY_DIAGNOSTIC_POP _Pragma("pop")
  822. #elif \
  823. JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \
  824. JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \
  825. JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,4,0) || \
  826. JSON_HEDLEY_TI_CL6X_VERSION_CHECK(8,1,0) || \
  827. JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \
  828. JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0)
  829. #define JSON_HEDLEY_DIAGNOSTIC_PUSH _Pragma("diag_push")
  830. #define JSON_HEDLEY_DIAGNOSTIC_POP _Pragma("diag_pop")
  831. #elif JSON_HEDLEY_PELLES_VERSION_CHECK(2,90,0)
  832. #define JSON_HEDLEY_DIAGNOSTIC_PUSH _Pragma("warning(push)")
  833. #define JSON_HEDLEY_DIAGNOSTIC_POP _Pragma("warning(pop)")
  834. #else
  835. #define JSON_HEDLEY_DIAGNOSTIC_PUSH
  836. #define JSON_HEDLEY_DIAGNOSTIC_POP
  837. #endif
  838. /* JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_ is for
  839. HEDLEY INTERNAL USE ONLY. API subject to change without notice. */
  840. #if defined(JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_)
  841. #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_
  842. #endif
  843. #if defined(__cplusplus)
  844. # if JSON_HEDLEY_HAS_WARNING("-Wc++98-compat")
  845. # if JSON_HEDLEY_HAS_WARNING("-Wc++17-extensions")
  846. # if JSON_HEDLEY_HAS_WARNING("-Wc++1z-extensions")
  847. # define JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_(xpr) \
  848. JSON_HEDLEY_DIAGNOSTIC_PUSH \
  849. _Pragma("clang diagnostic ignored \"-Wc++98-compat\"") \
  850. _Pragma("clang diagnostic ignored \"-Wc++17-extensions\"") \
  851. _Pragma("clang diagnostic ignored \"-Wc++1z-extensions\"") \
  852. xpr \
  853. JSON_HEDLEY_DIAGNOSTIC_POP
  854. # else
  855. # define JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_(xpr) \
  856. JSON_HEDLEY_DIAGNOSTIC_PUSH \
  857. _Pragma("clang diagnostic ignored \"-Wc++98-compat\"") \
  858. _Pragma("clang diagnostic ignored \"-Wc++17-extensions\"") \
  859. xpr \
  860. JSON_HEDLEY_DIAGNOSTIC_POP
  861. # endif
  862. # else
  863. # define JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_(xpr) \
  864. JSON_HEDLEY_DIAGNOSTIC_PUSH \
  865. _Pragma("clang diagnostic ignored \"-Wc++98-compat\"") \
  866. xpr \
  867. JSON_HEDLEY_DIAGNOSTIC_POP
  868. # endif
  869. # endif
  870. #endif
  871. #if !defined(JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_)
  872. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_(x) x
  873. #endif
  874. #if defined(JSON_HEDLEY_CONST_CAST)
  875. #undef JSON_HEDLEY_CONST_CAST
  876. #endif
  877. #if defined(__cplusplus)
  878. # define JSON_HEDLEY_CONST_CAST(T, expr) (const_cast<T>(expr))
  879. #elif \
  880. JSON_HEDLEY_HAS_WARNING("-Wcast-qual") || \
  881. JSON_HEDLEY_GCC_VERSION_CHECK(4,6,0) || \
  882. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0)
  883. # define JSON_HEDLEY_CONST_CAST(T, expr) (__extension__ ({ \
  884. JSON_HEDLEY_DIAGNOSTIC_PUSH \
  885. JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL \
  886. ((T) (expr)); \
  887. JSON_HEDLEY_DIAGNOSTIC_POP \
  888. }))
  889. #else
  890. # define JSON_HEDLEY_CONST_CAST(T, expr) ((T) (expr))
  891. #endif
  892. #if defined(JSON_HEDLEY_REINTERPRET_CAST)
  893. #undef JSON_HEDLEY_REINTERPRET_CAST
  894. #endif
  895. #if defined(__cplusplus)
  896. #define JSON_HEDLEY_REINTERPRET_CAST(T, expr) (reinterpret_cast<T>(expr))
  897. #else
  898. #define JSON_HEDLEY_REINTERPRET_CAST(T, expr) ((T) (expr))
  899. #endif
  900. #if defined(JSON_HEDLEY_STATIC_CAST)
  901. #undef JSON_HEDLEY_STATIC_CAST
  902. #endif
  903. #if defined(__cplusplus)
  904. #define JSON_HEDLEY_STATIC_CAST(T, expr) (static_cast<T>(expr))
  905. #else
  906. #define JSON_HEDLEY_STATIC_CAST(T, expr) ((T) (expr))
  907. #endif
  908. #if defined(JSON_HEDLEY_CPP_CAST)
  909. #undef JSON_HEDLEY_CPP_CAST
  910. #endif
  911. #if defined(__cplusplus)
  912. # if JSON_HEDLEY_HAS_WARNING("-Wold-style-cast")
  913. # define JSON_HEDLEY_CPP_CAST(T, expr) \
  914. JSON_HEDLEY_DIAGNOSTIC_PUSH \
  915. _Pragma("clang diagnostic ignored \"-Wold-style-cast\"") \
  916. ((T) (expr)) \
  917. JSON_HEDLEY_DIAGNOSTIC_POP
  918. # elif JSON_HEDLEY_IAR_VERSION_CHECK(8,3,0)
  919. # define JSON_HEDLEY_CPP_CAST(T, expr) \
  920. JSON_HEDLEY_DIAGNOSTIC_PUSH \
  921. _Pragma("diag_suppress=Pe137") \
  922. JSON_HEDLEY_DIAGNOSTIC_POP
  923. # else
  924. # define JSON_HEDLEY_CPP_CAST(T, expr) ((T) (expr))
  925. # endif
  926. #else
  927. # define JSON_HEDLEY_CPP_CAST(T, expr) (expr)
  928. #endif
  929. #if defined(JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED)
  930. #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED
  931. #endif
  932. #if JSON_HEDLEY_HAS_WARNING("-Wdeprecated-declarations")
  933. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("clang diagnostic ignored \"-Wdeprecated-declarations\"")
  934. #elif JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0)
  935. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("warning(disable:1478 1786)")
  936. #elif JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0)
  937. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED __pragma(warning(disable:1478 1786))
  938. #elif JSON_HEDLEY_PGI_VERSION_CHECK(20,7,0)
  939. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("diag_suppress 1215,1216,1444,1445")
  940. #elif JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0)
  941. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("diag_suppress 1215,1444")
  942. #elif JSON_HEDLEY_GCC_VERSION_CHECK(4,3,0)
  943. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("GCC diagnostic ignored \"-Wdeprecated-declarations\"")
  944. #elif JSON_HEDLEY_MSVC_VERSION_CHECK(15,0,0)
  945. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED __pragma(warning(disable:4996))
  946. #elif JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10)
  947. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("diag_suppress 1215,1444")
  948. #elif \
  949. JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \
  950. (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  951. JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \
  952. (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  953. JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \
  954. (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  955. JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \
  956. (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  957. JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \
  958. JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \
  959. JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0)
  960. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("diag_suppress 1291,1718")
  961. #elif JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,13,0) && !defined(__cplusplus)
  962. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("error_messages(off,E_DEPRECATED_ATT,E_DEPRECATED_ATT_MESS)")
  963. #elif JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,13,0) && defined(__cplusplus)
  964. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("error_messages(off,symdeprecated,symdeprecated2)")
  965. #elif JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0)
  966. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("diag_suppress=Pe1444,Pe1215")
  967. #elif JSON_HEDLEY_PELLES_VERSION_CHECK(2,90,0)
  968. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("warn(disable:2241)")
  969. #else
  970. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED
  971. #endif
  972. #if defined(JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS)
  973. #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS
  974. #endif
  975. #if JSON_HEDLEY_HAS_WARNING("-Wunknown-pragmas")
  976. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("clang diagnostic ignored \"-Wunknown-pragmas\"")
  977. #elif JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0)
  978. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("warning(disable:161)")
  979. #elif JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0)
  980. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS __pragma(warning(disable:161))
  981. #elif JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0)
  982. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("diag_suppress 1675")
  983. #elif JSON_HEDLEY_GCC_VERSION_CHECK(4,3,0)
  984. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("GCC diagnostic ignored \"-Wunknown-pragmas\"")
  985. #elif JSON_HEDLEY_MSVC_VERSION_CHECK(15,0,0)
  986. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS __pragma(warning(disable:4068))
  987. #elif \
  988. JSON_HEDLEY_TI_VERSION_CHECK(16,9,0) || \
  989. JSON_HEDLEY_TI_CL6X_VERSION_CHECK(8,0,0) || \
  990. JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \
  991. JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,3,0)
  992. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("diag_suppress 163")
  993. #elif JSON_HEDLEY_TI_CL6X_VERSION_CHECK(8,0,0)
  994. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("diag_suppress 163")
  995. #elif JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0)
  996. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("diag_suppress=Pe161")
  997. #elif JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10)
  998. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("diag_suppress 161")
  999. #else
  1000. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS
  1001. #endif
  1002. #if defined(JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES)
  1003. #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES
  1004. #endif
  1005. #if JSON_HEDLEY_HAS_WARNING("-Wunknown-attributes")
  1006. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("clang diagnostic ignored \"-Wunknown-attributes\"")
  1007. #elif JSON_HEDLEY_GCC_VERSION_CHECK(4,6,0)
  1008. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("GCC diagnostic ignored \"-Wdeprecated-declarations\"")
  1009. #elif JSON_HEDLEY_INTEL_VERSION_CHECK(17,0,0)
  1010. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("warning(disable:1292)")
  1011. #elif JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0)
  1012. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES __pragma(warning(disable:1292))
  1013. #elif JSON_HEDLEY_MSVC_VERSION_CHECK(19,0,0)
  1014. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES __pragma(warning(disable:5030))
  1015. #elif JSON_HEDLEY_PGI_VERSION_CHECK(20,7,0)
  1016. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("diag_suppress 1097,1098")
  1017. #elif JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0)
  1018. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("diag_suppress 1097")
  1019. #elif JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,14,0) && defined(__cplusplus)
  1020. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("error_messages(off,attrskipunsup)")
  1021. #elif \
  1022. JSON_HEDLEY_TI_VERSION_CHECK(18,1,0) || \
  1023. JSON_HEDLEY_TI_CL6X_VERSION_CHECK(8,3,0) || \
  1024. JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0)
  1025. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("diag_suppress 1173")
  1026. #elif JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0)
  1027. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("diag_suppress=Pe1097")
  1028. #elif JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10)
  1029. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("diag_suppress 1097")
  1030. #else
  1031. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES
  1032. #endif
  1033. #if defined(JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL)
  1034. #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL
  1035. #endif
  1036. #if JSON_HEDLEY_HAS_WARNING("-Wcast-qual")
  1037. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL _Pragma("clang diagnostic ignored \"-Wcast-qual\"")
  1038. #elif JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0)
  1039. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL _Pragma("warning(disable:2203 2331)")
  1040. #elif JSON_HEDLEY_GCC_VERSION_CHECK(3,0,0)
  1041. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL _Pragma("GCC diagnostic ignored \"-Wcast-qual\"")
  1042. #else
  1043. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL
  1044. #endif
  1045. #if defined(JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNUSED_FUNCTION)
  1046. #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNUSED_FUNCTION
  1047. #endif
  1048. #if JSON_HEDLEY_HAS_WARNING("-Wunused-function")
  1049. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNUSED_FUNCTION _Pragma("clang diagnostic ignored \"-Wunused-function\"")
  1050. #elif JSON_HEDLEY_GCC_VERSION_CHECK(3,4,0)
  1051. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNUSED_FUNCTION _Pragma("GCC diagnostic ignored \"-Wunused-function\"")
  1052. #elif JSON_HEDLEY_MSVC_VERSION_CHECK(1,0,0)
  1053. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNUSED_FUNCTION __pragma(warning(disable:4505))
  1054. #elif JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10)
  1055. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNUSED_FUNCTION _Pragma("diag_suppress 3142")
  1056. #else
  1057. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNUSED_FUNCTION
  1058. #endif
  1059. #if defined(JSON_HEDLEY_DEPRECATED)
  1060. #undef JSON_HEDLEY_DEPRECATED
  1061. #endif
  1062. #if defined(JSON_HEDLEY_DEPRECATED_FOR)
  1063. #undef JSON_HEDLEY_DEPRECATED_FOR
  1064. #endif
  1065. #if \
  1066. JSON_HEDLEY_MSVC_VERSION_CHECK(14,0,0) || \
  1067. JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0)
  1068. #define JSON_HEDLEY_DEPRECATED(since) __declspec(deprecated("Since " # since))
  1069. #define JSON_HEDLEY_DEPRECATED_FOR(since, replacement) __declspec(deprecated("Since " #since "; use " #replacement))
  1070. #elif \
  1071. (JSON_HEDLEY_HAS_EXTENSION(attribute_deprecated_with_message) && !defined(JSON_HEDLEY_IAR_VERSION)) || \
  1072. JSON_HEDLEY_GCC_VERSION_CHECK(4,5,0) || \
  1073. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
  1074. JSON_HEDLEY_ARM_VERSION_CHECK(5,6,0) || \
  1075. JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,13,0) || \
  1076. JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0) || \
  1077. JSON_HEDLEY_TI_VERSION_CHECK(18,1,0) || \
  1078. JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(18,1,0) || \
  1079. JSON_HEDLEY_TI_CL6X_VERSION_CHECK(8,3,0) || \
  1080. JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \
  1081. JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,3,0) || \
  1082. JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10)
  1083. #define JSON_HEDLEY_DEPRECATED(since) __attribute__((__deprecated__("Since " #since)))
  1084. #define JSON_HEDLEY_DEPRECATED_FOR(since, replacement) __attribute__((__deprecated__("Since " #since "; use " #replacement)))
  1085. #elif defined(__cplusplus) && (__cplusplus >= 201402L)
  1086. #define JSON_HEDLEY_DEPRECATED(since) JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[deprecated("Since " #since)]])
  1087. #define JSON_HEDLEY_DEPRECATED_FOR(since, replacement) JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[deprecated("Since " #since "; use " #replacement)]])
  1088. #elif \
  1089. JSON_HEDLEY_HAS_ATTRIBUTE(deprecated) || \
  1090. JSON_HEDLEY_GCC_VERSION_CHECK(3,1,0) || \
  1091. JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \
  1092. JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \
  1093. (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  1094. JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \
  1095. (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  1096. JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \
  1097. (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  1098. JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \
  1099. (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  1100. JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \
  1101. JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \
  1102. JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \
  1103. JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) || \
  1104. JSON_HEDLEY_IAR_VERSION_CHECK(8,10,0)
  1105. #define JSON_HEDLEY_DEPRECATED(since) __attribute__((__deprecated__))
  1106. #define JSON_HEDLEY_DEPRECATED_FOR(since, replacement) __attribute__((__deprecated__))
  1107. #elif \
  1108. JSON_HEDLEY_MSVC_VERSION_CHECK(13,10,0) || \
  1109. JSON_HEDLEY_PELLES_VERSION_CHECK(6,50,0) || \
  1110. JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0)
  1111. #define JSON_HEDLEY_DEPRECATED(since) __declspec(deprecated)
  1112. #define JSON_HEDLEY_DEPRECATED_FOR(since, replacement) __declspec(deprecated)
  1113. #elif JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0)
  1114. #define JSON_HEDLEY_DEPRECATED(since) _Pragma("deprecated")
  1115. #define JSON_HEDLEY_DEPRECATED_FOR(since, replacement) _Pragma("deprecated")
  1116. #else
  1117. #define JSON_HEDLEY_DEPRECATED(since)
  1118. #define JSON_HEDLEY_DEPRECATED_FOR(since, replacement)
  1119. #endif
  1120. #if defined(JSON_HEDLEY_UNAVAILABLE)
  1121. #undef JSON_HEDLEY_UNAVAILABLE
  1122. #endif
  1123. #if \
  1124. JSON_HEDLEY_HAS_ATTRIBUTE(warning) || \
  1125. JSON_HEDLEY_GCC_VERSION_CHECK(4,3,0) || \
  1126. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
  1127. JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10)
  1128. #define JSON_HEDLEY_UNAVAILABLE(available_since) __attribute__((__warning__("Not available until " #available_since)))
  1129. #else
  1130. #define JSON_HEDLEY_UNAVAILABLE(available_since)
  1131. #endif
  1132. #if defined(JSON_HEDLEY_WARN_UNUSED_RESULT)
  1133. #undef JSON_HEDLEY_WARN_UNUSED_RESULT
  1134. #endif
  1135. #if defined(JSON_HEDLEY_WARN_UNUSED_RESULT_MSG)
  1136. #undef JSON_HEDLEY_WARN_UNUSED_RESULT_MSG
  1137. #endif
  1138. #if \
  1139. JSON_HEDLEY_HAS_ATTRIBUTE(warn_unused_result) || \
  1140. JSON_HEDLEY_GCC_VERSION_CHECK(3,4,0) || \
  1141. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
  1142. JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \
  1143. (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  1144. JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \
  1145. (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  1146. JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \
  1147. (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  1148. JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \
  1149. (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  1150. JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \
  1151. JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \
  1152. JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \
  1153. (JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,15,0) && defined(__cplusplus)) || \
  1154. JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0) || \
  1155. JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10)
  1156. #define JSON_HEDLEY_WARN_UNUSED_RESULT __attribute__((__warn_unused_result__))
  1157. #define JSON_HEDLEY_WARN_UNUSED_RESULT_MSG(msg) __attribute__((__warn_unused_result__))
  1158. #elif (JSON_HEDLEY_HAS_CPP_ATTRIBUTE(nodiscard) >= 201907L)
  1159. #define JSON_HEDLEY_WARN_UNUSED_RESULT JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[nodiscard]])
  1160. #define JSON_HEDLEY_WARN_UNUSED_RESULT_MSG(msg) JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[nodiscard(msg)]])
  1161. #elif JSON_HEDLEY_HAS_CPP_ATTRIBUTE(nodiscard)
  1162. #define JSON_HEDLEY_WARN_UNUSED_RESULT JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[nodiscard]])
  1163. #define JSON_HEDLEY_WARN_UNUSED_RESULT_MSG(msg) JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[nodiscard]])
  1164. #elif defined(_Check_return_) /* SAL */
  1165. #define JSON_HEDLEY_WARN_UNUSED_RESULT _Check_return_
  1166. #define JSON_HEDLEY_WARN_UNUSED_RESULT_MSG(msg) _Check_return_
  1167. #else
  1168. #define JSON_HEDLEY_WARN_UNUSED_RESULT
  1169. #define JSON_HEDLEY_WARN_UNUSED_RESULT_MSG(msg)
  1170. #endif
  1171. #if defined(JSON_HEDLEY_SENTINEL)
  1172. #undef JSON_HEDLEY_SENTINEL
  1173. #endif
  1174. #if \
  1175. JSON_HEDLEY_HAS_ATTRIBUTE(sentinel) || \
  1176. JSON_HEDLEY_GCC_VERSION_CHECK(4,0,0) || \
  1177. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
  1178. JSON_HEDLEY_ARM_VERSION_CHECK(5,4,0) || \
  1179. JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10)
  1180. #define JSON_HEDLEY_SENTINEL(position) __attribute__((__sentinel__(position)))
  1181. #else
  1182. #define JSON_HEDLEY_SENTINEL(position)
  1183. #endif
  1184. #if defined(JSON_HEDLEY_NO_RETURN)
  1185. #undef JSON_HEDLEY_NO_RETURN
  1186. #endif
  1187. #if JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0)
  1188. #define JSON_HEDLEY_NO_RETURN __noreturn
  1189. #elif \
  1190. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
  1191. JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10)
  1192. #define JSON_HEDLEY_NO_RETURN __attribute__((__noreturn__))
  1193. #elif defined(__STDC_VERSION__) && __STDC_VERSION__ >= 201112L
  1194. #define JSON_HEDLEY_NO_RETURN _Noreturn
  1195. #elif defined(__cplusplus) && (__cplusplus >= 201103L)
  1196. #define JSON_HEDLEY_NO_RETURN JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[noreturn]])
  1197. #elif \
  1198. JSON_HEDLEY_HAS_ATTRIBUTE(noreturn) || \
  1199. JSON_HEDLEY_GCC_VERSION_CHECK(3,2,0) || \
  1200. JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,11,0) || \
  1201. JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \
  1202. JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \
  1203. JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \
  1204. (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  1205. JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \
  1206. (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  1207. JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \
  1208. (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  1209. JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \
  1210. (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  1211. JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \
  1212. JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \
  1213. JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \
  1214. JSON_HEDLEY_IAR_VERSION_CHECK(8,10,0)
  1215. #define JSON_HEDLEY_NO_RETURN __attribute__((__noreturn__))
  1216. #elif JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,10,0)
  1217. #define JSON_HEDLEY_NO_RETURN _Pragma("does_not_return")
  1218. #elif \
  1219. JSON_HEDLEY_MSVC_VERSION_CHECK(13,10,0) || \
  1220. JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0)
  1221. #define JSON_HEDLEY_NO_RETURN __declspec(noreturn)
  1222. #elif JSON_HEDLEY_TI_CL6X_VERSION_CHECK(6,0,0) && defined(__cplusplus)
  1223. #define JSON_HEDLEY_NO_RETURN _Pragma("FUNC_NEVER_RETURNS;")
  1224. #elif JSON_HEDLEY_COMPCERT_VERSION_CHECK(3,2,0)
  1225. #define JSON_HEDLEY_NO_RETURN __attribute((noreturn))
  1226. #elif JSON_HEDLEY_PELLES_VERSION_CHECK(9,0,0)
  1227. #define JSON_HEDLEY_NO_RETURN __declspec(noreturn)
  1228. #else
  1229. #define JSON_HEDLEY_NO_RETURN
  1230. #endif
  1231. #if defined(JSON_HEDLEY_NO_ESCAPE)
  1232. #undef JSON_HEDLEY_NO_ESCAPE
  1233. #endif
  1234. #if JSON_HEDLEY_HAS_ATTRIBUTE(noescape)
  1235. #define JSON_HEDLEY_NO_ESCAPE __attribute__((__noescape__))
  1236. #else
  1237. #define JSON_HEDLEY_NO_ESCAPE
  1238. #endif
  1239. #if defined(JSON_HEDLEY_UNREACHABLE)
  1240. #undef JSON_HEDLEY_UNREACHABLE
  1241. #endif
  1242. #if defined(JSON_HEDLEY_UNREACHABLE_RETURN)
  1243. #undef JSON_HEDLEY_UNREACHABLE_RETURN
  1244. #endif
  1245. #if defined(JSON_HEDLEY_ASSUME)
  1246. #undef JSON_HEDLEY_ASSUME
  1247. #endif
  1248. #if \
  1249. JSON_HEDLEY_MSVC_VERSION_CHECK(13,10,0) || \
  1250. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
  1251. JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0)
  1252. #define JSON_HEDLEY_ASSUME(expr) __assume(expr)
  1253. #elif JSON_HEDLEY_HAS_BUILTIN(__builtin_assume)
  1254. #define JSON_HEDLEY_ASSUME(expr) __builtin_assume(expr)
  1255. #elif \
  1256. JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,2,0) || \
  1257. JSON_HEDLEY_TI_CL6X_VERSION_CHECK(4,0,0)
  1258. #if defined(__cplusplus)
  1259. #define JSON_HEDLEY_ASSUME(expr) std::_nassert(expr)
  1260. #else
  1261. #define JSON_HEDLEY_ASSUME(expr) _nassert(expr)
  1262. #endif
  1263. #endif
  1264. #if \
  1265. (JSON_HEDLEY_HAS_BUILTIN(__builtin_unreachable) && (!defined(JSON_HEDLEY_ARM_VERSION))) || \
  1266. JSON_HEDLEY_GCC_VERSION_CHECK(4,5,0) || \
  1267. JSON_HEDLEY_PGI_VERSION_CHECK(18,10,0) || \
  1268. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
  1269. JSON_HEDLEY_IBM_VERSION_CHECK(13,1,5) || \
  1270. JSON_HEDLEY_CRAY_VERSION_CHECK(10,0,0) || \
  1271. JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10)
  1272. #define JSON_HEDLEY_UNREACHABLE() __builtin_unreachable()
  1273. #elif defined(JSON_HEDLEY_ASSUME)
  1274. #define JSON_HEDLEY_UNREACHABLE() JSON_HEDLEY_ASSUME(0)
  1275. #endif
  1276. #if !defined(JSON_HEDLEY_ASSUME)
  1277. #if defined(JSON_HEDLEY_UNREACHABLE)
  1278. #define JSON_HEDLEY_ASSUME(expr) JSON_HEDLEY_STATIC_CAST(void, ((expr) ? 1 : (JSON_HEDLEY_UNREACHABLE(), 1)))
  1279. #else
  1280. #define JSON_HEDLEY_ASSUME(expr) JSON_HEDLEY_STATIC_CAST(void, expr)
  1281. #endif
  1282. #endif
  1283. #if defined(JSON_HEDLEY_UNREACHABLE)
  1284. #if \
  1285. JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,2,0) || \
  1286. JSON_HEDLEY_TI_CL6X_VERSION_CHECK(4,0,0)
  1287. #define JSON_HEDLEY_UNREACHABLE_RETURN(value) return (JSON_HEDLEY_STATIC_CAST(void, JSON_HEDLEY_ASSUME(0)), (value))
  1288. #else
  1289. #define JSON_HEDLEY_UNREACHABLE_RETURN(value) JSON_HEDLEY_UNREACHABLE()
  1290. #endif
  1291. #else
  1292. #define JSON_HEDLEY_UNREACHABLE_RETURN(value) return (value)
  1293. #endif
  1294. #if !defined(JSON_HEDLEY_UNREACHABLE)
  1295. #define JSON_HEDLEY_UNREACHABLE() JSON_HEDLEY_ASSUME(0)
  1296. #endif
  1297. JSON_HEDLEY_DIAGNOSTIC_PUSH
  1298. #if JSON_HEDLEY_HAS_WARNING("-Wpedantic")
  1299. #pragma clang diagnostic ignored "-Wpedantic"
  1300. #endif
  1301. #if JSON_HEDLEY_HAS_WARNING("-Wc++98-compat-pedantic") && defined(__cplusplus)
  1302. #pragma clang diagnostic ignored "-Wc++98-compat-pedantic"
  1303. #endif
  1304. #if JSON_HEDLEY_GCC_HAS_WARNING("-Wvariadic-macros",4,0,0)
  1305. #if defined(__clang__)
  1306. #pragma clang diagnostic ignored "-Wvariadic-macros"
  1307. #elif defined(JSON_HEDLEY_GCC_VERSION)
  1308. #pragma GCC diagnostic ignored "-Wvariadic-macros"
  1309. #endif
  1310. #endif
  1311. #if defined(JSON_HEDLEY_NON_NULL)
  1312. #undef JSON_HEDLEY_NON_NULL
  1313. #endif
  1314. #if \
  1315. JSON_HEDLEY_HAS_ATTRIBUTE(nonnull) || \
  1316. JSON_HEDLEY_GCC_VERSION_CHECK(3,3,0) || \
  1317. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
  1318. JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0)
  1319. #define JSON_HEDLEY_NON_NULL(...) __attribute__((__nonnull__(__VA_ARGS__)))
  1320. #else
  1321. #define JSON_HEDLEY_NON_NULL(...)
  1322. #endif
  1323. JSON_HEDLEY_DIAGNOSTIC_POP
  1324. #if defined(JSON_HEDLEY_PRINTF_FORMAT)
  1325. #undef JSON_HEDLEY_PRINTF_FORMAT
  1326. #endif
  1327. #if defined(__MINGW32__) && JSON_HEDLEY_GCC_HAS_ATTRIBUTE(format,4,4,0) && !defined(__USE_MINGW_ANSI_STDIO)
  1328. #define JSON_HEDLEY_PRINTF_FORMAT(string_idx,first_to_check) __attribute__((__format__(ms_printf, string_idx, first_to_check)))
  1329. #elif defined(__MINGW32__) && JSON_HEDLEY_GCC_HAS_ATTRIBUTE(format,4,4,0) && defined(__USE_MINGW_ANSI_STDIO)
  1330. #define JSON_HEDLEY_PRINTF_FORMAT(string_idx,first_to_check) __attribute__((__format__(gnu_printf, string_idx, first_to_check)))
  1331. #elif \
  1332. JSON_HEDLEY_HAS_ATTRIBUTE(format) || \
  1333. JSON_HEDLEY_GCC_VERSION_CHECK(3,1,0) || \
  1334. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
  1335. JSON_HEDLEY_ARM_VERSION_CHECK(5,6,0) || \
  1336. JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \
  1337. JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \
  1338. (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  1339. JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \
  1340. (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  1341. JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \
  1342. (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  1343. JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \
  1344. (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  1345. JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \
  1346. JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \
  1347. JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \
  1348. JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10)
  1349. #define JSON_HEDLEY_PRINTF_FORMAT(string_idx,first_to_check) __attribute__((__format__(__printf__, string_idx, first_to_check)))
  1350. #elif JSON_HEDLEY_PELLES_VERSION_CHECK(6,0,0)
  1351. #define JSON_HEDLEY_PRINTF_FORMAT(string_idx,first_to_check) __declspec(vaformat(printf,string_idx,first_to_check))
  1352. #else
  1353. #define JSON_HEDLEY_PRINTF_FORMAT(string_idx,first_to_check)
  1354. #endif
  1355. #if defined(JSON_HEDLEY_CONSTEXPR)
  1356. #undef JSON_HEDLEY_CONSTEXPR
  1357. #endif
  1358. #if defined(__cplusplus)
  1359. #if __cplusplus >= 201103L
  1360. #define JSON_HEDLEY_CONSTEXPR JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_(constexpr)
  1361. #endif
  1362. #endif
  1363. #if !defined(JSON_HEDLEY_CONSTEXPR)
  1364. #define JSON_HEDLEY_CONSTEXPR
  1365. #endif
  1366. #if defined(JSON_HEDLEY_PREDICT)
  1367. #undef JSON_HEDLEY_PREDICT
  1368. #endif
  1369. #if defined(JSON_HEDLEY_LIKELY)
  1370. #undef JSON_HEDLEY_LIKELY
  1371. #endif
  1372. #if defined(JSON_HEDLEY_UNLIKELY)
  1373. #undef JSON_HEDLEY_UNLIKELY
  1374. #endif
  1375. #if defined(JSON_HEDLEY_UNPREDICTABLE)
  1376. #undef JSON_HEDLEY_UNPREDICTABLE
  1377. #endif
  1378. #if JSON_HEDLEY_HAS_BUILTIN(__builtin_unpredictable)
  1379. #define JSON_HEDLEY_UNPREDICTABLE(expr) __builtin_unpredictable((expr))
  1380. #endif
  1381. #if \
  1382. (JSON_HEDLEY_HAS_BUILTIN(__builtin_expect_with_probability) && !defined(JSON_HEDLEY_PGI_VERSION)) || \
  1383. JSON_HEDLEY_GCC_VERSION_CHECK(9,0,0) || \
  1384. JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10)
  1385. # define JSON_HEDLEY_PREDICT(expr, value, probability) __builtin_expect_with_probability( (expr), (value), (probability))
  1386. # define JSON_HEDLEY_PREDICT_TRUE(expr, probability) __builtin_expect_with_probability(!!(expr), 1 , (probability))
  1387. # define JSON_HEDLEY_PREDICT_FALSE(expr, probability) __builtin_expect_with_probability(!!(expr), 0 , (probability))
  1388. # define JSON_HEDLEY_LIKELY(expr) __builtin_expect (!!(expr), 1 )
  1389. # define JSON_HEDLEY_UNLIKELY(expr) __builtin_expect (!!(expr), 0 )
  1390. #elif \
  1391. (JSON_HEDLEY_HAS_BUILTIN(__builtin_expect) && !defined(JSON_HEDLEY_INTEL_CL_VERSION)) || \
  1392. JSON_HEDLEY_GCC_VERSION_CHECK(3,0,0) || \
  1393. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
  1394. (JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,15,0) && defined(__cplusplus)) || \
  1395. JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \
  1396. JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \
  1397. JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \
  1398. JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,7,0) || \
  1399. JSON_HEDLEY_TI_CL430_VERSION_CHECK(3,1,0) || \
  1400. JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,1,0) || \
  1401. JSON_HEDLEY_TI_CL6X_VERSION_CHECK(6,1,0) || \
  1402. JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \
  1403. JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \
  1404. JSON_HEDLEY_TINYC_VERSION_CHECK(0,9,27) || \
  1405. JSON_HEDLEY_CRAY_VERSION_CHECK(8,1,0) || \
  1406. JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10)
  1407. # define JSON_HEDLEY_PREDICT(expr, expected, probability) \
  1408. (((probability) >= 0.9) ? __builtin_expect((expr), (expected)) : (JSON_HEDLEY_STATIC_CAST(void, expected), (expr)))
  1409. # define JSON_HEDLEY_PREDICT_TRUE(expr, probability) \
  1410. (__extension__ ({ \
  1411. double hedley_probability_ = (probability); \
  1412. ((hedley_probability_ >= 0.9) ? __builtin_expect(!!(expr), 1) : ((hedley_probability_ <= 0.1) ? __builtin_expect(!!(expr), 0) : !!(expr))); \
  1413. }))
  1414. # define JSON_HEDLEY_PREDICT_FALSE(expr, probability) \
  1415. (__extension__ ({ \
  1416. double hedley_probability_ = (probability); \
  1417. ((hedley_probability_ >= 0.9) ? __builtin_expect(!!(expr), 0) : ((hedley_probability_ <= 0.1) ? __builtin_expect(!!(expr), 1) : !!(expr))); \
  1418. }))
  1419. # define JSON_HEDLEY_LIKELY(expr) __builtin_expect(!!(expr), 1)
  1420. # define JSON_HEDLEY_UNLIKELY(expr) __builtin_expect(!!(expr), 0)
  1421. #else
  1422. # define JSON_HEDLEY_PREDICT(expr, expected, probability) (JSON_HEDLEY_STATIC_CAST(void, expected), (expr))
  1423. # define JSON_HEDLEY_PREDICT_TRUE(expr, probability) (!!(expr))
  1424. # define JSON_HEDLEY_PREDICT_FALSE(expr, probability) (!!(expr))
  1425. # define JSON_HEDLEY_LIKELY(expr) (!!(expr))
  1426. # define JSON_HEDLEY_UNLIKELY(expr) (!!(expr))
  1427. #endif
  1428. #if !defined(JSON_HEDLEY_UNPREDICTABLE)
  1429. #define JSON_HEDLEY_UNPREDICTABLE(expr) JSON_HEDLEY_PREDICT(expr, 1, 0.5)
  1430. #endif
  1431. #if defined(JSON_HEDLEY_MALLOC)
  1432. #undef JSON_HEDLEY_MALLOC
  1433. #endif
  1434. #if \
  1435. JSON_HEDLEY_HAS_ATTRIBUTE(malloc) || \
  1436. JSON_HEDLEY_GCC_VERSION_CHECK(3,1,0) || \
  1437. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
  1438. JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,11,0) || \
  1439. JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \
  1440. JSON_HEDLEY_IBM_VERSION_CHECK(12,1,0) || \
  1441. JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \
  1442. (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  1443. JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \
  1444. (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  1445. JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \
  1446. (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  1447. JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \
  1448. (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  1449. JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \
  1450. JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \
  1451. JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \
  1452. JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10)
  1453. #define JSON_HEDLEY_MALLOC __attribute__((__malloc__))
  1454. #elif JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,10,0)
  1455. #define JSON_HEDLEY_MALLOC _Pragma("returns_new_memory")
  1456. #elif \
  1457. JSON_HEDLEY_MSVC_VERSION_CHECK(14,0,0) || \
  1458. JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0)
  1459. #define JSON_HEDLEY_MALLOC __declspec(restrict)
  1460. #else
  1461. #define JSON_HEDLEY_MALLOC
  1462. #endif
  1463. #if defined(JSON_HEDLEY_PURE)
  1464. #undef JSON_HEDLEY_PURE
  1465. #endif
  1466. #if \
  1467. JSON_HEDLEY_HAS_ATTRIBUTE(pure) || \
  1468. JSON_HEDLEY_GCC_VERSION_CHECK(2,96,0) || \
  1469. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
  1470. JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,11,0) || \
  1471. JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \
  1472. JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \
  1473. JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \
  1474. (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  1475. JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \
  1476. (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  1477. JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \
  1478. (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  1479. JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \
  1480. (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  1481. JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \
  1482. JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \
  1483. JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \
  1484. JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0) || \
  1485. JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10)
  1486. # define JSON_HEDLEY_PURE __attribute__((__pure__))
  1487. #elif JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,10,0)
  1488. # define JSON_HEDLEY_PURE _Pragma("does_not_write_global_data")
  1489. #elif defined(__cplusplus) && \
  1490. ( \
  1491. JSON_HEDLEY_TI_CL430_VERSION_CHECK(2,0,1) || \
  1492. JSON_HEDLEY_TI_CL6X_VERSION_CHECK(4,0,0) || \
  1493. JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) \
  1494. )
  1495. # define JSON_HEDLEY_PURE _Pragma("FUNC_IS_PURE;")
  1496. #else
  1497. # define JSON_HEDLEY_PURE
  1498. #endif
  1499. #if defined(JSON_HEDLEY_CONST)
  1500. #undef JSON_HEDLEY_CONST
  1501. #endif
  1502. #if \
  1503. JSON_HEDLEY_HAS_ATTRIBUTE(const) || \
  1504. JSON_HEDLEY_GCC_VERSION_CHECK(2,5,0) || \
  1505. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
  1506. JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,11,0) || \
  1507. JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \
  1508. JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \
  1509. JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \
  1510. (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  1511. JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \
  1512. (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  1513. JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \
  1514. (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  1515. JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \
  1516. (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  1517. JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \
  1518. JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \
  1519. JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \
  1520. JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0) || \
  1521. JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10)
  1522. #define JSON_HEDLEY_CONST __attribute__((__const__))
  1523. #elif \
  1524. JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,10,0)
  1525. #define JSON_HEDLEY_CONST _Pragma("no_side_effect")
  1526. #else
  1527. #define JSON_HEDLEY_CONST JSON_HEDLEY_PURE
  1528. #endif
  1529. #if defined(JSON_HEDLEY_RESTRICT)
  1530. #undef JSON_HEDLEY_RESTRICT
  1531. #endif
  1532. #if defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) && !defined(__cplusplus)
  1533. #define JSON_HEDLEY_RESTRICT restrict
  1534. #elif \
  1535. JSON_HEDLEY_GCC_VERSION_CHECK(3,1,0) || \
  1536. JSON_HEDLEY_MSVC_VERSION_CHECK(14,0,0) || \
  1537. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
  1538. JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) || \
  1539. JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \
  1540. JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \
  1541. JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0) || \
  1542. JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \
  1543. JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,2,4) || \
  1544. JSON_HEDLEY_TI_CL6X_VERSION_CHECK(8,1,0) || \
  1545. JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \
  1546. (JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,14,0) && defined(__cplusplus)) || \
  1547. JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0) || \
  1548. defined(__clang__) || \
  1549. JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10)
  1550. #define JSON_HEDLEY_RESTRICT __restrict
  1551. #elif JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,3,0) && !defined(__cplusplus)
  1552. #define JSON_HEDLEY_RESTRICT _Restrict
  1553. #else
  1554. #define JSON_HEDLEY_RESTRICT
  1555. #endif
  1556. #if defined(JSON_HEDLEY_INLINE)
  1557. #undef JSON_HEDLEY_INLINE
  1558. #endif
  1559. #if \
  1560. (defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L)) || \
  1561. (defined(__cplusplus) && (__cplusplus >= 199711L))
  1562. #define JSON_HEDLEY_INLINE inline
  1563. #elif \
  1564. defined(JSON_HEDLEY_GCC_VERSION) || \
  1565. JSON_HEDLEY_ARM_VERSION_CHECK(6,2,0)
  1566. #define JSON_HEDLEY_INLINE __inline__
  1567. #elif \
  1568. JSON_HEDLEY_MSVC_VERSION_CHECK(12,0,0) || \
  1569. JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) || \
  1570. JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \
  1571. JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,1,0) || \
  1572. JSON_HEDLEY_TI_CL430_VERSION_CHECK(3,1,0) || \
  1573. JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,2,0) || \
  1574. JSON_HEDLEY_TI_CL6X_VERSION_CHECK(8,0,0) || \
  1575. JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \
  1576. JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \
  1577. JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10)
  1578. #define JSON_HEDLEY_INLINE __inline
  1579. #else
  1580. #define JSON_HEDLEY_INLINE
  1581. #endif
  1582. #if defined(JSON_HEDLEY_ALWAYS_INLINE)
  1583. #undef JSON_HEDLEY_ALWAYS_INLINE
  1584. #endif
  1585. #if \
  1586. JSON_HEDLEY_HAS_ATTRIBUTE(always_inline) || \
  1587. JSON_HEDLEY_GCC_VERSION_CHECK(4,0,0) || \
  1588. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
  1589. JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,11,0) || \
  1590. JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \
  1591. JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \
  1592. JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \
  1593. (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  1594. JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \
  1595. (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  1596. JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \
  1597. (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  1598. JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \
  1599. (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  1600. JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \
  1601. JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \
  1602. JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \
  1603. JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) || \
  1604. JSON_HEDLEY_IAR_VERSION_CHECK(8,10,0)
  1605. # define JSON_HEDLEY_ALWAYS_INLINE __attribute__((__always_inline__)) JSON_HEDLEY_INLINE
  1606. #elif \
  1607. JSON_HEDLEY_MSVC_VERSION_CHECK(12,0,0) || \
  1608. JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0)
  1609. # define JSON_HEDLEY_ALWAYS_INLINE __forceinline
  1610. #elif defined(__cplusplus) && \
  1611. ( \
  1612. JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \
  1613. JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \
  1614. JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \
  1615. JSON_HEDLEY_TI_CL6X_VERSION_CHECK(6,1,0) || \
  1616. JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \
  1617. JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) \
  1618. )
  1619. # define JSON_HEDLEY_ALWAYS_INLINE _Pragma("FUNC_ALWAYS_INLINE;")
  1620. #elif JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0)
  1621. # define JSON_HEDLEY_ALWAYS_INLINE _Pragma("inline=forced")
  1622. #else
  1623. # define JSON_HEDLEY_ALWAYS_INLINE JSON_HEDLEY_INLINE
  1624. #endif
  1625. #if defined(JSON_HEDLEY_NEVER_INLINE)
  1626. #undef JSON_HEDLEY_NEVER_INLINE
  1627. #endif
  1628. #if \
  1629. JSON_HEDLEY_HAS_ATTRIBUTE(noinline) || \
  1630. JSON_HEDLEY_GCC_VERSION_CHECK(4,0,0) || \
  1631. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
  1632. JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,11,0) || \
  1633. JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \
  1634. JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \
  1635. JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \
  1636. (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  1637. JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \
  1638. (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  1639. JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \
  1640. (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  1641. JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \
  1642. (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  1643. JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \
  1644. JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \
  1645. JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \
  1646. JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) || \
  1647. JSON_HEDLEY_IAR_VERSION_CHECK(8,10,0)
  1648. #define JSON_HEDLEY_NEVER_INLINE __attribute__((__noinline__))
  1649. #elif \
  1650. JSON_HEDLEY_MSVC_VERSION_CHECK(13,10,0) || \
  1651. JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0)
  1652. #define JSON_HEDLEY_NEVER_INLINE __declspec(noinline)
  1653. #elif JSON_HEDLEY_PGI_VERSION_CHECK(10,2,0)
  1654. #define JSON_HEDLEY_NEVER_INLINE _Pragma("noinline")
  1655. #elif JSON_HEDLEY_TI_CL6X_VERSION_CHECK(6,0,0) && defined(__cplusplus)
  1656. #define JSON_HEDLEY_NEVER_INLINE _Pragma("FUNC_CANNOT_INLINE;")
  1657. #elif JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0)
  1658. #define JSON_HEDLEY_NEVER_INLINE _Pragma("inline=never")
  1659. #elif JSON_HEDLEY_COMPCERT_VERSION_CHECK(3,2,0)
  1660. #define JSON_HEDLEY_NEVER_INLINE __attribute((noinline))
  1661. #elif JSON_HEDLEY_PELLES_VERSION_CHECK(9,0,0)
  1662. #define JSON_HEDLEY_NEVER_INLINE __declspec(noinline)
  1663. #else
  1664. #define JSON_HEDLEY_NEVER_INLINE
  1665. #endif
  1666. #if defined(JSON_HEDLEY_PRIVATE)
  1667. #undef JSON_HEDLEY_PRIVATE
  1668. #endif
  1669. #if defined(JSON_HEDLEY_PUBLIC)
  1670. #undef JSON_HEDLEY_PUBLIC
  1671. #endif
  1672. #if defined(JSON_HEDLEY_IMPORT)
  1673. #undef JSON_HEDLEY_IMPORT
  1674. #endif
  1675. #if defined(_WIN32) || defined(__CYGWIN__)
  1676. # define JSON_HEDLEY_PRIVATE
  1677. # define JSON_HEDLEY_PUBLIC __declspec(dllexport)
  1678. # define JSON_HEDLEY_IMPORT __declspec(dllimport)
  1679. #else
  1680. # if \
  1681. JSON_HEDLEY_HAS_ATTRIBUTE(visibility) || \
  1682. JSON_HEDLEY_GCC_VERSION_CHECK(3,3,0) || \
  1683. JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,11,0) || \
  1684. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
  1685. JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \
  1686. JSON_HEDLEY_IBM_VERSION_CHECK(13,1,0) || \
  1687. ( \
  1688. defined(__TI_EABI__) && \
  1689. ( \
  1690. (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  1691. JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) \
  1692. ) \
  1693. ) || \
  1694. JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10)
  1695. # define JSON_HEDLEY_PRIVATE __attribute__((__visibility__("hidden")))
  1696. # define JSON_HEDLEY_PUBLIC __attribute__((__visibility__("default")))
  1697. # else
  1698. # define JSON_HEDLEY_PRIVATE
  1699. # define JSON_HEDLEY_PUBLIC
  1700. # endif
  1701. # define JSON_HEDLEY_IMPORT extern
  1702. #endif
  1703. #if defined(JSON_HEDLEY_NO_THROW)
  1704. #undef JSON_HEDLEY_NO_THROW
  1705. #endif
  1706. #if \
  1707. JSON_HEDLEY_HAS_ATTRIBUTE(nothrow) || \
  1708. JSON_HEDLEY_GCC_VERSION_CHECK(3,3,0) || \
  1709. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
  1710. JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10)
  1711. #define JSON_HEDLEY_NO_THROW __attribute__((__nothrow__))
  1712. #elif \
  1713. JSON_HEDLEY_MSVC_VERSION_CHECK(13,1,0) || \
  1714. JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) || \
  1715. JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0)
  1716. #define JSON_HEDLEY_NO_THROW __declspec(nothrow)
  1717. #else
  1718. #define JSON_HEDLEY_NO_THROW
  1719. #endif
  1720. #if defined(JSON_HEDLEY_FALL_THROUGH)
  1721. #undef JSON_HEDLEY_FALL_THROUGH
  1722. #endif
  1723. #if \
  1724. JSON_HEDLEY_HAS_ATTRIBUTE(fallthrough) || \
  1725. JSON_HEDLEY_GCC_VERSION_CHECK(7,0,0) || \
  1726. JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10)
  1727. #define JSON_HEDLEY_FALL_THROUGH __attribute__((__fallthrough__))
  1728. #elif JSON_HEDLEY_HAS_CPP_ATTRIBUTE_NS(clang,fallthrough)
  1729. #define JSON_HEDLEY_FALL_THROUGH JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[clang::fallthrough]])
  1730. #elif JSON_HEDLEY_HAS_CPP_ATTRIBUTE(fallthrough)
  1731. #define JSON_HEDLEY_FALL_THROUGH JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[fallthrough]])
  1732. #elif defined(__fallthrough) /* SAL */
  1733. #define JSON_HEDLEY_FALL_THROUGH __fallthrough
  1734. #else
  1735. #define JSON_HEDLEY_FALL_THROUGH
  1736. #endif
  1737. #if defined(JSON_HEDLEY_RETURNS_NON_NULL)
  1738. #undef JSON_HEDLEY_RETURNS_NON_NULL
  1739. #endif
  1740. #if \
  1741. JSON_HEDLEY_HAS_ATTRIBUTE(returns_nonnull) || \
  1742. JSON_HEDLEY_GCC_VERSION_CHECK(4,9,0) || \
  1743. JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10)
  1744. #define JSON_HEDLEY_RETURNS_NON_NULL __attribute__((__returns_nonnull__))
  1745. #elif defined(_Ret_notnull_) /* SAL */
  1746. #define JSON_HEDLEY_RETURNS_NON_NULL _Ret_notnull_
  1747. #else
  1748. #define JSON_HEDLEY_RETURNS_NON_NULL
  1749. #endif
  1750. #if defined(JSON_HEDLEY_ARRAY_PARAM)
  1751. #undef JSON_HEDLEY_ARRAY_PARAM
  1752. #endif
  1753. #if \
  1754. defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) && \
  1755. !defined(__STDC_NO_VLA__) && \
  1756. !defined(__cplusplus) && \
  1757. !defined(JSON_HEDLEY_PGI_VERSION) && \
  1758. !defined(JSON_HEDLEY_TINYC_VERSION)
  1759. #define JSON_HEDLEY_ARRAY_PARAM(name) (name)
  1760. #else
  1761. #define JSON_HEDLEY_ARRAY_PARAM(name)
  1762. #endif
  1763. #if defined(JSON_HEDLEY_IS_CONSTANT)
  1764. #undef JSON_HEDLEY_IS_CONSTANT
  1765. #endif
  1766. #if defined(JSON_HEDLEY_REQUIRE_CONSTEXPR)
  1767. #undef JSON_HEDLEY_REQUIRE_CONSTEXPR
  1768. #endif
  1769. /* JSON_HEDLEY_IS_CONSTEXPR_ is for
  1770. HEDLEY INTERNAL USE ONLY. API subject to change without notice. */
  1771. #if defined(JSON_HEDLEY_IS_CONSTEXPR_)
  1772. #undef JSON_HEDLEY_IS_CONSTEXPR_
  1773. #endif
  1774. #if \
  1775. JSON_HEDLEY_HAS_BUILTIN(__builtin_constant_p) || \
  1776. JSON_HEDLEY_GCC_VERSION_CHECK(3,4,0) || \
  1777. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
  1778. JSON_HEDLEY_TINYC_VERSION_CHECK(0,9,19) || \
  1779. JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \
  1780. JSON_HEDLEY_IBM_VERSION_CHECK(13,1,0) || \
  1781. JSON_HEDLEY_TI_CL6X_VERSION_CHECK(6,1,0) || \
  1782. (JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,10,0) && !defined(__cplusplus)) || \
  1783. JSON_HEDLEY_CRAY_VERSION_CHECK(8,1,0) || \
  1784. JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10)
  1785. #define JSON_HEDLEY_IS_CONSTANT(expr) __builtin_constant_p(expr)
  1786. #endif
  1787. #if !defined(__cplusplus)
  1788. # if \
  1789. JSON_HEDLEY_HAS_BUILTIN(__builtin_types_compatible_p) || \
  1790. JSON_HEDLEY_GCC_VERSION_CHECK(3,4,0) || \
  1791. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
  1792. JSON_HEDLEY_IBM_VERSION_CHECK(13,1,0) || \
  1793. JSON_HEDLEY_CRAY_VERSION_CHECK(8,1,0) || \
  1794. JSON_HEDLEY_ARM_VERSION_CHECK(5,4,0) || \
  1795. JSON_HEDLEY_TINYC_VERSION_CHECK(0,9,24)
  1796. #if defined(__INTPTR_TYPE__)
  1797. #define JSON_HEDLEY_IS_CONSTEXPR_(expr) __builtin_types_compatible_p(__typeof__((1 ? (void*) ((__INTPTR_TYPE__) ((expr) * 0)) : (int*) 0)), int*)
  1798. #else
  1799. #include <stdint.h>
  1800. #define JSON_HEDLEY_IS_CONSTEXPR_(expr) __builtin_types_compatible_p(__typeof__((1 ? (void*) ((intptr_t) ((expr) * 0)) : (int*) 0)), int*)
  1801. #endif
  1802. # elif \
  1803. ( \
  1804. defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 201112L) && \
  1805. !defined(JSON_HEDLEY_SUNPRO_VERSION) && \
  1806. !defined(JSON_HEDLEY_PGI_VERSION) && \
  1807. !defined(JSON_HEDLEY_IAR_VERSION)) || \
  1808. (JSON_HEDLEY_HAS_EXTENSION(c_generic_selections) && !defined(JSON_HEDLEY_IAR_VERSION)) || \
  1809. JSON_HEDLEY_GCC_VERSION_CHECK(4,9,0) || \
  1810. JSON_HEDLEY_INTEL_VERSION_CHECK(17,0,0) || \
  1811. JSON_HEDLEY_IBM_VERSION_CHECK(12,1,0) || \
  1812. JSON_HEDLEY_ARM_VERSION_CHECK(5,3,0)
  1813. #if defined(__INTPTR_TYPE__)
  1814. #define JSON_HEDLEY_IS_CONSTEXPR_(expr) _Generic((1 ? (void*) ((__INTPTR_TYPE__) ((expr) * 0)) : (int*) 0), int*: 1, void*: 0)
  1815. #else
  1816. #include <stdint.h>
  1817. #define JSON_HEDLEY_IS_CONSTEXPR_(expr) _Generic((1 ? (void*) ((intptr_t) * 0) : (int*) 0), int*: 1, void*: 0)
  1818. #endif
  1819. # elif \
  1820. defined(JSON_HEDLEY_GCC_VERSION) || \
  1821. defined(JSON_HEDLEY_INTEL_VERSION) || \
  1822. defined(JSON_HEDLEY_TINYC_VERSION) || \
  1823. defined(JSON_HEDLEY_TI_ARMCL_VERSION) || \
  1824. JSON_HEDLEY_TI_CL430_VERSION_CHECK(18,12,0) || \
  1825. defined(JSON_HEDLEY_TI_CL2000_VERSION) || \
  1826. defined(JSON_HEDLEY_TI_CL6X_VERSION) || \
  1827. defined(JSON_HEDLEY_TI_CL7X_VERSION) || \
  1828. defined(JSON_HEDLEY_TI_CLPRU_VERSION) || \
  1829. defined(__clang__)
  1830. # define JSON_HEDLEY_IS_CONSTEXPR_(expr) ( \
  1831. sizeof(void) != \
  1832. sizeof(*( \
  1833. 1 ? \
  1834. ((void*) ((expr) * 0L) ) : \
  1835. ((struct { char v[sizeof(void) * 2]; } *) 1) \
  1836. ) \
  1837. ) \
  1838. )
  1839. # endif
  1840. #endif
  1841. #if defined(JSON_HEDLEY_IS_CONSTEXPR_)
  1842. #if !defined(JSON_HEDLEY_IS_CONSTANT)
  1843. #define JSON_HEDLEY_IS_CONSTANT(expr) JSON_HEDLEY_IS_CONSTEXPR_(expr)
  1844. #endif
  1845. #define JSON_HEDLEY_REQUIRE_CONSTEXPR(expr) (JSON_HEDLEY_IS_CONSTEXPR_(expr) ? (expr) : (-1))
  1846. #else
  1847. #if !defined(JSON_HEDLEY_IS_CONSTANT)
  1848. #define JSON_HEDLEY_IS_CONSTANT(expr) (0)
  1849. #endif
  1850. #define JSON_HEDLEY_REQUIRE_CONSTEXPR(expr) (expr)
  1851. #endif
  1852. #if defined(JSON_HEDLEY_BEGIN_C_DECLS)
  1853. #undef JSON_HEDLEY_BEGIN_C_DECLS
  1854. #endif
  1855. #if defined(JSON_HEDLEY_END_C_DECLS)
  1856. #undef JSON_HEDLEY_END_C_DECLS
  1857. #endif
  1858. #if defined(JSON_HEDLEY_C_DECL)
  1859. #undef JSON_HEDLEY_C_DECL
  1860. #endif
  1861. #if defined(__cplusplus)
  1862. #define JSON_HEDLEY_BEGIN_C_DECLS extern "C" {
  1863. #define JSON_HEDLEY_END_C_DECLS }
  1864. #define JSON_HEDLEY_C_DECL extern "C"
  1865. #else
  1866. #define JSON_HEDLEY_BEGIN_C_DECLS
  1867. #define JSON_HEDLEY_END_C_DECLS
  1868. #define JSON_HEDLEY_C_DECL
  1869. #endif
  1870. #if defined(JSON_HEDLEY_STATIC_ASSERT)
  1871. #undef JSON_HEDLEY_STATIC_ASSERT
  1872. #endif
  1873. #if \
  1874. !defined(__cplusplus) && ( \
  1875. (defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 201112L)) || \
  1876. (JSON_HEDLEY_HAS_FEATURE(c_static_assert) && !defined(JSON_HEDLEY_INTEL_CL_VERSION)) || \
  1877. JSON_HEDLEY_GCC_VERSION_CHECK(6,0,0) || \
  1878. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
  1879. defined(_Static_assert) \
  1880. )
  1881. # define JSON_HEDLEY_STATIC_ASSERT(expr, message) _Static_assert(expr, message)
  1882. #elif \
  1883. (defined(__cplusplus) && (__cplusplus >= 201103L)) || \
  1884. JSON_HEDLEY_MSVC_VERSION_CHECK(16,0,0) || \
  1885. JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0)
  1886. # define JSON_HEDLEY_STATIC_ASSERT(expr, message) JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_(static_assert(expr, message))
  1887. #else
  1888. # define JSON_HEDLEY_STATIC_ASSERT(expr, message)
  1889. #endif
  1890. #if defined(JSON_HEDLEY_NULL)
  1891. #undef JSON_HEDLEY_NULL
  1892. #endif
  1893. #if defined(__cplusplus)
  1894. #if __cplusplus >= 201103L
  1895. #define JSON_HEDLEY_NULL JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_(nullptr)
  1896. #elif defined(NULL)
  1897. #define JSON_HEDLEY_NULL NULL
  1898. #else
  1899. #define JSON_HEDLEY_NULL JSON_HEDLEY_STATIC_CAST(void*, 0)
  1900. #endif
  1901. #elif defined(NULL)
  1902. #define JSON_HEDLEY_NULL NULL
  1903. #else
  1904. #define JSON_HEDLEY_NULL ((void*) 0)
  1905. #endif
  1906. #if defined(JSON_HEDLEY_MESSAGE)
  1907. #undef JSON_HEDLEY_MESSAGE
  1908. #endif
  1909. #if JSON_HEDLEY_HAS_WARNING("-Wunknown-pragmas")
  1910. # define JSON_HEDLEY_MESSAGE(msg) \
  1911. JSON_HEDLEY_DIAGNOSTIC_PUSH \
  1912. JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS \
  1913. JSON_HEDLEY_PRAGMA(message msg) \
  1914. JSON_HEDLEY_DIAGNOSTIC_POP
  1915. #elif \
  1916. JSON_HEDLEY_GCC_VERSION_CHECK(4,4,0) || \
  1917. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0)
  1918. # define JSON_HEDLEY_MESSAGE(msg) JSON_HEDLEY_PRAGMA(message msg)
  1919. #elif JSON_HEDLEY_CRAY_VERSION_CHECK(5,0,0)
  1920. # define JSON_HEDLEY_MESSAGE(msg) JSON_HEDLEY_PRAGMA(_CRI message msg)
  1921. #elif JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0)
  1922. # define JSON_HEDLEY_MESSAGE(msg) JSON_HEDLEY_PRAGMA(message(msg))
  1923. #elif JSON_HEDLEY_PELLES_VERSION_CHECK(2,0,0)
  1924. # define JSON_HEDLEY_MESSAGE(msg) JSON_HEDLEY_PRAGMA(message(msg))
  1925. #else
  1926. # define JSON_HEDLEY_MESSAGE(msg)
  1927. #endif
  1928. #if defined(JSON_HEDLEY_WARNING)
  1929. #undef JSON_HEDLEY_WARNING
  1930. #endif
  1931. #if JSON_HEDLEY_HAS_WARNING("-Wunknown-pragmas")
  1932. # define JSON_HEDLEY_WARNING(msg) \
  1933. JSON_HEDLEY_DIAGNOSTIC_PUSH \
  1934. JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS \
  1935. JSON_HEDLEY_PRAGMA(clang warning msg) \
  1936. JSON_HEDLEY_DIAGNOSTIC_POP
  1937. #elif \
  1938. JSON_HEDLEY_GCC_VERSION_CHECK(4,8,0) || \
  1939. JSON_HEDLEY_PGI_VERSION_CHECK(18,4,0) || \
  1940. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0)
  1941. # define JSON_HEDLEY_WARNING(msg) JSON_HEDLEY_PRAGMA(GCC warning msg)
  1942. #elif \
  1943. JSON_HEDLEY_MSVC_VERSION_CHECK(15,0,0) || \
  1944. JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0)
  1945. # define JSON_HEDLEY_WARNING(msg) JSON_HEDLEY_PRAGMA(message(msg))
  1946. #else
  1947. # define JSON_HEDLEY_WARNING(msg) JSON_HEDLEY_MESSAGE(msg)
  1948. #endif
  1949. #if defined(JSON_HEDLEY_REQUIRE)
  1950. #undef JSON_HEDLEY_REQUIRE
  1951. #endif
  1952. #if defined(JSON_HEDLEY_REQUIRE_MSG)
  1953. #undef JSON_HEDLEY_REQUIRE_MSG
  1954. #endif
  1955. #if JSON_HEDLEY_HAS_ATTRIBUTE(diagnose_if)
  1956. # if JSON_HEDLEY_HAS_WARNING("-Wgcc-compat")
  1957. # define JSON_HEDLEY_REQUIRE(expr) \
  1958. JSON_HEDLEY_DIAGNOSTIC_PUSH \
  1959. _Pragma("clang diagnostic ignored \"-Wgcc-compat\"") \
  1960. __attribute__((diagnose_if(!(expr), #expr, "error"))) \
  1961. JSON_HEDLEY_DIAGNOSTIC_POP
  1962. # define JSON_HEDLEY_REQUIRE_MSG(expr,msg) \
  1963. JSON_HEDLEY_DIAGNOSTIC_PUSH \
  1964. _Pragma("clang diagnostic ignored \"-Wgcc-compat\"") \
  1965. __attribute__((diagnose_if(!(expr), msg, "error"))) \
  1966. JSON_HEDLEY_DIAGNOSTIC_POP
  1967. # else
  1968. # define JSON_HEDLEY_REQUIRE(expr) __attribute__((diagnose_if(!(expr), #expr, "error")))
  1969. # define JSON_HEDLEY_REQUIRE_MSG(expr,msg) __attribute__((diagnose_if(!(expr), msg, "error")))
  1970. # endif
  1971. #else
  1972. # define JSON_HEDLEY_REQUIRE(expr)
  1973. # define JSON_HEDLEY_REQUIRE_MSG(expr,msg)
  1974. #endif
  1975. #if defined(JSON_HEDLEY_FLAGS)
  1976. #undef JSON_HEDLEY_FLAGS
  1977. #endif
  1978. #if JSON_HEDLEY_HAS_ATTRIBUTE(flag_enum) && (!defined(__cplusplus) || JSON_HEDLEY_HAS_WARNING("-Wbitfield-enum-conversion"))
  1979. #define JSON_HEDLEY_FLAGS __attribute__((__flag_enum__))
  1980. #else
  1981. #define JSON_HEDLEY_FLAGS
  1982. #endif
  1983. #if defined(JSON_HEDLEY_FLAGS_CAST)
  1984. #undef JSON_HEDLEY_FLAGS_CAST
  1985. #endif
  1986. #if JSON_HEDLEY_INTEL_VERSION_CHECK(19,0,0)
  1987. # define JSON_HEDLEY_FLAGS_CAST(T, expr) (__extension__ ({ \
  1988. JSON_HEDLEY_DIAGNOSTIC_PUSH \
  1989. _Pragma("warning(disable:188)") \
  1990. ((T) (expr)); \
  1991. JSON_HEDLEY_DIAGNOSTIC_POP \
  1992. }))
  1993. #else
  1994. # define JSON_HEDLEY_FLAGS_CAST(T, expr) JSON_HEDLEY_STATIC_CAST(T, expr)
  1995. #endif
  1996. #if defined(JSON_HEDLEY_EMPTY_BASES)
  1997. #undef JSON_HEDLEY_EMPTY_BASES
  1998. #endif
  1999. #if \
  2000. (JSON_HEDLEY_MSVC_VERSION_CHECK(19,0,23918) && !JSON_HEDLEY_MSVC_VERSION_CHECK(20,0,0)) || \
  2001. JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0)
  2002. #define JSON_HEDLEY_EMPTY_BASES __declspec(empty_bases)
  2003. #else
  2004. #define JSON_HEDLEY_EMPTY_BASES
  2005. #endif
  2006. /* Remaining macros are deprecated. */
  2007. #if defined(JSON_HEDLEY_GCC_NOT_CLANG_VERSION_CHECK)
  2008. #undef JSON_HEDLEY_GCC_NOT_CLANG_VERSION_CHECK
  2009. #endif
  2010. #if defined(__clang__)
  2011. #define JSON_HEDLEY_GCC_NOT_CLANG_VERSION_CHECK(major,minor,patch) (0)
  2012. #else
  2013. #define JSON_HEDLEY_GCC_NOT_CLANG_VERSION_CHECK(major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch)
  2014. #endif
  2015. #if defined(JSON_HEDLEY_CLANG_HAS_ATTRIBUTE)
  2016. #undef JSON_HEDLEY_CLANG_HAS_ATTRIBUTE
  2017. #endif
  2018. #define JSON_HEDLEY_CLANG_HAS_ATTRIBUTE(attribute) JSON_HEDLEY_HAS_ATTRIBUTE(attribute)
  2019. #if defined(JSON_HEDLEY_CLANG_HAS_CPP_ATTRIBUTE)
  2020. #undef JSON_HEDLEY_CLANG_HAS_CPP_ATTRIBUTE
  2021. #endif
  2022. #define JSON_HEDLEY_CLANG_HAS_CPP_ATTRIBUTE(attribute) JSON_HEDLEY_HAS_CPP_ATTRIBUTE(attribute)
  2023. #if defined(JSON_HEDLEY_CLANG_HAS_BUILTIN)
  2024. #undef JSON_HEDLEY_CLANG_HAS_BUILTIN
  2025. #endif
  2026. #define JSON_HEDLEY_CLANG_HAS_BUILTIN(builtin) JSON_HEDLEY_HAS_BUILTIN(builtin)
  2027. #if defined(JSON_HEDLEY_CLANG_HAS_FEATURE)
  2028. #undef JSON_HEDLEY_CLANG_HAS_FEATURE
  2029. #endif
  2030. #define JSON_HEDLEY_CLANG_HAS_FEATURE(feature) JSON_HEDLEY_HAS_FEATURE(feature)
  2031. #if defined(JSON_HEDLEY_CLANG_HAS_EXTENSION)
  2032. #undef JSON_HEDLEY_CLANG_HAS_EXTENSION
  2033. #endif
  2034. #define JSON_HEDLEY_CLANG_HAS_EXTENSION(extension) JSON_HEDLEY_HAS_EXTENSION(extension)
  2035. #if defined(JSON_HEDLEY_CLANG_HAS_DECLSPEC_DECLSPEC_ATTRIBUTE)
  2036. #undef JSON_HEDLEY_CLANG_HAS_DECLSPEC_DECLSPEC_ATTRIBUTE
  2037. #endif
  2038. #define JSON_HEDLEY_CLANG_HAS_DECLSPEC_ATTRIBUTE(attribute) JSON_HEDLEY_HAS_DECLSPEC_ATTRIBUTE(attribute)
  2039. #if defined(JSON_HEDLEY_CLANG_HAS_WARNING)
  2040. #undef JSON_HEDLEY_CLANG_HAS_WARNING
  2041. #endif
  2042. #define JSON_HEDLEY_CLANG_HAS_WARNING(warning) JSON_HEDLEY_HAS_WARNING(warning)
  2043. #endif /* !defined(JSON_HEDLEY_VERSION) || (JSON_HEDLEY_VERSION < X) */
  2044. // #include <nlohmann/detail/meta/detected.hpp>
  2045. #include <type_traits>
  2046. // #include <nlohmann/detail/meta/void_t.hpp>
  2047. namespace nlohmann
  2048. {
  2049. namespace detail
  2050. {
  2051. template<typename ...Ts> struct make_void
  2052. {
  2053. using type = void;
  2054. };
  2055. template<typename ...Ts> using void_t = typename make_void<Ts...>::type;
  2056. } // namespace detail
  2057. } // namespace nlohmann
  2058. // https://en.cppreference.com/w/cpp/experimental/is_detected
  2059. namespace nlohmann
  2060. {
  2061. namespace detail
  2062. {
  2063. struct nonesuch
  2064. {
  2065. nonesuch() = delete;
  2066. ~nonesuch() = delete;
  2067. nonesuch(nonesuch const&) = delete;
  2068. nonesuch(nonesuch const&&) = delete;
  2069. void operator=(nonesuch const&) = delete;
  2070. void operator=(nonesuch&&) = delete;
  2071. };
  2072. template<class Default,
  2073. class AlwaysVoid,
  2074. template<class...> class Op,
  2075. class... Args>
  2076. struct detector
  2077. {
  2078. using value_t = std::false_type;
  2079. using type = Default;
  2080. };
  2081. template<class Default, template<class...> class Op, class... Args>
  2082. struct detector<Default, void_t<Op<Args...>>, Op, Args...>
  2083. {
  2084. using value_t = std::true_type;
  2085. using type = Op<Args...>;
  2086. };
  2087. template<template<class...> class Op, class... Args>
  2088. using is_detected = typename detector<nonesuch, void, Op, Args...>::value_t;
  2089. template<template<class...> class Op, class... Args>
  2090. struct is_detected_lazy : is_detected<Op, Args...> { };
  2091. template<template<class...> class Op, class... Args>
  2092. using detected_t = typename detector<nonesuch, void, Op, Args...>::type;
  2093. template<class Default, template<class...> class Op, class... Args>
  2094. using detected_or = detector<Default, void, Op, Args...>;
  2095. template<class Default, template<class...> class Op, class... Args>
  2096. using detected_or_t = typename detected_or<Default, Op, Args...>::type;
  2097. template<class Expected, template<class...> class Op, class... Args>
  2098. using is_detected_exact = std::is_same<Expected, detected_t<Op, Args...>>;
  2099. template<class To, template<class...> class Op, class... Args>
  2100. using is_detected_convertible =
  2101. std::is_convertible<detected_t<Op, Args...>, To>;
  2102. } // namespace detail
  2103. } // namespace nlohmann
  2104. // This file contains all internal macro definitions
  2105. // You MUST include macro_unscope.hpp at the end of json.hpp to undef all of them
  2106. // exclude unsupported compilers
  2107. #if !defined(JSON_SKIP_UNSUPPORTED_COMPILER_CHECK)
  2108. #if defined(__clang__)
  2109. #if (__clang_major__ * 10000 + __clang_minor__ * 100 + __clang_patchlevel__) < 30400
  2110. #error "unsupported Clang version - see https://github.com/nlohmann/json#supported-compilers"
  2111. #endif
  2112. #elif defined(__GNUC__) && !(defined(__ICC) || defined(__INTEL_COMPILER))
  2113. #if (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__) < 40800
  2114. #error "unsupported GCC version - see https://github.com/nlohmann/json#supported-compilers"
  2115. #endif
  2116. #endif
  2117. #endif
  2118. // C++ language standard detection
  2119. // if the user manually specified the used c++ version this is skipped
  2120. #if !defined(JSON_HAS_CPP_20) && !defined(JSON_HAS_CPP_17) && !defined(JSON_HAS_CPP_14) && !defined(JSON_HAS_CPP_11)
  2121. #if (defined(__cplusplus) && __cplusplus >= 202002L) || (defined(_MSVC_LANG) && _MSVC_LANG >= 202002L)
  2122. #define JSON_HAS_CPP_20
  2123. #define JSON_HAS_CPP_17
  2124. #define JSON_HAS_CPP_14
  2125. #elif (defined(__cplusplus) && __cplusplus >= 201703L) || (defined(_HAS_CXX17) && _HAS_CXX17 == 1) // fix for issue #464
  2126. #define JSON_HAS_CPP_17
  2127. #define JSON_HAS_CPP_14
  2128. #elif (defined(__cplusplus) && __cplusplus >= 201402L) || (defined(_HAS_CXX14) && _HAS_CXX14 == 1)
  2129. #define JSON_HAS_CPP_14
  2130. #endif
  2131. // the cpp 11 flag is always specified because it is the minimal required version
  2132. #define JSON_HAS_CPP_11
  2133. #endif
  2134. // disable documentation warnings on clang
  2135. #if defined(__clang__)
  2136. #pragma clang diagnostic push
  2137. #pragma clang diagnostic ignored "-Wdocumentation"
  2138. #pragma clang diagnostic ignored "-Wdocumentation-unknown-command"
  2139. #endif
  2140. // allow to disable exceptions
  2141. #if (defined(__cpp_exceptions) || defined(__EXCEPTIONS) || defined(_CPPUNWIND)) && !defined(JSON_NOEXCEPTION)
  2142. #define JSON_THROW(exception) throw exception
  2143. #define JSON_TRY try
  2144. #define JSON_CATCH(exception) catch(exception)
  2145. #define JSON_INTERNAL_CATCH(exception) catch(exception)
  2146. #else
  2147. #include <cstdlib>
  2148. #define JSON_THROW(exception) std::abort()
  2149. #define JSON_TRY if(true)
  2150. #define JSON_CATCH(exception) if(false)
  2151. #define JSON_INTERNAL_CATCH(exception) if(false)
  2152. #endif
  2153. // override exception macros
  2154. #if defined(JSON_THROW_USER)
  2155. #undef JSON_THROW
  2156. #define JSON_THROW JSON_THROW_USER
  2157. #endif
  2158. #if defined(JSON_TRY_USER)
  2159. #undef JSON_TRY
  2160. #define JSON_TRY JSON_TRY_USER
  2161. #endif
  2162. #if defined(JSON_CATCH_USER)
  2163. #undef JSON_CATCH
  2164. #define JSON_CATCH JSON_CATCH_USER
  2165. #undef JSON_INTERNAL_CATCH
  2166. #define JSON_INTERNAL_CATCH JSON_CATCH_USER
  2167. #endif
  2168. #if defined(JSON_INTERNAL_CATCH_USER)
  2169. #undef JSON_INTERNAL_CATCH
  2170. #define JSON_INTERNAL_CATCH JSON_INTERNAL_CATCH_USER
  2171. #endif
  2172. // allow to override assert
  2173. #if !defined(JSON_ASSERT)
  2174. #include <cassert> // assert
  2175. #define JSON_ASSERT(x) assert(x)
  2176. #endif
  2177. // allow to access some private functions (needed by the test suite)
  2178. #if defined(JSON_TESTS_PRIVATE)
  2179. #define JSON_PRIVATE_UNLESS_TESTED public
  2180. #else
  2181. #define JSON_PRIVATE_UNLESS_TESTED private
  2182. #endif
  2183. /*!
  2184. @brief macro to briefly define a mapping between an enum and JSON
  2185. @def NLOHMANN_JSON_SERIALIZE_ENUM
  2186. @since version 3.4.0
  2187. */
  2188. #define NLOHMANN_JSON_SERIALIZE_ENUM(ENUM_TYPE, ...) \
  2189. template<typename BasicJsonType> \
  2190. inline void to_json(BasicJsonType& j, const ENUM_TYPE& e) \
  2191. { \
  2192. static_assert(std::is_enum<ENUM_TYPE>::value, #ENUM_TYPE " must be an enum!"); \
  2193. static const std::pair<ENUM_TYPE, BasicJsonType> m[] = __VA_ARGS__; \
  2194. auto it = std::find_if(std::begin(m), std::end(m), \
  2195. [e](const std::pair<ENUM_TYPE, BasicJsonType>& ej_pair) -> bool \
  2196. { \
  2197. return ej_pair.first == e; \
  2198. }); \
  2199. j = ((it != std::end(m)) ? it : std::begin(m))->second; \
  2200. } \
  2201. template<typename BasicJsonType> \
  2202. inline void from_json(const BasicJsonType& j, ENUM_TYPE& e) \
  2203. { \
  2204. static_assert(std::is_enum<ENUM_TYPE>::value, #ENUM_TYPE " must be an enum!"); \
  2205. static const std::pair<ENUM_TYPE, BasicJsonType> m[] = __VA_ARGS__; \
  2206. auto it = std::find_if(std::begin(m), std::end(m), \
  2207. [&j](const std::pair<ENUM_TYPE, BasicJsonType>& ej_pair) -> bool \
  2208. { \
  2209. return ej_pair.second == j; \
  2210. }); \
  2211. e = ((it != std::end(m)) ? it : std::begin(m))->first; \
  2212. }
  2213. // Ugly macros to avoid uglier copy-paste when specializing basic_json. They
  2214. // may be removed in the future once the class is split.
  2215. #define NLOHMANN_BASIC_JSON_TPL_DECLARATION \
  2216. template<template<typename, typename, typename...> class ObjectType, \
  2217. template<typename, typename...> class ArrayType, \
  2218. class StringType, class BooleanType, class NumberIntegerType, \
  2219. class NumberUnsignedType, class NumberFloatType, \
  2220. template<typename> class AllocatorType, \
  2221. template<typename, typename = void> class JSONSerializer, \
  2222. class BinaryType>
  2223. #define NLOHMANN_BASIC_JSON_TPL \
  2224. basic_json<ObjectType, ArrayType, StringType, BooleanType, \
  2225. NumberIntegerType, NumberUnsignedType, NumberFloatType, \
  2226. AllocatorType, JSONSerializer, BinaryType>
  2227. // Macros to simplify conversion from/to types
  2228. #define NLOHMANN_JSON_EXPAND( x ) x
  2229. #define NLOHMANN_JSON_GET_MACRO(_1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16, _17, _18, _19, _20, _21, _22, _23, _24, _25, _26, _27, _28, _29, _30, _31, _32, _33, _34, _35, _36, _37, _38, _39, _40, _41, _42, _43, _44, _45, _46, _47, _48, _49, _50, _51, _52, _53, _54, _55, _56, _57, _58, _59, _60, _61, _62, _63, _64, NAME,...) NAME
  2230. #define NLOHMANN_JSON_PASTE(...) NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_GET_MACRO(__VA_ARGS__, \
  2231. NLOHMANN_JSON_PASTE64, \
  2232. NLOHMANN_JSON_PASTE63, \
  2233. NLOHMANN_JSON_PASTE62, \
  2234. NLOHMANN_JSON_PASTE61, \
  2235. NLOHMANN_JSON_PASTE60, \
  2236. NLOHMANN_JSON_PASTE59, \
  2237. NLOHMANN_JSON_PASTE58, \
  2238. NLOHMANN_JSON_PASTE57, \
  2239. NLOHMANN_JSON_PASTE56, \
  2240. NLOHMANN_JSON_PASTE55, \
  2241. NLOHMANN_JSON_PASTE54, \
  2242. NLOHMANN_JSON_PASTE53, \
  2243. NLOHMANN_JSON_PASTE52, \
  2244. NLOHMANN_JSON_PASTE51, \
  2245. NLOHMANN_JSON_PASTE50, \
  2246. NLOHMANN_JSON_PASTE49, \
  2247. NLOHMANN_JSON_PASTE48, \
  2248. NLOHMANN_JSON_PASTE47, \
  2249. NLOHMANN_JSON_PASTE46, \
  2250. NLOHMANN_JSON_PASTE45, \
  2251. NLOHMANN_JSON_PASTE44, \
  2252. NLOHMANN_JSON_PASTE43, \
  2253. NLOHMANN_JSON_PASTE42, \
  2254. NLOHMANN_JSON_PASTE41, \
  2255. NLOHMANN_JSON_PASTE40, \
  2256. NLOHMANN_JSON_PASTE39, \
  2257. NLOHMANN_JSON_PASTE38, \
  2258. NLOHMANN_JSON_PASTE37, \
  2259. NLOHMANN_JSON_PASTE36, \
  2260. NLOHMANN_JSON_PASTE35, \
  2261. NLOHMANN_JSON_PASTE34, \
  2262. NLOHMANN_JSON_PASTE33, \
  2263. NLOHMANN_JSON_PASTE32, \
  2264. NLOHMANN_JSON_PASTE31, \
  2265. NLOHMANN_JSON_PASTE30, \
  2266. NLOHMANN_JSON_PASTE29, \
  2267. NLOHMANN_JSON_PASTE28, \
  2268. NLOHMANN_JSON_PASTE27, \
  2269. NLOHMANN_JSON_PASTE26, \
  2270. NLOHMANN_JSON_PASTE25, \
  2271. NLOHMANN_JSON_PASTE24, \
  2272. NLOHMANN_JSON_PASTE23, \
  2273. NLOHMANN_JSON_PASTE22, \
  2274. NLOHMANN_JSON_PASTE21, \
  2275. NLOHMANN_JSON_PASTE20, \
  2276. NLOHMANN_JSON_PASTE19, \
  2277. NLOHMANN_JSON_PASTE18, \
  2278. NLOHMANN_JSON_PASTE17, \
  2279. NLOHMANN_JSON_PASTE16, \
  2280. NLOHMANN_JSON_PASTE15, \
  2281. NLOHMANN_JSON_PASTE14, \
  2282. NLOHMANN_JSON_PASTE13, \
  2283. NLOHMANN_JSON_PASTE12, \
  2284. NLOHMANN_JSON_PASTE11, \
  2285. NLOHMANN_JSON_PASTE10, \
  2286. NLOHMANN_JSON_PASTE9, \
  2287. NLOHMANN_JSON_PASTE8, \
  2288. NLOHMANN_JSON_PASTE7, \
  2289. NLOHMANN_JSON_PASTE6, \
  2290. NLOHMANN_JSON_PASTE5, \
  2291. NLOHMANN_JSON_PASTE4, \
  2292. NLOHMANN_JSON_PASTE3, \
  2293. NLOHMANN_JSON_PASTE2, \
  2294. NLOHMANN_JSON_PASTE1)(__VA_ARGS__))
  2295. #define NLOHMANN_JSON_PASTE2(func, v1) func(v1)
  2296. #define NLOHMANN_JSON_PASTE3(func, v1, v2) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE2(func, v2)
  2297. #define NLOHMANN_JSON_PASTE4(func, v1, v2, v3) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE3(func, v2, v3)
  2298. #define NLOHMANN_JSON_PASTE5(func, v1, v2, v3, v4) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE4(func, v2, v3, v4)
  2299. #define NLOHMANN_JSON_PASTE6(func, v1, v2, v3, v4, v5) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE5(func, v2, v3, v4, v5)
  2300. #define NLOHMANN_JSON_PASTE7(func, v1, v2, v3, v4, v5, v6) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE6(func, v2, v3, v4, v5, v6)
  2301. #define NLOHMANN_JSON_PASTE8(func, v1, v2, v3, v4, v5, v6, v7) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE7(func, v2, v3, v4, v5, v6, v7)
  2302. #define NLOHMANN_JSON_PASTE9(func, v1, v2, v3, v4, v5, v6, v7, v8) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE8(func, v2, v3, v4, v5, v6, v7, v8)
  2303. #define NLOHMANN_JSON_PASTE10(func, v1, v2, v3, v4, v5, v6, v7, v8, v9) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE9(func, v2, v3, v4, v5, v6, v7, v8, v9)
  2304. #define NLOHMANN_JSON_PASTE11(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE10(func, v2, v3, v4, v5, v6, v7, v8, v9, v10)
  2305. #define NLOHMANN_JSON_PASTE12(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE11(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11)
  2306. #define NLOHMANN_JSON_PASTE13(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE12(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12)
  2307. #define NLOHMANN_JSON_PASTE14(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE13(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13)
  2308. #define NLOHMANN_JSON_PASTE15(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE14(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14)
  2309. #define NLOHMANN_JSON_PASTE16(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE15(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15)
  2310. #define NLOHMANN_JSON_PASTE17(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE16(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16)
  2311. #define NLOHMANN_JSON_PASTE18(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE17(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17)
  2312. #define NLOHMANN_JSON_PASTE19(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE18(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18)
  2313. #define NLOHMANN_JSON_PASTE20(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE19(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19)
  2314. #define NLOHMANN_JSON_PASTE21(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE20(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20)
  2315. #define NLOHMANN_JSON_PASTE22(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE21(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21)
  2316. #define NLOHMANN_JSON_PASTE23(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE22(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22)
  2317. #define NLOHMANN_JSON_PASTE24(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE23(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23)
  2318. #define NLOHMANN_JSON_PASTE25(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE24(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24)
  2319. #define NLOHMANN_JSON_PASTE26(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE25(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25)
  2320. #define NLOHMANN_JSON_PASTE27(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE26(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26)
  2321. #define NLOHMANN_JSON_PASTE28(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE27(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27)
  2322. #define NLOHMANN_JSON_PASTE29(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE28(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28)
  2323. #define NLOHMANN_JSON_PASTE30(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE29(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29)
  2324. #define NLOHMANN_JSON_PASTE31(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE30(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30)
  2325. #define NLOHMANN_JSON_PASTE32(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE31(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31)
  2326. #define NLOHMANN_JSON_PASTE33(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE32(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32)
  2327. #define NLOHMANN_JSON_PASTE34(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE33(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33)
  2328. #define NLOHMANN_JSON_PASTE35(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE34(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34)
  2329. #define NLOHMANN_JSON_PASTE36(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE35(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35)
  2330. #define NLOHMANN_JSON_PASTE37(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE36(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36)
  2331. #define NLOHMANN_JSON_PASTE38(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE37(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37)
  2332. #define NLOHMANN_JSON_PASTE39(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE38(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38)
  2333. #define NLOHMANN_JSON_PASTE40(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE39(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39)
  2334. #define NLOHMANN_JSON_PASTE41(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE40(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40)
  2335. #define NLOHMANN_JSON_PASTE42(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE41(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41)
  2336. #define NLOHMANN_JSON_PASTE43(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE42(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42)
  2337. #define NLOHMANN_JSON_PASTE44(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE43(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43)
  2338. #define NLOHMANN_JSON_PASTE45(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE44(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44)
  2339. #define NLOHMANN_JSON_PASTE46(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE45(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45)
  2340. #define NLOHMANN_JSON_PASTE47(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE46(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46)
  2341. #define NLOHMANN_JSON_PASTE48(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE47(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47)
  2342. #define NLOHMANN_JSON_PASTE49(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE48(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48)
  2343. #define NLOHMANN_JSON_PASTE50(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE49(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49)
  2344. #define NLOHMANN_JSON_PASTE51(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE50(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50)
  2345. #define NLOHMANN_JSON_PASTE52(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE51(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51)
  2346. #define NLOHMANN_JSON_PASTE53(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE52(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52)
  2347. #define NLOHMANN_JSON_PASTE54(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE53(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53)
  2348. #define NLOHMANN_JSON_PASTE55(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE54(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54)
  2349. #define NLOHMANN_JSON_PASTE56(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE55(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55)
  2350. #define NLOHMANN_JSON_PASTE57(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE56(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56)
  2351. #define NLOHMANN_JSON_PASTE58(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE57(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57)
  2352. #define NLOHMANN_JSON_PASTE59(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE58(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58)
  2353. #define NLOHMANN_JSON_PASTE60(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58, v59) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE59(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58, v59)
  2354. #define NLOHMANN_JSON_PASTE61(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58, v59, v60) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE60(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58, v59, v60)
  2355. #define NLOHMANN_JSON_PASTE62(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58, v59, v60, v61) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE61(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58, v59, v60, v61)
  2356. #define NLOHMANN_JSON_PASTE63(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58, v59, v60, v61, v62) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE62(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58, v59, v60, v61, v62)
  2357. #define NLOHMANN_JSON_PASTE64(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58, v59, v60, v61, v62, v63) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE63(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58, v59, v60, v61, v62, v63)
  2358. #define NLOHMANN_JSON_TO(v1) nlohmann_json_j[#v1] = nlohmann_json_t.v1;
  2359. #define NLOHMANN_JSON_FROM(v1) nlohmann_json_j.at(#v1).get_to(nlohmann_json_t.v1);
  2360. /*!
  2361. @brief macro
  2362. @def NLOHMANN_DEFINE_TYPE_INTRUSIVE
  2363. @since version 3.9.0
  2364. */
  2365. #define NLOHMANN_DEFINE_TYPE_INTRUSIVE(Type, ...) \
  2366. friend void to_json(nlohmann::json& nlohmann_json_j, const Type& nlohmann_json_t) { NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_PASTE(NLOHMANN_JSON_TO, __VA_ARGS__)) } \
  2367. friend void from_json(const nlohmann::json& nlohmann_json_j, Type& nlohmann_json_t) { NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_PASTE(NLOHMANN_JSON_FROM, __VA_ARGS__)) }
  2368. /*!
  2369. @brief macro
  2370. @def NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE
  2371. @since version 3.9.0
  2372. */
  2373. #define NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE(Type, ...) \
  2374. inline void to_json(nlohmann::json& nlohmann_json_j, const Type& nlohmann_json_t) { NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_PASTE(NLOHMANN_JSON_TO, __VA_ARGS__)) } \
  2375. inline void from_json(const nlohmann::json& nlohmann_json_j, Type& nlohmann_json_t) { NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_PASTE(NLOHMANN_JSON_FROM, __VA_ARGS__)) }
  2376. // inspired from https://stackoverflow.com/a/26745591
  2377. // allows to call any std function as if (e.g. with begin):
  2378. // using std::begin; begin(x);
  2379. //
  2380. // it allows using the detected idiom to retrieve the return type
  2381. // of such an expression
  2382. #define NLOHMANN_CAN_CALL_STD_FUNC_IMPL(std_name) \
  2383. namespace detail { \
  2384. using std::std_name; \
  2385. \
  2386. template<typename... T> \
  2387. using result_of_##std_name = decltype(std_name(std::declval<T>()...)); \
  2388. } \
  2389. \
  2390. namespace detail2 { \
  2391. struct std_name##_tag \
  2392. { \
  2393. }; \
  2394. \
  2395. template<typename... T> \
  2396. std_name##_tag std_name(T&&...); \
  2397. \
  2398. template<typename... T> \
  2399. using result_of_##std_name = decltype(std_name(std::declval<T>()...)); \
  2400. \
  2401. template<typename... T> \
  2402. struct would_call_std_##std_name \
  2403. { \
  2404. static constexpr auto const value = ::nlohmann::detail:: \
  2405. is_detected_exact<std_name##_tag, result_of_##std_name, T...>::value; \
  2406. }; \
  2407. } /* namespace detail2 */ \
  2408. \
  2409. template<typename... T> \
  2410. struct would_call_std_##std_name : detail2::would_call_std_##std_name<T...> \
  2411. { \
  2412. }
  2413. #ifndef JSON_USE_IMPLICIT_CONVERSIONS
  2414. #define JSON_USE_IMPLICIT_CONVERSIONS 1
  2415. #endif
  2416. #if JSON_USE_IMPLICIT_CONVERSIONS
  2417. #define JSON_EXPLICIT
  2418. #else
  2419. #define JSON_EXPLICIT explicit
  2420. #endif
  2421. #ifndef JSON_DIAGNOSTICS
  2422. #define JSON_DIAGNOSTICS 0
  2423. #endif
  2424. namespace nlohmann
  2425. {
  2426. namespace detail
  2427. {
  2428. /*!
  2429. @brief replace all occurrences of a substring by another string
  2430. @param[in,out] s the string to manipulate; changed so that all
  2431. occurrences of @a f are replaced with @a t
  2432. @param[in] f the substring to replace with @a t
  2433. @param[in] t the string to replace @a f
  2434. @pre The search string @a f must not be empty. **This precondition is
  2435. enforced with an assertion.**
  2436. @since version 2.0.0
  2437. */
  2438. inline void replace_substring(std::string& s, const std::string& f,
  2439. const std::string& t)
  2440. {
  2441. JSON_ASSERT(!f.empty());
  2442. for (auto pos = s.find(f); // find first occurrence of f
  2443. pos != std::string::npos; // make sure f was found
  2444. s.replace(pos, f.size(), t), // replace with t, and
  2445. pos = s.find(f, pos + t.size())) // find next occurrence of f
  2446. {}
  2447. }
  2448. /*!
  2449. * @brief string escaping as described in RFC 6901 (Sect. 4)
  2450. * @param[in] s string to escape
  2451. * @return escaped string
  2452. *
  2453. * Note the order of escaping "~" to "~0" and "/" to "~1" is important.
  2454. */
  2455. inline std::string escape(std::string s)
  2456. {
  2457. replace_substring(s, "~", "~0");
  2458. replace_substring(s, "/", "~1");
  2459. return s;
  2460. }
  2461. /*!
  2462. * @brief string unescaping as described in RFC 6901 (Sect. 4)
  2463. * @param[in] s string to unescape
  2464. * @return unescaped string
  2465. *
  2466. * Note the order of escaping "~1" to "/" and "~0" to "~" is important.
  2467. */
  2468. static void unescape(std::string& s)
  2469. {
  2470. replace_substring(s, "~1", "/");
  2471. replace_substring(s, "~0", "~");
  2472. }
  2473. } // namespace detail
  2474. } // namespace nlohmann
  2475. // #include <nlohmann/detail/input/position_t.hpp>
  2476. #include <cstddef> // size_t
  2477. namespace nlohmann
  2478. {
  2479. namespace detail
  2480. {
  2481. /// struct to capture the start position of the current token
  2482. struct position_t
  2483. {
  2484. /// the total number of characters read
  2485. std::size_t chars_read_total = 0;
  2486. /// the number of characters read in the current line
  2487. std::size_t chars_read_current_line = 0;
  2488. /// the number of lines read
  2489. std::size_t lines_read = 0;
  2490. /// conversion to size_t to preserve SAX interface
  2491. constexpr operator size_t() const
  2492. {
  2493. return chars_read_total;
  2494. }
  2495. };
  2496. } // namespace detail
  2497. } // namespace nlohmann
  2498. // #include <nlohmann/detail/macro_scope.hpp>
  2499. namespace nlohmann
  2500. {
  2501. namespace detail
  2502. {
  2503. ////////////////
  2504. // exceptions //
  2505. ////////////////
  2506. /*!
  2507. @brief general exception of the @ref basic_json class
  2508. This class is an extension of `std::exception` objects with a member @a id for
  2509. exception ids. It is used as the base class for all exceptions thrown by the
  2510. @ref basic_json class. This class can hence be used as "wildcard" to catch
  2511. exceptions.
  2512. Subclasses:
  2513. - @ref parse_error for exceptions indicating a parse error
  2514. - @ref invalid_iterator for exceptions indicating errors with iterators
  2515. - @ref type_error for exceptions indicating executing a member function with
  2516. a wrong type
  2517. - @ref out_of_range for exceptions indicating access out of the defined range
  2518. - @ref other_error for exceptions indicating other library errors
  2519. @internal
  2520. @note To have nothrow-copy-constructible exceptions, we internally use
  2521. `std::runtime_error` which can cope with arbitrary-length error messages.
  2522. Intermediate strings are built with static functions and then passed to
  2523. the actual constructor.
  2524. @endinternal
  2525. @liveexample{The following code shows how arbitrary library exceptions can be
  2526. caught.,exception}
  2527. @since version 3.0.0
  2528. */
  2529. class exception : public std::exception
  2530. {
  2531. public:
  2532. /// returns the explanatory string
  2533. const char* what() const noexcept override
  2534. {
  2535. return m.what();
  2536. }
  2537. /// the id of the exception
  2538. const int id; // NOLINT(cppcoreguidelines-non-private-member-variables-in-classes)
  2539. protected:
  2540. JSON_HEDLEY_NON_NULL(3)
  2541. exception(int id_, const char* what_arg) : id(id_), m(what_arg) {}
  2542. static std::string name(const std::string& ename, int id_)
  2543. {
  2544. return "[json.exception." + ename + "." + std::to_string(id_) + "] ";
  2545. }
  2546. template<typename BasicJsonType>
  2547. static std::string diagnostics(const BasicJsonType& leaf_element)
  2548. {
  2549. #if JSON_DIAGNOSTICS
  2550. std::vector<std::string> tokens;
  2551. for (const auto* current = &leaf_element; current->m_parent != nullptr; current = current->m_parent)
  2552. {
  2553. switch (current->m_parent->type())
  2554. {
  2555. case value_t::array:
  2556. {
  2557. for (std::size_t i = 0; i < current->m_parent->m_value.array->size(); ++i)
  2558. {
  2559. if (&current->m_parent->m_value.array->operator[](i) == current)
  2560. {
  2561. tokens.emplace_back(std::to_string(i));
  2562. break;
  2563. }
  2564. }
  2565. break;
  2566. }
  2567. case value_t::object:
  2568. {
  2569. for (const auto& element : *current->m_parent->m_value.object)
  2570. {
  2571. if (&element.second == current)
  2572. {
  2573. tokens.emplace_back(element.first.c_str());
  2574. break;
  2575. }
  2576. }
  2577. break;
  2578. }
  2579. case value_t::null: // LCOV_EXCL_LINE
  2580. case value_t::string: // LCOV_EXCL_LINE
  2581. case value_t::boolean: // LCOV_EXCL_LINE
  2582. case value_t::number_integer: // LCOV_EXCL_LINE
  2583. case value_t::number_unsigned: // LCOV_EXCL_LINE
  2584. case value_t::number_float: // LCOV_EXCL_LINE
  2585. case value_t::binary: // LCOV_EXCL_LINE
  2586. case value_t::discarded: // LCOV_EXCL_LINE
  2587. default: // LCOV_EXCL_LINE
  2588. break; // LCOV_EXCL_LINE
  2589. }
  2590. }
  2591. if (tokens.empty())
  2592. {
  2593. return "";
  2594. }
  2595. return "(" + std::accumulate(tokens.rbegin(), tokens.rend(), std::string{},
  2596. [](const std::string & a, const std::string & b)
  2597. {
  2598. return a + "/" + detail::escape(b);
  2599. }) + ") ";
  2600. #else
  2601. static_cast<void>(leaf_element);
  2602. return "";
  2603. #endif
  2604. }
  2605. private:
  2606. /// an exception object as storage for error messages
  2607. std::runtime_error m;
  2608. };
  2609. /*!
  2610. @brief exception indicating a parse error
  2611. This exception is thrown by the library when a parse error occurs. Parse errors
  2612. can occur during the deserialization of JSON text, CBOR, MessagePack, as well
  2613. as when using JSON Patch.
  2614. Member @a byte holds the byte index of the last read character in the input
  2615. file.
  2616. Exceptions have ids 1xx.
  2617. name / id | example message | description
  2618. ------------------------------ | --------------- | -------------------------
  2619. 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.
  2620. 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.
  2621. 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.
  2622. 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.
  2623. 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.
  2624. 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`.
  2625. 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.
  2626. 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.
  2627. json.exception.parse_error.109 | parse error: array index 'one' is not a number | A JSON Pointer array index must be a number.
  2628. 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.
  2629. 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.
  2630. 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.
  2631. json.exception.parse_error.114 | parse error: Unsupported BSON record type 0x0F | The parsing of the corresponding BSON record type is not implemented (yet).
  2632. json.exception.parse_error.115 | parse error at byte 5: syntax error while parsing UBJSON high-precision number: invalid number text: 1A | A UBJSON high-precision number could not be parsed.
  2633. @note For an input with n bytes, 1 is the index of the first character and n+1
  2634. is the index of the terminating null byte or the end of file. This also
  2635. holds true when reading a byte vector (CBOR or MessagePack).
  2636. @liveexample{The following code shows how a `parse_error` exception can be
  2637. caught.,parse_error}
  2638. @sa - @ref exception for the base class of the library exceptions
  2639. @sa - @ref invalid_iterator for exceptions indicating errors with iterators
  2640. @sa - @ref type_error for exceptions indicating executing a member function with
  2641. a wrong type
  2642. @sa - @ref out_of_range for exceptions indicating access out of the defined range
  2643. @sa - @ref other_error for exceptions indicating other library errors
  2644. @since version 3.0.0
  2645. */
  2646. class parse_error : public exception
  2647. {
  2648. public:
  2649. /*!
  2650. @brief create a parse error exception
  2651. @param[in] id_ the id of the exception
  2652. @param[in] pos the position where the error occurred (or with
  2653. chars_read_total=0 if the position cannot be
  2654. determined)
  2655. @param[in] what_arg the explanatory string
  2656. @return parse_error object
  2657. */
  2658. template<typename BasicJsonType>
  2659. static parse_error create(int id_, const position_t& pos, const std::string& what_arg, const BasicJsonType& context)
  2660. {
  2661. std::string w = exception::name("parse_error", id_) + "parse error" +
  2662. position_string(pos) + ": " + exception::diagnostics(context) + what_arg;
  2663. return parse_error(id_, pos.chars_read_total, w.c_str());
  2664. }
  2665. template<typename BasicJsonType>
  2666. static parse_error create(int id_, std::size_t byte_, const std::string& what_arg, const BasicJsonType& context)
  2667. {
  2668. std::string w = exception::name("parse_error", id_) + "parse error" +
  2669. (byte_ != 0 ? (" at byte " + std::to_string(byte_)) : "") +
  2670. ": " + exception::diagnostics(context) + what_arg;
  2671. return parse_error(id_, byte_, w.c_str());
  2672. }
  2673. /*!
  2674. @brief byte index of the parse error
  2675. The byte index of the last read character in the input file.
  2676. @note For an input with n bytes, 1 is the index of the first character and
  2677. n+1 is the index of the terminating null byte or the end of file.
  2678. This also holds true when reading a byte vector (CBOR or MessagePack).
  2679. */
  2680. const std::size_t byte;
  2681. private:
  2682. parse_error(int id_, std::size_t byte_, const char* what_arg)
  2683. : exception(id_, what_arg), byte(byte_) {}
  2684. static std::string position_string(const position_t& pos)
  2685. {
  2686. return " at line " + std::to_string(pos.lines_read + 1) +
  2687. ", column " + std::to_string(pos.chars_read_current_line);
  2688. }
  2689. };
  2690. /*!
  2691. @brief exception indicating errors with iterators
  2692. This exception is thrown if iterators passed to a library function do not match
  2693. the expected semantics.
  2694. Exceptions have ids 2xx.
  2695. name / id | example message | description
  2696. ----------------------------------- | --------------- | -------------------------
  2697. 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.
  2698. 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.
  2699. 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.
  2700. 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.
  2701. 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.
  2702. 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.
  2703. 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.
  2704. 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.
  2705. 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.
  2706. 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.
  2707. 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.
  2708. json.exception.invalid_iterator.212 | cannot compare iterators of different containers | When two iterators are compared, they must belong to the same container.
  2709. json.exception.invalid_iterator.213 | cannot compare order of object iterators | The order of object iterators cannot be compared, because JSON objects are unordered.
  2710. 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().
  2711. @liveexample{The following code shows how an `invalid_iterator` exception can be
  2712. caught.,invalid_iterator}
  2713. @sa - @ref exception for the base class of the library exceptions
  2714. @sa - @ref parse_error for exceptions indicating a parse error
  2715. @sa - @ref type_error for exceptions indicating executing a member function with
  2716. a wrong type
  2717. @sa - @ref out_of_range for exceptions indicating access out of the defined range
  2718. @sa - @ref other_error for exceptions indicating other library errors
  2719. @since version 3.0.0
  2720. */
  2721. class invalid_iterator : public exception
  2722. {
  2723. public:
  2724. template<typename BasicJsonType>
  2725. static invalid_iterator create(int id_, const std::string& what_arg, const BasicJsonType& context)
  2726. {
  2727. std::string w = exception::name("invalid_iterator", id_) + exception::diagnostics(context) + what_arg;
  2728. return invalid_iterator(id_, w.c_str());
  2729. }
  2730. private:
  2731. JSON_HEDLEY_NON_NULL(3)
  2732. invalid_iterator(int id_, const char* what_arg)
  2733. : exception(id_, what_arg) {}
  2734. };
  2735. /*!
  2736. @brief exception indicating executing a member function with a wrong type
  2737. This exception is thrown in case of a type error; that is, a library function is
  2738. executed on a JSON value whose type does not match the expected semantics.
  2739. Exceptions have ids 3xx.
  2740. name / id | example message | description
  2741. ----------------------------- | --------------- | -------------------------
  2742. 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.
  2743. 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.
  2744. 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 &.
  2745. json.exception.type_error.304 | cannot use at() with string | The @ref at() member functions can only be executed for certain JSON types.
  2746. json.exception.type_error.305 | cannot use operator[] with string | The @ref operator[] member functions can only be executed for certain JSON types.
  2747. json.exception.type_error.306 | cannot use value() with string | The @ref value() member functions can only be executed for certain JSON types.
  2748. json.exception.type_error.307 | cannot use erase() with string | The @ref erase() member functions can only be executed for certain JSON types.
  2749. 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.
  2750. json.exception.type_error.309 | cannot use insert() with | The @ref insert() member functions can only be executed for certain JSON types.
  2751. json.exception.type_error.310 | cannot use swap() with number | The @ref swap() member functions can only be executed for certain JSON types.
  2752. 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.
  2753. json.exception.type_error.312 | cannot use update() with string | The @ref update() member functions can only be executed for certain JSON types.
  2754. 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.
  2755. json.exception.type_error.314 | only objects can be unflattened | The @ref unflatten function only works for an object whose keys are JSON Pointers.
  2756. 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.
  2757. 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. |
  2758. 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) |
  2759. @liveexample{The following code shows how a `type_error` exception can be
  2760. caught.,type_error}
  2761. @sa - @ref exception for the base class of the library exceptions
  2762. @sa - @ref parse_error for exceptions indicating a parse error
  2763. @sa - @ref invalid_iterator for exceptions indicating errors with iterators
  2764. @sa - @ref out_of_range for exceptions indicating access out of the defined range
  2765. @sa - @ref other_error for exceptions indicating other library errors
  2766. @since version 3.0.0
  2767. */
  2768. class type_error : public exception
  2769. {
  2770. public:
  2771. template<typename BasicJsonType>
  2772. static type_error create(int id_, const std::string& what_arg, const BasicJsonType& context)
  2773. {
  2774. std::string w = exception::name("type_error", id_) + exception::diagnostics(context) + what_arg;
  2775. return type_error(id_, w.c_str());
  2776. }
  2777. private:
  2778. JSON_HEDLEY_NON_NULL(3)
  2779. type_error(int id_, const char* what_arg) : exception(id_, what_arg) {}
  2780. };
  2781. /*!
  2782. @brief exception indicating access out of the defined range
  2783. This exception is thrown in case a library function is called on an input
  2784. parameter that exceeds the expected range, for instance in case of array
  2785. indices or nonexisting object keys.
  2786. Exceptions have ids 4xx.
  2787. name / id | example message | description
  2788. ------------------------------- | --------------- | -------------------------
  2789. 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.
  2790. 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.
  2791. json.exception.out_of_range.403 | key 'foo' not found | The provided key was not found in the JSON object.
  2792. json.exception.out_of_range.404 | unresolved reference token 'foo' | A reference token in a JSON Pointer could not be resolved.
  2793. 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.
  2794. 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.
  2795. json.exception.out_of_range.407 | number overflow serializing '9223372036854775808' | UBJSON and BSON only support integer numbers up to 9223372036854775807. (until version 3.8.0) |
  2796. json.exception.out_of_range.408 | excessive array size: 8658170730974374167 | The size (following `#`) of an UBJSON array or object exceeds the maximal capacity. |
  2797. 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 |
  2798. @liveexample{The following code shows how an `out_of_range` exception can be
  2799. caught.,out_of_range}
  2800. @sa - @ref exception for the base class of the library exceptions
  2801. @sa - @ref parse_error for exceptions indicating a parse error
  2802. @sa - @ref invalid_iterator for exceptions indicating errors with iterators
  2803. @sa - @ref type_error for exceptions indicating executing a member function with
  2804. a wrong type
  2805. @sa - @ref other_error for exceptions indicating other library errors
  2806. @since version 3.0.0
  2807. */
  2808. class out_of_range : public exception
  2809. {
  2810. public:
  2811. template<typename BasicJsonType>
  2812. static out_of_range create(int id_, const std::string& what_arg, const BasicJsonType& context)
  2813. {
  2814. std::string w = exception::name("out_of_range", id_) + exception::diagnostics(context) + what_arg;
  2815. return out_of_range(id_, w.c_str());
  2816. }
  2817. private:
  2818. JSON_HEDLEY_NON_NULL(3)
  2819. out_of_range(int id_, const char* what_arg) : exception(id_, what_arg) {}
  2820. };
  2821. /*!
  2822. @brief exception indicating other library errors
  2823. This exception is thrown in case of errors that cannot be classified with the
  2824. other exception types.
  2825. Exceptions have ids 5xx.
  2826. name / id | example message | description
  2827. ------------------------------ | --------------- | -------------------------
  2828. json.exception.other_error.501 | unsuccessful: {"op":"test","path":"/baz", "value":"bar"} | A JSON Patch operation 'test' failed. The unsuccessful operation is also printed.
  2829. @sa - @ref exception for the base class of the library exceptions
  2830. @sa - @ref parse_error for exceptions indicating a parse error
  2831. @sa - @ref invalid_iterator for exceptions indicating errors with iterators
  2832. @sa - @ref type_error for exceptions indicating executing a member function with
  2833. a wrong type
  2834. @sa - @ref out_of_range for exceptions indicating access out of the defined range
  2835. @liveexample{The following code shows how an `other_error` exception can be
  2836. caught.,other_error}
  2837. @since version 3.0.0
  2838. */
  2839. class other_error : public exception
  2840. {
  2841. public:
  2842. template<typename BasicJsonType>
  2843. static other_error create(int id_, const std::string& what_arg, const BasicJsonType& context)
  2844. {
  2845. std::string w = exception::name("other_error", id_) + exception::diagnostics(context) + what_arg;
  2846. return other_error(id_, w.c_str());
  2847. }
  2848. private:
  2849. JSON_HEDLEY_NON_NULL(3)
  2850. other_error(int id_, const char* what_arg) : exception(id_, what_arg) {}
  2851. };
  2852. } // namespace detail
  2853. } // namespace nlohmann
  2854. // #include <nlohmann/detail/macro_scope.hpp>
  2855. // #include <nlohmann/detail/meta/cpp_future.hpp>
  2856. #include <cstddef> // size_t
  2857. #include <type_traits> // conditional, enable_if, false_type, integral_constant, is_constructible, is_integral, is_same, remove_cv, remove_reference, true_type
  2858. #include <utility> // index_sequence, make_index_sequence, index_sequence_for
  2859. // #include <nlohmann/detail/macro_scope.hpp>
  2860. namespace nlohmann
  2861. {
  2862. namespace detail
  2863. {
  2864. template<typename T>
  2865. using uncvref_t = typename std::remove_cv<typename std::remove_reference<T>::type>::type;
  2866. #ifdef JSON_HAS_CPP_14
  2867. // the following utilities are natively available in C++14
  2868. using std::enable_if_t;
  2869. using std::index_sequence;
  2870. using std::make_index_sequence;
  2871. using std::index_sequence_for;
  2872. #else
  2873. // alias templates to reduce boilerplate
  2874. template<bool B, typename T = void>
  2875. using enable_if_t = typename std::enable_if<B, T>::type;
  2876. // The following code is taken from https://github.com/abseil/abseil-cpp/blob/10cb35e459f5ecca5b2ff107635da0bfa41011b4/absl/utility/utility.h
  2877. // which is part of Google Abseil (https://github.com/abseil/abseil-cpp), licensed under the Apache License 2.0.
  2878. //// START OF CODE FROM GOOGLE ABSEIL
  2879. // integer_sequence
  2880. //
  2881. // Class template representing a compile-time integer sequence. An instantiation
  2882. // of `integer_sequence<T, Ints...>` has a sequence of integers encoded in its
  2883. // type through its template arguments (which is a common need when
  2884. // working with C++11 variadic templates). `absl::integer_sequence` is designed
  2885. // to be a drop-in replacement for C++14's `std::integer_sequence`.
  2886. //
  2887. // Example:
  2888. //
  2889. // template< class T, T... Ints >
  2890. // void user_function(integer_sequence<T, Ints...>);
  2891. //
  2892. // int main()
  2893. // {
  2894. // // user_function's `T` will be deduced to `int` and `Ints...`
  2895. // // will be deduced to `0, 1, 2, 3, 4`.
  2896. // user_function(make_integer_sequence<int, 5>());
  2897. // }
  2898. template <typename T, T... Ints>
  2899. struct integer_sequence
  2900. {
  2901. using value_type = T;
  2902. static constexpr std::size_t size() noexcept
  2903. {
  2904. return sizeof...(Ints);
  2905. }
  2906. };
  2907. // index_sequence
  2908. //
  2909. // A helper template for an `integer_sequence` of `size_t`,
  2910. // `absl::index_sequence` is designed to be a drop-in replacement for C++14's
  2911. // `std::index_sequence`.
  2912. template <size_t... Ints>
  2913. using index_sequence = integer_sequence<size_t, Ints...>;
  2914. namespace utility_internal
  2915. {
  2916. template <typename Seq, size_t SeqSize, size_t Rem>
  2917. struct Extend;
  2918. // Note that SeqSize == sizeof...(Ints). It's passed explicitly for efficiency.
  2919. template <typename T, T... Ints, size_t SeqSize>
  2920. struct Extend<integer_sequence<T, Ints...>, SeqSize, 0>
  2921. {
  2922. using type = integer_sequence < T, Ints..., (Ints + SeqSize)... >;
  2923. };
  2924. template <typename T, T... Ints, size_t SeqSize>
  2925. struct Extend<integer_sequence<T, Ints...>, SeqSize, 1>
  2926. {
  2927. using type = integer_sequence < T, Ints..., (Ints + SeqSize)..., 2 * SeqSize >;
  2928. };
  2929. // Recursion helper for 'make_integer_sequence<T, N>'.
  2930. // 'Gen<T, N>::type' is an alias for 'integer_sequence<T, 0, 1, ... N-1>'.
  2931. template <typename T, size_t N>
  2932. struct Gen
  2933. {
  2934. using type =
  2935. typename Extend < typename Gen < T, N / 2 >::type, N / 2, N % 2 >::type;
  2936. };
  2937. template <typename T>
  2938. struct Gen<T, 0>
  2939. {
  2940. using type = integer_sequence<T>;
  2941. };
  2942. } // namespace utility_internal
  2943. // Compile-time sequences of integers
  2944. // make_integer_sequence
  2945. //
  2946. // This template alias is equivalent to
  2947. // `integer_sequence<int, 0, 1, ..., N-1>`, and is designed to be a drop-in
  2948. // replacement for C++14's `std::make_integer_sequence`.
  2949. template <typename T, T N>
  2950. using make_integer_sequence = typename utility_internal::Gen<T, N>::type;
  2951. // make_index_sequence
  2952. //
  2953. // This template alias is equivalent to `index_sequence<0, 1, ..., N-1>`,
  2954. // and is designed to be a drop-in replacement for C++14's
  2955. // `std::make_index_sequence`.
  2956. template <size_t N>
  2957. using make_index_sequence = make_integer_sequence<size_t, N>;
  2958. // index_sequence_for
  2959. //
  2960. // Converts a typename pack into an index sequence of the same length, and
  2961. // is designed to be a drop-in replacement for C++14's
  2962. // `std::index_sequence_for()`
  2963. template <typename... Ts>
  2964. using index_sequence_for = make_index_sequence<sizeof...(Ts)>;
  2965. //// END OF CODE FROM GOOGLE ABSEIL
  2966. #endif
  2967. // dispatch utility (taken from ranges-v3)
  2968. template<unsigned N> struct priority_tag : priority_tag < N - 1 > {};
  2969. template<> struct priority_tag<0> {};
  2970. // taken from ranges-v3
  2971. template<typename T>
  2972. struct static_const
  2973. {
  2974. static constexpr T value{};
  2975. };
  2976. template<typename T>
  2977. constexpr T static_const<T>::value;
  2978. } // namespace detail
  2979. } // namespace nlohmann
  2980. // #include <nlohmann/detail/meta/identity_tag.hpp>
  2981. namespace nlohmann
  2982. {
  2983. namespace detail
  2984. {
  2985. // dispatching helper struct
  2986. template <class T> struct identity_tag {};
  2987. } // namespace detail
  2988. } // namespace nlohmann
  2989. // #include <nlohmann/detail/meta/type_traits.hpp>
  2990. #include <limits> // numeric_limits
  2991. #include <type_traits> // false_type, is_constructible, is_integral, is_same, true_type
  2992. #include <utility> // declval
  2993. #include <tuple> // tuple
  2994. // #include <nlohmann/detail/macro_scope.hpp>
  2995. // #include <nlohmann/detail/iterators/iterator_traits.hpp>
  2996. #include <iterator> // random_access_iterator_tag
  2997. // #include <nlohmann/detail/meta/void_t.hpp>
  2998. // #include <nlohmann/detail/meta/cpp_future.hpp>
  2999. namespace nlohmann
  3000. {
  3001. namespace detail
  3002. {
  3003. template<typename It, typename = void>
  3004. struct iterator_types {};
  3005. template<typename It>
  3006. struct iterator_types <
  3007. It,
  3008. void_t<typename It::difference_type, typename It::value_type, typename It::pointer,
  3009. typename It::reference, typename It::iterator_category >>
  3010. {
  3011. using difference_type = typename It::difference_type;
  3012. using value_type = typename It::value_type;
  3013. using pointer = typename It::pointer;
  3014. using reference = typename It::reference;
  3015. using iterator_category = typename It::iterator_category;
  3016. };
  3017. // This is required as some compilers implement std::iterator_traits in a way that
  3018. // doesn't work with SFINAE. See https://github.com/nlohmann/json/issues/1341.
  3019. template<typename T, typename = void>
  3020. struct iterator_traits
  3021. {
  3022. };
  3023. template<typename T>
  3024. struct iterator_traits < T, enable_if_t < !std::is_pointer<T>::value >>
  3025. : iterator_types<T>
  3026. {
  3027. };
  3028. template<typename T>
  3029. struct iterator_traits<T*, enable_if_t<std::is_object<T>::value>>
  3030. {
  3031. using iterator_category = std::random_access_iterator_tag;
  3032. using value_type = T;
  3033. using difference_type = ptrdiff_t;
  3034. using pointer = T*;
  3035. using reference = T&;
  3036. };
  3037. } // namespace detail
  3038. } // namespace nlohmann
  3039. // #include <nlohmann/detail/meta/call_std/begin.hpp>
  3040. // #include <nlohmann/detail/macro_scope.hpp>
  3041. namespace nlohmann
  3042. {
  3043. NLOHMANN_CAN_CALL_STD_FUNC_IMPL(begin);
  3044. } // namespace nlohmann
  3045. // #include <nlohmann/detail/meta/call_std/end.hpp>
  3046. // #include <nlohmann/detail/macro_scope.hpp>
  3047. namespace nlohmann
  3048. {
  3049. NLOHMANN_CAN_CALL_STD_FUNC_IMPL(end);
  3050. } // namespace nlohmann
  3051. // #include <nlohmann/detail/meta/cpp_future.hpp>
  3052. // #include <nlohmann/detail/meta/detected.hpp>
  3053. // #include <nlohmann/json_fwd.hpp>
  3054. #ifndef INCLUDE_NLOHMANN_JSON_FWD_HPP_
  3055. #define INCLUDE_NLOHMANN_JSON_FWD_HPP_
  3056. #include <cstdint> // int64_t, uint64_t
  3057. #include <map> // map
  3058. #include <memory> // allocator
  3059. #include <string> // string
  3060. #include <vector> // vector
  3061. /*!
  3062. @brief namespace for Niels Lohmann
  3063. @see https://github.com/nlohmann
  3064. @since version 1.0.0
  3065. */
  3066. namespace nlohmann
  3067. {
  3068. /*!
  3069. @brief default JSONSerializer template argument
  3070. This serializer ignores the template arguments and uses ADL
  3071. ([argument-dependent lookup](https://en.cppreference.com/w/cpp/language/adl))
  3072. for serialization.
  3073. */
  3074. template<typename T = void, typename SFINAE = void>
  3075. struct adl_serializer;
  3076. template<template<typename U, typename V, typename... Args> class ObjectType =
  3077. std::map,
  3078. template<typename U, typename... Args> class ArrayType = std::vector,
  3079. class StringType = std::string, class BooleanType = bool,
  3080. class NumberIntegerType = std::int64_t,
  3081. class NumberUnsignedType = std::uint64_t,
  3082. class NumberFloatType = double,
  3083. template<typename U> class AllocatorType = std::allocator,
  3084. template<typename T, typename SFINAE = void> class JSONSerializer =
  3085. adl_serializer,
  3086. class BinaryType = std::vector<std::uint8_t>>
  3087. class basic_json;
  3088. /*!
  3089. @brief JSON Pointer
  3090. A JSON pointer defines a string syntax for identifying a specific value
  3091. within a JSON document. It can be used with functions `at` and
  3092. `operator[]`. Furthermore, JSON pointers are the base for JSON patches.
  3093. @sa [RFC 6901](https://tools.ietf.org/html/rfc6901)
  3094. @since version 2.0.0
  3095. */
  3096. template<typename BasicJsonType>
  3097. class json_pointer;
  3098. /*!
  3099. @brief default JSON class
  3100. This type is the default specialization of the @ref basic_json class which
  3101. uses the standard template types.
  3102. @since version 1.0.0
  3103. */
  3104. using json = basic_json<>;
  3105. template<class Key, class T, class IgnoredLess, class Allocator>
  3106. struct ordered_map;
  3107. /*!
  3108. @brief ordered JSON class
  3109. This type preserves the insertion order of object keys.
  3110. @since version 3.9.0
  3111. */
  3112. using ordered_json = basic_json<nlohmann::ordered_map>;
  3113. } // namespace nlohmann
  3114. #endif // INCLUDE_NLOHMANN_JSON_FWD_HPP_
  3115. namespace nlohmann
  3116. {
  3117. /*!
  3118. @brief detail namespace with internal helper functions
  3119. This namespace collects functions that should not be exposed,
  3120. implementations of some @ref basic_json methods, and meta-programming helpers.
  3121. @since version 2.1.0
  3122. */
  3123. namespace detail
  3124. {
  3125. /////////////
  3126. // helpers //
  3127. /////////////
  3128. // Note to maintainers:
  3129. //
  3130. // Every trait in this file expects a non CV-qualified type.
  3131. // The only exceptions are in the 'aliases for detected' section
  3132. // (i.e. those of the form: decltype(T::member_function(std::declval<T>())))
  3133. //
  3134. // In this case, T has to be properly CV-qualified to constraint the function arguments
  3135. // (e.g. to_json(BasicJsonType&, const T&))
  3136. template<typename> struct is_basic_json : std::false_type {};
  3137. NLOHMANN_BASIC_JSON_TPL_DECLARATION
  3138. struct is_basic_json<NLOHMANN_BASIC_JSON_TPL> : std::true_type {};
  3139. //////////////////////
  3140. // json_ref helpers //
  3141. //////////////////////
  3142. template<typename>
  3143. class json_ref;
  3144. template<typename>
  3145. struct is_json_ref : std::false_type {};
  3146. template<typename T>
  3147. struct is_json_ref<json_ref<T>> : std::true_type {};
  3148. //////////////////////////
  3149. // aliases for detected //
  3150. //////////////////////////
  3151. template<typename T>
  3152. using mapped_type_t = typename T::mapped_type;
  3153. template<typename T>
  3154. using key_type_t = typename T::key_type;
  3155. template<typename T>
  3156. using value_type_t = typename T::value_type;
  3157. template<typename T>
  3158. using difference_type_t = typename T::difference_type;
  3159. template<typename T>
  3160. using pointer_t = typename T::pointer;
  3161. template<typename T>
  3162. using reference_t = typename T::reference;
  3163. template<typename T>
  3164. using iterator_category_t = typename T::iterator_category;
  3165. template<typename T, typename... Args>
  3166. using to_json_function = decltype(T::to_json(std::declval<Args>()...));
  3167. template<typename T, typename... Args>
  3168. using from_json_function = decltype(T::from_json(std::declval<Args>()...));
  3169. template<typename T, typename U>
  3170. using get_template_function = decltype(std::declval<T>().template get<U>());
  3171. // trait checking if JSONSerializer<T>::from_json(json const&, udt&) exists
  3172. template<typename BasicJsonType, typename T, typename = void>
  3173. struct has_from_json : std::false_type {};
  3174. // trait checking if j.get<T> is valid
  3175. // use this trait instead of std::is_constructible or std::is_convertible,
  3176. // both rely on, or make use of implicit conversions, and thus fail when T
  3177. // has several constructors/operator= (see https://github.com/nlohmann/json/issues/958)
  3178. template <typename BasicJsonType, typename T>
  3179. struct is_getable
  3180. {
  3181. static constexpr bool value = is_detected<get_template_function, const BasicJsonType&, T>::value;
  3182. };
  3183. template<typename BasicJsonType, typename T>
  3184. struct has_from_json < BasicJsonType, T, enable_if_t < !is_basic_json<T>::value >>
  3185. {
  3186. using serializer = typename BasicJsonType::template json_serializer<T, void>;
  3187. static constexpr bool value =
  3188. is_detected_exact<void, from_json_function, serializer,
  3189. const BasicJsonType&, T&>::value;
  3190. };
  3191. // This trait checks if JSONSerializer<T>::from_json(json const&) exists
  3192. // this overload is used for non-default-constructible user-defined-types
  3193. template<typename BasicJsonType, typename T, typename = void>
  3194. struct has_non_default_from_json : std::false_type {};
  3195. template<typename BasicJsonType, typename T>
  3196. struct has_non_default_from_json < BasicJsonType, T, enable_if_t < !is_basic_json<T>::value >>
  3197. {
  3198. using serializer = typename BasicJsonType::template json_serializer<T, void>;
  3199. static constexpr bool value =
  3200. is_detected_exact<T, from_json_function, serializer,
  3201. const BasicJsonType&>::value;
  3202. };
  3203. // This trait checks if BasicJsonType::json_serializer<T>::to_json exists
  3204. // Do not evaluate the trait when T is a basic_json type, to avoid template instantiation infinite recursion.
  3205. template<typename BasicJsonType, typename T, typename = void>
  3206. struct has_to_json : std::false_type {};
  3207. template<typename BasicJsonType, typename T>
  3208. struct has_to_json < BasicJsonType, T, enable_if_t < !is_basic_json<T>::value >>
  3209. {
  3210. using serializer = typename BasicJsonType::template json_serializer<T, void>;
  3211. static constexpr bool value =
  3212. is_detected_exact<void, to_json_function, serializer, BasicJsonType&,
  3213. T>::value;
  3214. };
  3215. ///////////////////
  3216. // is_ functions //
  3217. ///////////////////
  3218. // https://en.cppreference.com/w/cpp/types/conjunction
  3219. template<class...> struct conjunction : std::true_type { };
  3220. template<class B1> struct conjunction<B1> : B1 { };
  3221. template<class B1, class... Bn>
  3222. struct conjunction<B1, Bn...>
  3223. : std::conditional<bool(B1::value), conjunction<Bn...>, B1>::type {};
  3224. // https://en.cppreference.com/w/cpp/types/negation
  3225. template<class B> struct negation : std::integral_constant < bool, !B::value > { };
  3226. // Reimplementation of is_constructible and is_default_constructible, due to them being broken for
  3227. // std::pair and std::tuple until LWG 2367 fix (see https://cplusplus.github.io/LWG/lwg-defects.html#2367).
  3228. // This causes compile errors in e.g. clang 3.5 or gcc 4.9.
  3229. template <typename T>
  3230. struct is_default_constructible : std::is_default_constructible<T> {};
  3231. template <typename T1, typename T2>
  3232. struct is_default_constructible<std::pair<T1, T2>>
  3233. : conjunction<is_default_constructible<T1>, is_default_constructible<T2>> {};
  3234. template <typename T1, typename T2>
  3235. struct is_default_constructible<const std::pair<T1, T2>>
  3236. : conjunction<is_default_constructible<T1>, is_default_constructible<T2>> {};
  3237. template <typename... Ts>
  3238. struct is_default_constructible<std::tuple<Ts...>>
  3239. : conjunction<is_default_constructible<Ts>...> {};
  3240. template <typename... Ts>
  3241. struct is_default_constructible<const std::tuple<Ts...>>
  3242. : conjunction<is_default_constructible<Ts>...> {};
  3243. template <typename T, typename... Args>
  3244. struct is_constructible : std::is_constructible<T, Args...> {};
  3245. template <typename T1, typename T2>
  3246. struct is_constructible<std::pair<T1, T2>> : is_default_constructible<std::pair<T1, T2>> {};
  3247. template <typename T1, typename T2>
  3248. struct is_constructible<const std::pair<T1, T2>> : is_default_constructible<const std::pair<T1, T2>> {};
  3249. template <typename... Ts>
  3250. struct is_constructible<std::tuple<Ts...>> : is_default_constructible<std::tuple<Ts...>> {};
  3251. template <typename... Ts>
  3252. struct is_constructible<const std::tuple<Ts...>> : is_default_constructible<const std::tuple<Ts...>> {};
  3253. template<typename T, typename = void>
  3254. struct is_iterator_traits : std::false_type {};
  3255. template<typename T>
  3256. struct is_iterator_traits<iterator_traits<T>>
  3257. {
  3258. private:
  3259. using traits = iterator_traits<T>;
  3260. public:
  3261. static constexpr auto value =
  3262. is_detected<value_type_t, traits>::value &&
  3263. is_detected<difference_type_t, traits>::value &&
  3264. is_detected<pointer_t, traits>::value &&
  3265. is_detected<iterator_category_t, traits>::value &&
  3266. is_detected<reference_t, traits>::value;
  3267. };
  3268. template<typename T>
  3269. struct is_range
  3270. {
  3271. private:
  3272. using t_ref = typename std::add_lvalue_reference<T>::type;
  3273. using iterator = detected_t<result_of_begin, t_ref>;
  3274. using sentinel = detected_t<result_of_end, t_ref>;
  3275. // to be 100% correct, it should use https://en.cppreference.com/w/cpp/iterator/input_or_output_iterator
  3276. // and https://en.cppreference.com/w/cpp/iterator/sentinel_for
  3277. // but reimplementing these would be too much work, as a lot of other concepts are used underneath
  3278. static constexpr auto is_iterator_begin =
  3279. is_iterator_traits<iterator_traits<iterator>>::value;
  3280. public:
  3281. static constexpr bool value = !std::is_same<iterator, nonesuch>::value && !std::is_same<sentinel, nonesuch>::value && is_iterator_begin;
  3282. };
  3283. template<typename R>
  3284. using iterator_t = enable_if_t<is_range<R>::value, result_of_begin<decltype(std::declval<R&>())>>;
  3285. template<typename T>
  3286. using range_value_t = value_type_t<iterator_traits<iterator_t<T>>>;
  3287. // The following implementation of is_complete_type is taken from
  3288. // https://blogs.msdn.microsoft.com/vcblog/2015/12/02/partial-support-for-expression-sfinae-in-vs-2015-update-1/
  3289. // and is written by Xiang Fan who agreed to using it in this library.
  3290. template<typename T, typename = void>
  3291. struct is_complete_type : std::false_type {};
  3292. template<typename T>
  3293. struct is_complete_type<T, decltype(void(sizeof(T)))> : std::true_type {};
  3294. template<typename BasicJsonType, typename CompatibleObjectType,
  3295. typename = void>
  3296. struct is_compatible_object_type_impl : std::false_type {};
  3297. template<typename BasicJsonType, typename CompatibleObjectType>
  3298. struct is_compatible_object_type_impl <
  3299. BasicJsonType, CompatibleObjectType,
  3300. enable_if_t < is_detected<mapped_type_t, CompatibleObjectType>::value&&
  3301. is_detected<key_type_t, CompatibleObjectType>::value >>
  3302. {
  3303. using object_t = typename BasicJsonType::object_t;
  3304. // macOS's is_constructible does not play well with nonesuch...
  3305. static constexpr bool value =
  3306. is_constructible<typename object_t::key_type,
  3307. typename CompatibleObjectType::key_type>::value &&
  3308. is_constructible<typename object_t::mapped_type,
  3309. typename CompatibleObjectType::mapped_type>::value;
  3310. };
  3311. template<typename BasicJsonType, typename CompatibleObjectType>
  3312. struct is_compatible_object_type
  3313. : is_compatible_object_type_impl<BasicJsonType, CompatibleObjectType> {};
  3314. template<typename BasicJsonType, typename ConstructibleObjectType,
  3315. typename = void>
  3316. struct is_constructible_object_type_impl : std::false_type {};
  3317. template<typename BasicJsonType, typename ConstructibleObjectType>
  3318. struct is_constructible_object_type_impl <
  3319. BasicJsonType, ConstructibleObjectType,
  3320. enable_if_t < is_detected<mapped_type_t, ConstructibleObjectType>::value&&
  3321. is_detected<key_type_t, ConstructibleObjectType>::value >>
  3322. {
  3323. using object_t = typename BasicJsonType::object_t;
  3324. static constexpr bool value =
  3325. (is_default_constructible<ConstructibleObjectType>::value &&
  3326. (std::is_move_assignable<ConstructibleObjectType>::value ||
  3327. std::is_copy_assignable<ConstructibleObjectType>::value) &&
  3328. (is_constructible<typename ConstructibleObjectType::key_type,
  3329. typename object_t::key_type>::value &&
  3330. std::is_same <
  3331. typename object_t::mapped_type,
  3332. typename ConstructibleObjectType::mapped_type >::value)) ||
  3333. (has_from_json<BasicJsonType,
  3334. typename ConstructibleObjectType::mapped_type>::value ||
  3335. has_non_default_from_json <
  3336. BasicJsonType,
  3337. typename ConstructibleObjectType::mapped_type >::value);
  3338. };
  3339. template<typename BasicJsonType, typename ConstructibleObjectType>
  3340. struct is_constructible_object_type
  3341. : is_constructible_object_type_impl<BasicJsonType,
  3342. ConstructibleObjectType> {};
  3343. template<typename BasicJsonType, typename CompatibleStringType>
  3344. struct is_compatible_string_type
  3345. {
  3346. static constexpr auto value =
  3347. is_constructible<typename BasicJsonType::string_t, CompatibleStringType>::value;
  3348. };
  3349. template<typename BasicJsonType, typename ConstructibleStringType>
  3350. struct is_constructible_string_type
  3351. {
  3352. static constexpr auto value =
  3353. is_constructible<ConstructibleStringType,
  3354. typename BasicJsonType::string_t>::value;
  3355. };
  3356. template<typename BasicJsonType, typename CompatibleArrayType, typename = void>
  3357. struct is_compatible_array_type_impl : std::false_type {};
  3358. template<typename BasicJsonType, typename CompatibleArrayType>
  3359. struct is_compatible_array_type_impl <
  3360. BasicJsonType, CompatibleArrayType,
  3361. enable_if_t <
  3362. is_detected<iterator_t, CompatibleArrayType>::value&&
  3363. is_iterator_traits<iterator_traits<detected_t<iterator_t, CompatibleArrayType>>>::value&&
  3364. // special case for types like std::filesystem::path whose iterator's value_type are themselves
  3365. // c.f. https://github.com/nlohmann/json/pull/3073
  3366. !std::is_same<CompatibleArrayType, detected_t<range_value_t, CompatibleArrayType>>::value >>
  3367. {
  3368. static constexpr bool value =
  3369. is_constructible<BasicJsonType,
  3370. range_value_t<CompatibleArrayType>>::value;
  3371. };
  3372. template<typename BasicJsonType, typename CompatibleArrayType>
  3373. struct is_compatible_array_type
  3374. : is_compatible_array_type_impl<BasicJsonType, CompatibleArrayType> {};
  3375. template<typename BasicJsonType, typename ConstructibleArrayType, typename = void>
  3376. struct is_constructible_array_type_impl : std::false_type {};
  3377. template<typename BasicJsonType, typename ConstructibleArrayType>
  3378. struct is_constructible_array_type_impl <
  3379. BasicJsonType, ConstructibleArrayType,
  3380. enable_if_t<std::is_same<ConstructibleArrayType,
  3381. typename BasicJsonType::value_type>::value >>
  3382. : std::true_type {};
  3383. template<typename BasicJsonType, typename ConstructibleArrayType>
  3384. struct is_constructible_array_type_impl <
  3385. BasicJsonType, ConstructibleArrayType,
  3386. enable_if_t < !std::is_same<ConstructibleArrayType,
  3387. typename BasicJsonType::value_type>::value&&
  3388. !is_compatible_string_type<BasicJsonType, ConstructibleArrayType>::value&&
  3389. is_default_constructible<ConstructibleArrayType>::value&&
  3390. (std::is_move_assignable<ConstructibleArrayType>::value ||
  3391. std::is_copy_assignable<ConstructibleArrayType>::value)&&
  3392. is_detected<iterator_t, ConstructibleArrayType>::value&&
  3393. is_iterator_traits<iterator_traits<detected_t<iterator_t, ConstructibleArrayType>>>::value&&
  3394. is_detected<range_value_t, ConstructibleArrayType>::value&&
  3395. // special case for types like std::filesystem::path whose iterator's value_type are themselves
  3396. // c.f. https://github.com/nlohmann/json/pull/3073
  3397. !std::is_same<ConstructibleArrayType, detected_t<range_value_t, ConstructibleArrayType>>::value&&
  3398. is_complete_type <
  3399. detected_t<range_value_t, ConstructibleArrayType >>::value >>
  3400. {
  3401. using value_type = range_value_t<ConstructibleArrayType>;
  3402. static constexpr bool value =
  3403. std::is_same<value_type,
  3404. typename BasicJsonType::array_t::value_type>::value ||
  3405. has_from_json<BasicJsonType,
  3406. value_type>::value ||
  3407. has_non_default_from_json <
  3408. BasicJsonType,
  3409. value_type >::value;
  3410. };
  3411. template<typename BasicJsonType, typename ConstructibleArrayType>
  3412. struct is_constructible_array_type
  3413. : is_constructible_array_type_impl<BasicJsonType, ConstructibleArrayType> {};
  3414. template<typename RealIntegerType, typename CompatibleNumberIntegerType,
  3415. typename = void>
  3416. struct is_compatible_integer_type_impl : std::false_type {};
  3417. template<typename RealIntegerType, typename CompatibleNumberIntegerType>
  3418. struct is_compatible_integer_type_impl <
  3419. RealIntegerType, CompatibleNumberIntegerType,
  3420. enable_if_t < std::is_integral<RealIntegerType>::value&&
  3421. std::is_integral<CompatibleNumberIntegerType>::value&&
  3422. !std::is_same<bool, CompatibleNumberIntegerType>::value >>
  3423. {
  3424. // is there an assert somewhere on overflows?
  3425. using RealLimits = std::numeric_limits<RealIntegerType>;
  3426. using CompatibleLimits = std::numeric_limits<CompatibleNumberIntegerType>;
  3427. static constexpr auto value =
  3428. is_constructible<RealIntegerType,
  3429. CompatibleNumberIntegerType>::value &&
  3430. CompatibleLimits::is_integer &&
  3431. RealLimits::is_signed == CompatibleLimits::is_signed;
  3432. };
  3433. template<typename RealIntegerType, typename CompatibleNumberIntegerType>
  3434. struct is_compatible_integer_type
  3435. : is_compatible_integer_type_impl<RealIntegerType,
  3436. CompatibleNumberIntegerType> {};
  3437. template<typename BasicJsonType, typename CompatibleType, typename = void>
  3438. struct is_compatible_type_impl: std::false_type {};
  3439. template<typename BasicJsonType, typename CompatibleType>
  3440. struct is_compatible_type_impl <
  3441. BasicJsonType, CompatibleType,
  3442. enable_if_t<is_complete_type<CompatibleType>::value >>
  3443. {
  3444. static constexpr bool value =
  3445. has_to_json<BasicJsonType, CompatibleType>::value;
  3446. };
  3447. template<typename BasicJsonType, typename CompatibleType>
  3448. struct is_compatible_type
  3449. : is_compatible_type_impl<BasicJsonType, CompatibleType> {};
  3450. template<typename T1, typename T2>
  3451. struct is_constructible_tuple : std::false_type {};
  3452. template<typename T1, typename... Args>
  3453. struct is_constructible_tuple<T1, std::tuple<Args...>> : conjunction<is_constructible<T1, Args>...> {};
  3454. // a naive helper to check if a type is an ordered_map (exploits the fact that
  3455. // ordered_map inherits capacity() from std::vector)
  3456. template <typename T>
  3457. struct is_ordered_map
  3458. {
  3459. using one = char;
  3460. struct two
  3461. {
  3462. char x[2]; // NOLINT(cppcoreguidelines-avoid-c-arrays,hicpp-avoid-c-arrays,modernize-avoid-c-arrays)
  3463. };
  3464. template <typename C> static one test( decltype(&C::capacity) ) ;
  3465. template <typename C> static two test(...);
  3466. enum { value = sizeof(test<T>(nullptr)) == sizeof(char) }; // NOLINT(cppcoreguidelines-pro-type-vararg,hicpp-vararg)
  3467. };
  3468. // to avoid useless casts (see https://github.com/nlohmann/json/issues/2893#issuecomment-889152324)
  3469. template < typename T, typename U, enable_if_t < !std::is_same<T, U>::value, int > = 0 >
  3470. T conditional_static_cast(U value)
  3471. {
  3472. return static_cast<T>(value);
  3473. }
  3474. template<typename T, typename U, enable_if_t<std::is_same<T, U>::value, int> = 0>
  3475. T conditional_static_cast(U value)
  3476. {
  3477. return value;
  3478. }
  3479. } // namespace detail
  3480. } // namespace nlohmann
  3481. // #include <nlohmann/detail/value_t.hpp>
  3482. #ifdef JSON_HAS_CPP_17
  3483. #include <filesystem>
  3484. #endif
  3485. namespace nlohmann
  3486. {
  3487. namespace detail
  3488. {
  3489. template<typename BasicJsonType>
  3490. void from_json(const BasicJsonType& j, typename std::nullptr_t& n)
  3491. {
  3492. if (JSON_HEDLEY_UNLIKELY(!j.is_null()))
  3493. {
  3494. JSON_THROW(type_error::create(302, "type must be null, but is " + std::string(j.type_name()), j));
  3495. }
  3496. n = nullptr;
  3497. }
  3498. // overloads for basic_json template parameters
  3499. template < typename BasicJsonType, typename ArithmeticType,
  3500. enable_if_t < std::is_arithmetic<ArithmeticType>::value&&
  3501. !std::is_same<ArithmeticType, typename BasicJsonType::boolean_t>::value,
  3502. int > = 0 >
  3503. void get_arithmetic_value(const BasicJsonType& j, ArithmeticType& val)
  3504. {
  3505. switch (static_cast<value_t>(j))
  3506. {
  3507. case value_t::number_unsigned:
  3508. {
  3509. val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::number_unsigned_t*>());
  3510. break;
  3511. }
  3512. case value_t::number_integer:
  3513. {
  3514. val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::number_integer_t*>());
  3515. break;
  3516. }
  3517. case value_t::number_float:
  3518. {
  3519. val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::number_float_t*>());
  3520. break;
  3521. }
  3522. case value_t::null:
  3523. case value_t::object:
  3524. case value_t::array:
  3525. case value_t::string:
  3526. case value_t::boolean:
  3527. case value_t::binary:
  3528. case value_t::discarded:
  3529. default:
  3530. JSON_THROW(type_error::create(302, "type must be number, but is " + std::string(j.type_name()), j));
  3531. }
  3532. }
  3533. template<typename BasicJsonType>
  3534. void from_json(const BasicJsonType& j, typename BasicJsonType::boolean_t& b)
  3535. {
  3536. if (JSON_HEDLEY_UNLIKELY(!j.is_boolean()))
  3537. {
  3538. JSON_THROW(type_error::create(302, "type must be boolean, but is " + std::string(j.type_name()), j));
  3539. }
  3540. b = *j.template get_ptr<const typename BasicJsonType::boolean_t*>();
  3541. }
  3542. template<typename BasicJsonType>
  3543. void from_json(const BasicJsonType& j, typename BasicJsonType::string_t& s)
  3544. {
  3545. if (JSON_HEDLEY_UNLIKELY(!j.is_string()))
  3546. {
  3547. JSON_THROW(type_error::create(302, "type must be string, but is " + std::string(j.type_name()), j));
  3548. }
  3549. s = *j.template get_ptr<const typename BasicJsonType::string_t*>();
  3550. }
  3551. template <
  3552. typename BasicJsonType, typename ConstructibleStringType,
  3553. enable_if_t <
  3554. is_constructible_string_type<BasicJsonType, ConstructibleStringType>::value&&
  3555. !std::is_same<typename BasicJsonType::string_t,
  3556. ConstructibleStringType>::value,
  3557. int > = 0 >
  3558. void from_json(const BasicJsonType& j, ConstructibleStringType& s)
  3559. {
  3560. if (JSON_HEDLEY_UNLIKELY(!j.is_string()))
  3561. {
  3562. JSON_THROW(type_error::create(302, "type must be string, but is " + std::string(j.type_name()), j));
  3563. }
  3564. s = *j.template get_ptr<const typename BasicJsonType::string_t*>();
  3565. }
  3566. template<typename BasicJsonType>
  3567. void from_json(const BasicJsonType& j, typename BasicJsonType::number_float_t& val)
  3568. {
  3569. get_arithmetic_value(j, val);
  3570. }
  3571. template<typename BasicJsonType>
  3572. void from_json(const BasicJsonType& j, typename BasicJsonType::number_unsigned_t& val)
  3573. {
  3574. get_arithmetic_value(j, val);
  3575. }
  3576. template<typename BasicJsonType>
  3577. void from_json(const BasicJsonType& j, typename BasicJsonType::number_integer_t& val)
  3578. {
  3579. get_arithmetic_value(j, val);
  3580. }
  3581. template<typename BasicJsonType, typename EnumType,
  3582. enable_if_t<std::is_enum<EnumType>::value, int> = 0>
  3583. void from_json(const BasicJsonType& j, EnumType& e)
  3584. {
  3585. typename std::underlying_type<EnumType>::type val;
  3586. get_arithmetic_value(j, val);
  3587. e = static_cast<EnumType>(val);
  3588. }
  3589. // forward_list doesn't have an insert method
  3590. template<typename BasicJsonType, typename T, typename Allocator,
  3591. enable_if_t<is_getable<BasicJsonType, T>::value, int> = 0>
  3592. void from_json(const BasicJsonType& j, std::forward_list<T, Allocator>& l)
  3593. {
  3594. if (JSON_HEDLEY_UNLIKELY(!j.is_array()))
  3595. {
  3596. JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(j.type_name()), j));
  3597. }
  3598. l.clear();
  3599. std::transform(j.rbegin(), j.rend(),
  3600. std::front_inserter(l), [](const BasicJsonType & i)
  3601. {
  3602. return i.template get<T>();
  3603. });
  3604. }
  3605. // valarray doesn't have an insert method
  3606. template<typename BasicJsonType, typename T,
  3607. enable_if_t<is_getable<BasicJsonType, T>::value, int> = 0>
  3608. void from_json(const BasicJsonType& j, std::valarray<T>& l)
  3609. {
  3610. if (JSON_HEDLEY_UNLIKELY(!j.is_array()))
  3611. {
  3612. JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(j.type_name()), j));
  3613. }
  3614. l.resize(j.size());
  3615. std::transform(j.begin(), j.end(), std::begin(l),
  3616. [](const BasicJsonType & elem)
  3617. {
  3618. return elem.template get<T>();
  3619. });
  3620. }
  3621. template<typename BasicJsonType, typename T, std::size_t N>
  3622. auto from_json(const BasicJsonType& j, T (&arr)[N]) // NOLINT(cppcoreguidelines-avoid-c-arrays,hicpp-avoid-c-arrays,modernize-avoid-c-arrays)
  3623. -> decltype(j.template get<T>(), void())
  3624. {
  3625. for (std::size_t i = 0; i < N; ++i)
  3626. {
  3627. arr[i] = j.at(i).template get<T>();
  3628. }
  3629. }
  3630. template<typename BasicJsonType>
  3631. void from_json_array_impl(const BasicJsonType& j, typename BasicJsonType::array_t& arr, priority_tag<3> /*unused*/)
  3632. {
  3633. arr = *j.template get_ptr<const typename BasicJsonType::array_t*>();
  3634. }
  3635. template<typename BasicJsonType, typename T, std::size_t N>
  3636. auto from_json_array_impl(const BasicJsonType& j, std::array<T, N>& arr,
  3637. priority_tag<2> /*unused*/)
  3638. -> decltype(j.template get<T>(), void())
  3639. {
  3640. for (std::size_t i = 0; i < N; ++i)
  3641. {
  3642. arr[i] = j.at(i).template get<T>();
  3643. }
  3644. }
  3645. template<typename BasicJsonType, typename ConstructibleArrayType,
  3646. enable_if_t<
  3647. std::is_assignable<ConstructibleArrayType&, ConstructibleArrayType>::value,
  3648. int> = 0>
  3649. auto from_json_array_impl(const BasicJsonType& j, ConstructibleArrayType& arr, priority_tag<1> /*unused*/)
  3650. -> decltype(
  3651. arr.reserve(std::declval<typename ConstructibleArrayType::size_type>()),
  3652. j.template get<typename ConstructibleArrayType::value_type>(),
  3653. void())
  3654. {
  3655. using std::end;
  3656. ConstructibleArrayType ret;
  3657. ret.reserve(j.size());
  3658. std::transform(j.begin(), j.end(),
  3659. std::inserter(ret, end(ret)), [](const BasicJsonType & i)
  3660. {
  3661. // get<BasicJsonType>() returns *this, this won't call a from_json
  3662. // method when value_type is BasicJsonType
  3663. return i.template get<typename ConstructibleArrayType::value_type>();
  3664. });
  3665. arr = std::move(ret);
  3666. }
  3667. template<typename BasicJsonType, typename ConstructibleArrayType,
  3668. enable_if_t<
  3669. std::is_assignable<ConstructibleArrayType&, ConstructibleArrayType>::value,
  3670. int> = 0>
  3671. void from_json_array_impl(const BasicJsonType& j, ConstructibleArrayType& arr,
  3672. priority_tag<0> /*unused*/)
  3673. {
  3674. using std::end;
  3675. ConstructibleArrayType ret;
  3676. std::transform(
  3677. j.begin(), j.end(), std::inserter(ret, end(ret)),
  3678. [](const BasicJsonType & i)
  3679. {
  3680. // get<BasicJsonType>() returns *this, this won't call a from_json
  3681. // method when value_type is BasicJsonType
  3682. return i.template get<typename ConstructibleArrayType::value_type>();
  3683. });
  3684. arr = std::move(ret);
  3685. }
  3686. template < typename BasicJsonType, typename ConstructibleArrayType,
  3687. enable_if_t <
  3688. is_constructible_array_type<BasicJsonType, ConstructibleArrayType>::value&&
  3689. !is_constructible_object_type<BasicJsonType, ConstructibleArrayType>::value&&
  3690. !is_constructible_string_type<BasicJsonType, ConstructibleArrayType>::value&&
  3691. !std::is_same<ConstructibleArrayType, typename BasicJsonType::binary_t>::value&&
  3692. !is_basic_json<ConstructibleArrayType>::value,
  3693. int > = 0 >
  3694. auto from_json(const BasicJsonType& j, ConstructibleArrayType& arr)
  3695. -> decltype(from_json_array_impl(j, arr, priority_tag<3> {}),
  3696. j.template get<typename ConstructibleArrayType::value_type>(),
  3697. void())
  3698. {
  3699. if (JSON_HEDLEY_UNLIKELY(!j.is_array()))
  3700. {
  3701. JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(j.type_name()), j));
  3702. }
  3703. from_json_array_impl(j, arr, priority_tag<3> {});
  3704. }
  3705. template < typename BasicJsonType, typename T, std::size_t... Idx >
  3706. std::array<T, sizeof...(Idx)> from_json_inplace_array_impl(BasicJsonType&& j,
  3707. identity_tag<std::array<T, sizeof...(Idx)>> /*unused*/, index_sequence<Idx...> /*unused*/)
  3708. {
  3709. return { { std::forward<BasicJsonType>(j).at(Idx).template get<T>()... } };
  3710. }
  3711. template < typename BasicJsonType, typename T, std::size_t N >
  3712. auto from_json(BasicJsonType&& j, identity_tag<std::array<T, N>> tag)
  3713. -> decltype(from_json_inplace_array_impl(std::forward<BasicJsonType>(j), tag, make_index_sequence<N> {}))
  3714. {
  3715. if (JSON_HEDLEY_UNLIKELY(!j.is_array()))
  3716. {
  3717. JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(j.type_name()), j));
  3718. }
  3719. return from_json_inplace_array_impl(std::forward<BasicJsonType>(j), tag, make_index_sequence<N> {});
  3720. }
  3721. template<typename BasicJsonType>
  3722. void from_json(const BasicJsonType& j, typename BasicJsonType::binary_t& bin)
  3723. {
  3724. if (JSON_HEDLEY_UNLIKELY(!j.is_binary()))
  3725. {
  3726. JSON_THROW(type_error::create(302, "type must be binary, but is " + std::string(j.type_name()), j));
  3727. }
  3728. bin = *j.template get_ptr<const typename BasicJsonType::binary_t*>();
  3729. }
  3730. template<typename BasicJsonType, typename ConstructibleObjectType,
  3731. enable_if_t<is_constructible_object_type<BasicJsonType, ConstructibleObjectType>::value, int> = 0>
  3732. void from_json(const BasicJsonType& j, ConstructibleObjectType& obj)
  3733. {
  3734. if (JSON_HEDLEY_UNLIKELY(!j.is_object()))
  3735. {
  3736. JSON_THROW(type_error::create(302, "type must be object, but is " + std::string(j.type_name()), j));
  3737. }
  3738. ConstructibleObjectType ret;
  3739. const auto* inner_object = j.template get_ptr<const typename BasicJsonType::object_t*>();
  3740. using value_type = typename ConstructibleObjectType::value_type;
  3741. std::transform(
  3742. inner_object->begin(), inner_object->end(),
  3743. std::inserter(ret, ret.begin()),
  3744. [](typename BasicJsonType::object_t::value_type const & p)
  3745. {
  3746. return value_type(p.first, p.second.template get<typename ConstructibleObjectType::mapped_type>());
  3747. });
  3748. obj = std::move(ret);
  3749. }
  3750. // overload for arithmetic types, not chosen for basic_json template arguments
  3751. // (BooleanType, etc..); note: Is it really necessary to provide explicit
  3752. // overloads for boolean_t etc. in case of a custom BooleanType which is not
  3753. // an arithmetic type?
  3754. template < typename BasicJsonType, typename ArithmeticType,
  3755. enable_if_t <
  3756. std::is_arithmetic<ArithmeticType>::value&&
  3757. !std::is_same<ArithmeticType, typename BasicJsonType::number_unsigned_t>::value&&
  3758. !std::is_same<ArithmeticType, typename BasicJsonType::number_integer_t>::value&&
  3759. !std::is_same<ArithmeticType, typename BasicJsonType::number_float_t>::value&&
  3760. !std::is_same<ArithmeticType, typename BasicJsonType::boolean_t>::value,
  3761. int > = 0 >
  3762. void from_json(const BasicJsonType& j, ArithmeticType& val)
  3763. {
  3764. switch (static_cast<value_t>(j))
  3765. {
  3766. case value_t::number_unsigned:
  3767. {
  3768. val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::number_unsigned_t*>());
  3769. break;
  3770. }
  3771. case value_t::number_integer:
  3772. {
  3773. val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::number_integer_t*>());
  3774. break;
  3775. }
  3776. case value_t::number_float:
  3777. {
  3778. val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::number_float_t*>());
  3779. break;
  3780. }
  3781. case value_t::boolean:
  3782. {
  3783. val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::boolean_t*>());
  3784. break;
  3785. }
  3786. case value_t::null:
  3787. case value_t::object:
  3788. case value_t::array:
  3789. case value_t::string:
  3790. case value_t::binary:
  3791. case value_t::discarded:
  3792. default:
  3793. JSON_THROW(type_error::create(302, "type must be number, but is " + std::string(j.type_name()), j));
  3794. }
  3795. }
  3796. template<typename BasicJsonType, typename... Args, std::size_t... Idx>
  3797. std::tuple<Args...> from_json_tuple_impl_base(BasicJsonType&& j, index_sequence<Idx...> /*unused*/)
  3798. {
  3799. return std::make_tuple(std::forward<BasicJsonType>(j).at(Idx).template get<Args>()...);
  3800. }
  3801. template < typename BasicJsonType, class A1, class A2 >
  3802. std::pair<A1, A2> from_json_tuple_impl(BasicJsonType&& j, identity_tag<std::pair<A1, A2>> /*unused*/, priority_tag<0> /*unused*/)
  3803. {
  3804. return {std::forward<BasicJsonType>(j).at(0).template get<A1>(),
  3805. std::forward<BasicJsonType>(j).at(1).template get<A2>()};
  3806. }
  3807. template<typename BasicJsonType, typename A1, typename A2>
  3808. void from_json_tuple_impl(BasicJsonType&& j, std::pair<A1, A2>& p, priority_tag<1> /*unused*/)
  3809. {
  3810. p = from_json_tuple_impl(std::forward<BasicJsonType>(j), identity_tag<std::pair<A1, A2>> {}, priority_tag<0> {});
  3811. }
  3812. template<typename BasicJsonType, typename... Args>
  3813. std::tuple<Args...> from_json_tuple_impl(BasicJsonType&& j, identity_tag<std::tuple<Args...>> /*unused*/, priority_tag<2> /*unused*/)
  3814. {
  3815. return from_json_tuple_impl_base<BasicJsonType, Args...>(std::forward<BasicJsonType>(j), index_sequence_for<Args...> {});
  3816. }
  3817. template<typename BasicJsonType, typename... Args>
  3818. void from_json_tuple_impl(BasicJsonType&& j, std::tuple<Args...>& t, priority_tag<3> /*unused*/)
  3819. {
  3820. t = from_json_tuple_impl_base<BasicJsonType, Args...>(std::forward<BasicJsonType>(j), index_sequence_for<Args...> {});
  3821. }
  3822. template<typename BasicJsonType, typename TupleRelated>
  3823. auto from_json(BasicJsonType&& j, TupleRelated&& t)
  3824. -> decltype(from_json_tuple_impl(std::forward<BasicJsonType>(j), std::forward<TupleRelated>(t), priority_tag<3> {}))
  3825. {
  3826. if (JSON_HEDLEY_UNLIKELY(!j.is_array()))
  3827. {
  3828. JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(j.type_name()), j));
  3829. }
  3830. return from_json_tuple_impl(std::forward<BasicJsonType>(j), std::forward<TupleRelated>(t), priority_tag<3> {});
  3831. }
  3832. template < typename BasicJsonType, typename Key, typename Value, typename Compare, typename Allocator,
  3833. typename = enable_if_t < !std::is_constructible <
  3834. typename BasicJsonType::string_t, Key >::value >>
  3835. void from_json(const BasicJsonType& j, std::map<Key, Value, Compare, Allocator>& m)
  3836. {
  3837. if (JSON_HEDLEY_UNLIKELY(!j.is_array()))
  3838. {
  3839. JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(j.type_name()), j));
  3840. }
  3841. m.clear();
  3842. for (const auto& p : j)
  3843. {
  3844. if (JSON_HEDLEY_UNLIKELY(!p.is_array()))
  3845. {
  3846. JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(p.type_name()), j));
  3847. }
  3848. m.emplace(p.at(0).template get<Key>(), p.at(1).template get<Value>());
  3849. }
  3850. }
  3851. template < typename BasicJsonType, typename Key, typename Value, typename Hash, typename KeyEqual, typename Allocator,
  3852. typename = enable_if_t < !std::is_constructible <
  3853. typename BasicJsonType::string_t, Key >::value >>
  3854. void from_json(const BasicJsonType& j, std::unordered_map<Key, Value, Hash, KeyEqual, Allocator>& m)
  3855. {
  3856. if (JSON_HEDLEY_UNLIKELY(!j.is_array()))
  3857. {
  3858. JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(j.type_name()), j));
  3859. }
  3860. m.clear();
  3861. for (const auto& p : j)
  3862. {
  3863. if (JSON_HEDLEY_UNLIKELY(!p.is_array()))
  3864. {
  3865. JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(p.type_name()), j));
  3866. }
  3867. m.emplace(p.at(0).template get<Key>(), p.at(1).template get<Value>());
  3868. }
  3869. }
  3870. #ifdef JSON_HAS_CPP_17
  3871. template<typename BasicJsonType>
  3872. void from_json(const BasicJsonType& j, std::filesystem::path& p)
  3873. {
  3874. if (JSON_HEDLEY_UNLIKELY(!j.is_string()))
  3875. {
  3876. JSON_THROW(type_error::create(302, "type must be string, but is " + std::string(j.type_name()), j));
  3877. }
  3878. p = *j.template get_ptr<const typename BasicJsonType::string_t*>();
  3879. }
  3880. #endif
  3881. struct from_json_fn
  3882. {
  3883. template<typename BasicJsonType, typename T>
  3884. auto operator()(const BasicJsonType& j, T&& val) const
  3885. noexcept(noexcept(from_json(j, std::forward<T>(val))))
  3886. -> decltype(from_json(j, std::forward<T>(val)))
  3887. {
  3888. return from_json(j, std::forward<T>(val));
  3889. }
  3890. };
  3891. } // namespace detail
  3892. /// namespace to hold default `from_json` function
  3893. /// to see why this is required:
  3894. /// http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2015/n4381.html
  3895. namespace // NOLINT(cert-dcl59-cpp,fuchsia-header-anon-namespaces,google-build-namespaces)
  3896. {
  3897. constexpr const auto& from_json = detail::static_const<detail::from_json_fn>::value; // NOLINT(misc-definitions-in-headers)
  3898. } // namespace
  3899. } // namespace nlohmann
  3900. // #include <nlohmann/detail/conversions/to_json.hpp>
  3901. #include <algorithm> // copy
  3902. #include <iterator> // begin, end
  3903. #include <string> // string
  3904. #include <tuple> // tuple, get
  3905. #include <type_traits> // is_same, is_constructible, is_floating_point, is_enum, underlying_type
  3906. #include <utility> // move, forward, declval, pair
  3907. #include <valarray> // valarray
  3908. #include <vector> // vector
  3909. // #include <nlohmann/detail/macro_scope.hpp>
  3910. // #include <nlohmann/detail/iterators/iteration_proxy.hpp>
  3911. #include <cstddef> // size_t
  3912. #include <iterator> // input_iterator_tag
  3913. #include <string> // string, to_string
  3914. #include <tuple> // tuple_size, get, tuple_element
  3915. #include <utility> // move
  3916. // #include <nlohmann/detail/meta/type_traits.hpp>
  3917. // #include <nlohmann/detail/value_t.hpp>
  3918. namespace nlohmann
  3919. {
  3920. namespace detail
  3921. {
  3922. template<typename string_type>
  3923. void int_to_string( string_type& target, std::size_t value )
  3924. {
  3925. // For ADL
  3926. using std::to_string;
  3927. target = to_string(value);
  3928. }
  3929. template<typename IteratorType> class iteration_proxy_value
  3930. {
  3931. public:
  3932. using difference_type = std::ptrdiff_t;
  3933. using value_type = iteration_proxy_value;
  3934. using pointer = value_type * ;
  3935. using reference = value_type & ;
  3936. using iterator_category = std::input_iterator_tag;
  3937. using string_type = typename std::remove_cv< typename std::remove_reference<decltype( std::declval<IteratorType>().key() ) >::type >::type;
  3938. private:
  3939. /// the iterator
  3940. IteratorType anchor;
  3941. /// an index for arrays (used to create key names)
  3942. std::size_t array_index = 0;
  3943. /// last stringified array index
  3944. mutable std::size_t array_index_last = 0;
  3945. /// a string representation of the array index
  3946. mutable string_type array_index_str = "0";
  3947. /// an empty string (to return a reference for primitive values)
  3948. const string_type empty_str{};
  3949. public:
  3950. explicit iteration_proxy_value(IteratorType it) noexcept
  3951. : anchor(std::move(it))
  3952. {}
  3953. /// dereference operator (needed for range-based for)
  3954. iteration_proxy_value& operator*()
  3955. {
  3956. return *this;
  3957. }
  3958. /// increment operator (needed for range-based for)
  3959. iteration_proxy_value& operator++()
  3960. {
  3961. ++anchor;
  3962. ++array_index;
  3963. return *this;
  3964. }
  3965. /// equality operator (needed for InputIterator)
  3966. bool operator==(const iteration_proxy_value& o) const
  3967. {
  3968. return anchor == o.anchor;
  3969. }
  3970. /// inequality operator (needed for range-based for)
  3971. bool operator!=(const iteration_proxy_value& o) const
  3972. {
  3973. return anchor != o.anchor;
  3974. }
  3975. /// return key of the iterator
  3976. const string_type& key() const
  3977. {
  3978. JSON_ASSERT(anchor.m_object != nullptr);
  3979. switch (anchor.m_object->type())
  3980. {
  3981. // use integer array index as key
  3982. case value_t::array:
  3983. {
  3984. if (array_index != array_index_last)
  3985. {
  3986. int_to_string( array_index_str, array_index );
  3987. array_index_last = array_index;
  3988. }
  3989. return array_index_str;
  3990. }
  3991. // use key from the object
  3992. case value_t::object:
  3993. return anchor.key();
  3994. // use an empty key for all primitive types
  3995. case value_t::null:
  3996. case value_t::string:
  3997. case value_t::boolean:
  3998. case value_t::number_integer:
  3999. case value_t::number_unsigned:
  4000. case value_t::number_float:
  4001. case value_t::binary:
  4002. case value_t::discarded:
  4003. default:
  4004. return empty_str;
  4005. }
  4006. }
  4007. /// return value of the iterator
  4008. typename IteratorType::reference value() const
  4009. {
  4010. return anchor.value();
  4011. }
  4012. };
  4013. /// proxy class for the items() function
  4014. template<typename IteratorType> class iteration_proxy
  4015. {
  4016. private:
  4017. /// the container to iterate
  4018. typename IteratorType::reference container;
  4019. public:
  4020. /// construct iteration proxy from a container
  4021. explicit iteration_proxy(typename IteratorType::reference cont) noexcept
  4022. : container(cont) {}
  4023. /// return iterator begin (needed for range-based for)
  4024. iteration_proxy_value<IteratorType> begin() noexcept
  4025. {
  4026. return iteration_proxy_value<IteratorType>(container.begin());
  4027. }
  4028. /// return iterator end (needed for range-based for)
  4029. iteration_proxy_value<IteratorType> end() noexcept
  4030. {
  4031. return iteration_proxy_value<IteratorType>(container.end());
  4032. }
  4033. };
  4034. // Structured Bindings Support
  4035. // For further reference see https://blog.tartanllama.xyz/structured-bindings/
  4036. // And see https://github.com/nlohmann/json/pull/1391
  4037. template<std::size_t N, typename IteratorType, enable_if_t<N == 0, int> = 0>
  4038. auto get(const nlohmann::detail::iteration_proxy_value<IteratorType>& i) -> decltype(i.key())
  4039. {
  4040. return i.key();
  4041. }
  4042. // Structured Bindings Support
  4043. // For further reference see https://blog.tartanllama.xyz/structured-bindings/
  4044. // And see https://github.com/nlohmann/json/pull/1391
  4045. template<std::size_t N, typename IteratorType, enable_if_t<N == 1, int> = 0>
  4046. auto get(const nlohmann::detail::iteration_proxy_value<IteratorType>& i) -> decltype(i.value())
  4047. {
  4048. return i.value();
  4049. }
  4050. } // namespace detail
  4051. } // namespace nlohmann
  4052. // The Addition to the STD Namespace is required to add
  4053. // Structured Bindings Support to the iteration_proxy_value class
  4054. // For further reference see https://blog.tartanllama.xyz/structured-bindings/
  4055. // And see https://github.com/nlohmann/json/pull/1391
  4056. namespace std
  4057. {
  4058. #if defined(__clang__)
  4059. // Fix: https://github.com/nlohmann/json/issues/1401
  4060. #pragma clang diagnostic push
  4061. #pragma clang diagnostic ignored "-Wmismatched-tags"
  4062. #endif
  4063. template<typename IteratorType>
  4064. class tuple_size<::nlohmann::detail::iteration_proxy_value<IteratorType>>
  4065. : public std::integral_constant<std::size_t, 2> {};
  4066. template<std::size_t N, typename IteratorType>
  4067. class tuple_element<N, ::nlohmann::detail::iteration_proxy_value<IteratorType >>
  4068. {
  4069. public:
  4070. using type = decltype(
  4071. get<N>(std::declval <
  4072. ::nlohmann::detail::iteration_proxy_value<IteratorType >> ()));
  4073. };
  4074. #if defined(__clang__)
  4075. #pragma clang diagnostic pop
  4076. #endif
  4077. } // namespace std
  4078. // #include <nlohmann/detail/meta/cpp_future.hpp>
  4079. // #include <nlohmann/detail/meta/type_traits.hpp>
  4080. // #include <nlohmann/detail/value_t.hpp>
  4081. #ifdef JSON_HAS_CPP_17
  4082. #include <filesystem>
  4083. #endif
  4084. namespace nlohmann
  4085. {
  4086. namespace detail
  4087. {
  4088. //////////////////
  4089. // constructors //
  4090. //////////////////
  4091. /*
  4092. * Note all external_constructor<>::construct functions need to call
  4093. * j.m_value.destroy(j.m_type) to avoid a memory leak in case j contains an
  4094. * allocated value (e.g., a string). See bug issue
  4095. * https://github.com/nlohmann/json/issues/2865 for more information.
  4096. */
  4097. template<value_t> struct external_constructor;
  4098. template<>
  4099. struct external_constructor<value_t::boolean>
  4100. {
  4101. template<typename BasicJsonType>
  4102. static void construct(BasicJsonType& j, typename BasicJsonType::boolean_t b) noexcept
  4103. {
  4104. j.m_value.destroy(j.m_type);
  4105. j.m_type = value_t::boolean;
  4106. j.m_value = b;
  4107. j.assert_invariant();
  4108. }
  4109. };
  4110. template<>
  4111. struct external_constructor<value_t::string>
  4112. {
  4113. template<typename BasicJsonType>
  4114. static void construct(BasicJsonType& j, const typename BasicJsonType::string_t& s)
  4115. {
  4116. j.m_value.destroy(j.m_type);
  4117. j.m_type = value_t::string;
  4118. j.m_value = s;
  4119. j.assert_invariant();
  4120. }
  4121. template<typename BasicJsonType>
  4122. static void construct(BasicJsonType& j, typename BasicJsonType::string_t&& s)
  4123. {
  4124. j.m_value.destroy(j.m_type);
  4125. j.m_type = value_t::string;
  4126. j.m_value = std::move(s);
  4127. j.assert_invariant();
  4128. }
  4129. template < typename BasicJsonType, typename CompatibleStringType,
  4130. enable_if_t < !std::is_same<CompatibleStringType, typename BasicJsonType::string_t>::value,
  4131. int > = 0 >
  4132. static void construct(BasicJsonType& j, const CompatibleStringType& str)
  4133. {
  4134. j.m_value.destroy(j.m_type);
  4135. j.m_type = value_t::string;
  4136. j.m_value.string = j.template create<typename BasicJsonType::string_t>(str);
  4137. j.assert_invariant();
  4138. }
  4139. };
  4140. template<>
  4141. struct external_constructor<value_t::binary>
  4142. {
  4143. template<typename BasicJsonType>
  4144. static void construct(BasicJsonType& j, const typename BasicJsonType::binary_t& b)
  4145. {
  4146. j.m_value.destroy(j.m_type);
  4147. j.m_type = value_t::binary;
  4148. j.m_value = typename BasicJsonType::binary_t(b);
  4149. j.assert_invariant();
  4150. }
  4151. template<typename BasicJsonType>
  4152. static void construct(BasicJsonType& j, typename BasicJsonType::binary_t&& b)
  4153. {
  4154. j.m_value.destroy(j.m_type);
  4155. j.m_type = value_t::binary;
  4156. j.m_value = typename BasicJsonType::binary_t(std::move(b));
  4157. j.assert_invariant();
  4158. }
  4159. };
  4160. template<>
  4161. struct external_constructor<value_t::number_float>
  4162. {
  4163. template<typename BasicJsonType>
  4164. static void construct(BasicJsonType& j, typename BasicJsonType::number_float_t val) noexcept
  4165. {
  4166. j.m_value.destroy(j.m_type);
  4167. j.m_type = value_t::number_float;
  4168. j.m_value = val;
  4169. j.assert_invariant();
  4170. }
  4171. };
  4172. template<>
  4173. struct external_constructor<value_t::number_unsigned>
  4174. {
  4175. template<typename BasicJsonType>
  4176. static void construct(BasicJsonType& j, typename BasicJsonType::number_unsigned_t val) noexcept
  4177. {
  4178. j.m_value.destroy(j.m_type);
  4179. j.m_type = value_t::number_unsigned;
  4180. j.m_value = val;
  4181. j.assert_invariant();
  4182. }
  4183. };
  4184. template<>
  4185. struct external_constructor<value_t::number_integer>
  4186. {
  4187. template<typename BasicJsonType>
  4188. static void construct(BasicJsonType& j, typename BasicJsonType::number_integer_t val) noexcept
  4189. {
  4190. j.m_value.destroy(j.m_type);
  4191. j.m_type = value_t::number_integer;
  4192. j.m_value = val;
  4193. j.assert_invariant();
  4194. }
  4195. };
  4196. template<>
  4197. struct external_constructor<value_t::array>
  4198. {
  4199. template<typename BasicJsonType>
  4200. static void construct(BasicJsonType& j, const typename BasicJsonType::array_t& arr)
  4201. {
  4202. j.m_value.destroy(j.m_type);
  4203. j.m_type = value_t::array;
  4204. j.m_value = arr;
  4205. j.set_parents();
  4206. j.assert_invariant();
  4207. }
  4208. template<typename BasicJsonType>
  4209. static void construct(BasicJsonType& j, typename BasicJsonType::array_t&& arr)
  4210. {
  4211. j.m_value.destroy(j.m_type);
  4212. j.m_type = value_t::array;
  4213. j.m_value = std::move(arr);
  4214. j.set_parents();
  4215. j.assert_invariant();
  4216. }
  4217. template < typename BasicJsonType, typename CompatibleArrayType,
  4218. enable_if_t < !std::is_same<CompatibleArrayType, typename BasicJsonType::array_t>::value,
  4219. int > = 0 >
  4220. static void construct(BasicJsonType& j, const CompatibleArrayType& arr)
  4221. {
  4222. using std::begin;
  4223. using std::end;
  4224. j.m_value.destroy(j.m_type);
  4225. j.m_type = value_t::array;
  4226. j.m_value.array = j.template create<typename BasicJsonType::array_t>(begin(arr), end(arr));
  4227. j.set_parents();
  4228. j.assert_invariant();
  4229. }
  4230. template<typename BasicJsonType>
  4231. static void construct(BasicJsonType& j, const std::vector<bool>& arr)
  4232. {
  4233. j.m_value.destroy(j.m_type);
  4234. j.m_type = value_t::array;
  4235. j.m_value = value_t::array;
  4236. j.m_value.array->reserve(arr.size());
  4237. for (const bool x : arr)
  4238. {
  4239. j.m_value.array->push_back(x);
  4240. j.set_parent(j.m_value.array->back());
  4241. }
  4242. j.assert_invariant();
  4243. }
  4244. template<typename BasicJsonType, typename T,
  4245. enable_if_t<std::is_convertible<T, BasicJsonType>::value, int> = 0>
  4246. static void construct(BasicJsonType& j, const std::valarray<T>& arr)
  4247. {
  4248. j.m_value.destroy(j.m_type);
  4249. j.m_type = value_t::array;
  4250. j.m_value = value_t::array;
  4251. j.m_value.array->resize(arr.size());
  4252. if (arr.size() > 0)
  4253. {
  4254. std::copy(std::begin(arr), std::end(arr), j.m_value.array->begin());
  4255. }
  4256. j.set_parents();
  4257. j.assert_invariant();
  4258. }
  4259. };
  4260. template<>
  4261. struct external_constructor<value_t::object>
  4262. {
  4263. template<typename BasicJsonType>
  4264. static void construct(BasicJsonType& j, const typename BasicJsonType::object_t& obj)
  4265. {
  4266. j.m_value.destroy(j.m_type);
  4267. j.m_type = value_t::object;
  4268. j.m_value = obj;
  4269. j.set_parents();
  4270. j.assert_invariant();
  4271. }
  4272. template<typename BasicJsonType>
  4273. static void construct(BasicJsonType& j, typename BasicJsonType::object_t&& obj)
  4274. {
  4275. j.m_value.destroy(j.m_type);
  4276. j.m_type = value_t::object;
  4277. j.m_value = std::move(obj);
  4278. j.set_parents();
  4279. j.assert_invariant();
  4280. }
  4281. template < typename BasicJsonType, typename CompatibleObjectType,
  4282. enable_if_t < !std::is_same<CompatibleObjectType, typename BasicJsonType::object_t>::value, int > = 0 >
  4283. static void construct(BasicJsonType& j, const CompatibleObjectType& obj)
  4284. {
  4285. using std::begin;
  4286. using std::end;
  4287. j.m_value.destroy(j.m_type);
  4288. j.m_type = value_t::object;
  4289. j.m_value.object = j.template create<typename BasicJsonType::object_t>(begin(obj), end(obj));
  4290. j.set_parents();
  4291. j.assert_invariant();
  4292. }
  4293. };
  4294. /////////////
  4295. // to_json //
  4296. /////////////
  4297. template<typename BasicJsonType, typename T,
  4298. enable_if_t<std::is_same<T, typename BasicJsonType::boolean_t>::value, int> = 0>
  4299. void to_json(BasicJsonType& j, T b) noexcept
  4300. {
  4301. external_constructor<value_t::boolean>::construct(j, b);
  4302. }
  4303. template<typename BasicJsonType, typename CompatibleString,
  4304. enable_if_t<std::is_constructible<typename BasicJsonType::string_t, CompatibleString>::value, int> = 0>
  4305. void to_json(BasicJsonType& j, const CompatibleString& s)
  4306. {
  4307. external_constructor<value_t::string>::construct(j, s);
  4308. }
  4309. template<typename BasicJsonType>
  4310. void to_json(BasicJsonType& j, typename BasicJsonType::string_t&& s)
  4311. {
  4312. external_constructor<value_t::string>::construct(j, std::move(s));
  4313. }
  4314. template<typename BasicJsonType, typename FloatType,
  4315. enable_if_t<std::is_floating_point<FloatType>::value, int> = 0>
  4316. void to_json(BasicJsonType& j, FloatType val) noexcept
  4317. {
  4318. external_constructor<value_t::number_float>::construct(j, static_cast<typename BasicJsonType::number_float_t>(val));
  4319. }
  4320. template<typename BasicJsonType, typename CompatibleNumberUnsignedType,
  4321. enable_if_t<is_compatible_integer_type<typename BasicJsonType::number_unsigned_t, CompatibleNumberUnsignedType>::value, int> = 0>
  4322. void to_json(BasicJsonType& j, CompatibleNumberUnsignedType val) noexcept
  4323. {
  4324. external_constructor<value_t::number_unsigned>::construct(j, static_cast<typename BasicJsonType::number_unsigned_t>(val));
  4325. }
  4326. template<typename BasicJsonType, typename CompatibleNumberIntegerType,
  4327. enable_if_t<is_compatible_integer_type<typename BasicJsonType::number_integer_t, CompatibleNumberIntegerType>::value, int> = 0>
  4328. void to_json(BasicJsonType& j, CompatibleNumberIntegerType val) noexcept
  4329. {
  4330. external_constructor<value_t::number_integer>::construct(j, static_cast<typename BasicJsonType::number_integer_t>(val));
  4331. }
  4332. template<typename BasicJsonType, typename EnumType,
  4333. enable_if_t<std::is_enum<EnumType>::value, int> = 0>
  4334. void to_json(BasicJsonType& j, EnumType e) noexcept
  4335. {
  4336. using underlying_type = typename std::underlying_type<EnumType>::type;
  4337. external_constructor<value_t::number_integer>::construct(j, static_cast<underlying_type>(e));
  4338. }
  4339. template<typename BasicJsonType>
  4340. void to_json(BasicJsonType& j, const std::vector<bool>& e)
  4341. {
  4342. external_constructor<value_t::array>::construct(j, e);
  4343. }
  4344. template < typename BasicJsonType, typename CompatibleArrayType,
  4345. enable_if_t < is_compatible_array_type<BasicJsonType,
  4346. CompatibleArrayType>::value&&
  4347. !is_compatible_object_type<BasicJsonType, CompatibleArrayType>::value&&
  4348. !is_compatible_string_type<BasicJsonType, CompatibleArrayType>::value&&
  4349. !std::is_same<typename BasicJsonType::binary_t, CompatibleArrayType>::value&&
  4350. !is_basic_json<CompatibleArrayType>::value,
  4351. int > = 0 >
  4352. void to_json(BasicJsonType& j, const CompatibleArrayType& arr)
  4353. {
  4354. external_constructor<value_t::array>::construct(j, arr);
  4355. }
  4356. template<typename BasicJsonType>
  4357. void to_json(BasicJsonType& j, const typename BasicJsonType::binary_t& bin)
  4358. {
  4359. external_constructor<value_t::binary>::construct(j, bin);
  4360. }
  4361. template<typename BasicJsonType, typename T,
  4362. enable_if_t<std::is_convertible<T, BasicJsonType>::value, int> = 0>
  4363. void to_json(BasicJsonType& j, const std::valarray<T>& arr)
  4364. {
  4365. external_constructor<value_t::array>::construct(j, std::move(arr));
  4366. }
  4367. template<typename BasicJsonType>
  4368. void to_json(BasicJsonType& j, typename BasicJsonType::array_t&& arr)
  4369. {
  4370. external_constructor<value_t::array>::construct(j, std::move(arr));
  4371. }
  4372. template < typename BasicJsonType, typename CompatibleObjectType,
  4373. enable_if_t < is_compatible_object_type<BasicJsonType, CompatibleObjectType>::value&& !is_basic_json<CompatibleObjectType>::value, int > = 0 >
  4374. void to_json(BasicJsonType& j, const CompatibleObjectType& obj)
  4375. {
  4376. external_constructor<value_t::object>::construct(j, obj);
  4377. }
  4378. template<typename BasicJsonType>
  4379. void to_json(BasicJsonType& j, typename BasicJsonType::object_t&& obj)
  4380. {
  4381. external_constructor<value_t::object>::construct(j, std::move(obj));
  4382. }
  4383. template <
  4384. typename BasicJsonType, typename T, std::size_t N,
  4385. enable_if_t < !std::is_constructible<typename BasicJsonType::string_t,
  4386. const T(&)[N]>::value, // NOLINT(cppcoreguidelines-avoid-c-arrays,hicpp-avoid-c-arrays,modernize-avoid-c-arrays)
  4387. int > = 0 >
  4388. void to_json(BasicJsonType& j, const T(&arr)[N]) // NOLINT(cppcoreguidelines-avoid-c-arrays,hicpp-avoid-c-arrays,modernize-avoid-c-arrays)
  4389. {
  4390. external_constructor<value_t::array>::construct(j, arr);
  4391. }
  4392. template < typename BasicJsonType, typename T1, typename T2, enable_if_t < std::is_constructible<BasicJsonType, T1>::value&& std::is_constructible<BasicJsonType, T2>::value, int > = 0 >
  4393. void to_json(BasicJsonType& j, const std::pair<T1, T2>& p)
  4394. {
  4395. j = { p.first, p.second };
  4396. }
  4397. // for https://github.com/nlohmann/json/pull/1134
  4398. template<typename BasicJsonType, typename T,
  4399. enable_if_t<std::is_same<T, iteration_proxy_value<typename BasicJsonType::iterator>>::value, int> = 0>
  4400. void to_json(BasicJsonType& j, const T& b)
  4401. {
  4402. j = { {b.key(), b.value()} };
  4403. }
  4404. template<typename BasicJsonType, typename Tuple, std::size_t... Idx>
  4405. void to_json_tuple_impl(BasicJsonType& j, const Tuple& t, index_sequence<Idx...> /*unused*/)
  4406. {
  4407. j = { std::get<Idx>(t)... };
  4408. }
  4409. template<typename BasicJsonType, typename T, enable_if_t<is_constructible_tuple<BasicJsonType, T>::value, int > = 0>
  4410. void to_json(BasicJsonType& j, const T& t)
  4411. {
  4412. to_json_tuple_impl(j, t, make_index_sequence<std::tuple_size<T>::value> {});
  4413. }
  4414. #ifdef JSON_HAS_CPP_17
  4415. template<typename BasicJsonType>
  4416. void to_json(BasicJsonType& j, const std::filesystem::path& p)
  4417. {
  4418. j = p.string();
  4419. }
  4420. #endif
  4421. struct to_json_fn
  4422. {
  4423. template<typename BasicJsonType, typename T>
  4424. auto operator()(BasicJsonType& j, T&& val) const noexcept(noexcept(to_json(j, std::forward<T>(val))))
  4425. -> decltype(to_json(j, std::forward<T>(val)), void())
  4426. {
  4427. return to_json(j, std::forward<T>(val));
  4428. }
  4429. };
  4430. } // namespace detail
  4431. /// namespace to hold default `to_json` function
  4432. /// to see why this is required:
  4433. /// http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2015/n4381.html
  4434. namespace // NOLINT(cert-dcl59-cpp,fuchsia-header-anon-namespaces,google-build-namespaces)
  4435. {
  4436. constexpr const auto& to_json = detail::static_const<detail::to_json_fn>::value; // NOLINT(misc-definitions-in-headers)
  4437. } // namespace
  4438. } // namespace nlohmann
  4439. // #include <nlohmann/detail/meta/identity_tag.hpp>
  4440. // #include <nlohmann/detail/meta/type_traits.hpp>
  4441. namespace nlohmann
  4442. {
  4443. template<typename ValueType, typename>
  4444. struct adl_serializer
  4445. {
  4446. /*!
  4447. @brief convert a JSON value to any value type
  4448. This function is usually called by the `get()` function of the
  4449. @ref basic_json class (either explicit or via conversion operators).
  4450. @note This function is chosen for default-constructible value types.
  4451. @param[in] j JSON value to read from
  4452. @param[in,out] val value to write to
  4453. */
  4454. template<typename BasicJsonType, typename TargetType = ValueType>
  4455. static auto from_json(BasicJsonType && j, TargetType& val) noexcept(
  4456. noexcept(::nlohmann::from_json(std::forward<BasicJsonType>(j), val)))
  4457. -> decltype(::nlohmann::from_json(std::forward<BasicJsonType>(j), val), void())
  4458. {
  4459. ::nlohmann::from_json(std::forward<BasicJsonType>(j), val);
  4460. }
  4461. /*!
  4462. @brief convert a JSON value to any value type
  4463. This function is usually called by the `get()` function of the
  4464. @ref basic_json class (either explicit or via conversion operators).
  4465. @note This function is chosen for value types which are not default-constructible.
  4466. @param[in] j JSON value to read from
  4467. @return copy of the JSON value, converted to @a ValueType
  4468. */
  4469. template<typename BasicJsonType, typename TargetType = ValueType>
  4470. static auto from_json(BasicJsonType && j) noexcept(
  4471. noexcept(::nlohmann::from_json(std::forward<BasicJsonType>(j), detail::identity_tag<TargetType> {})))
  4472. -> decltype(::nlohmann::from_json(std::forward<BasicJsonType>(j), detail::identity_tag<TargetType> {}))
  4473. {
  4474. return ::nlohmann::from_json(std::forward<BasicJsonType>(j), detail::identity_tag<TargetType> {});
  4475. }
  4476. /*!
  4477. @brief convert any value type to a JSON value
  4478. This function is usually called by the constructors of the @ref basic_json
  4479. class.
  4480. @param[in,out] j JSON value to write to
  4481. @param[in] val value to read from
  4482. */
  4483. template<typename BasicJsonType, typename TargetType = ValueType>
  4484. static auto to_json(BasicJsonType& j, TargetType && val) noexcept(
  4485. noexcept(::nlohmann::to_json(j, std::forward<TargetType>(val))))
  4486. -> decltype(::nlohmann::to_json(j, std::forward<TargetType>(val)), void())
  4487. {
  4488. ::nlohmann::to_json(j, std::forward<TargetType>(val));
  4489. }
  4490. };
  4491. } // namespace nlohmann
  4492. // #include <nlohmann/byte_container_with_subtype.hpp>
  4493. #include <cstdint> // uint8_t, uint64_t
  4494. #include <tuple> // tie
  4495. #include <utility> // move
  4496. namespace nlohmann
  4497. {
  4498. /*!
  4499. @brief an internal type for a backed binary type
  4500. This type extends the template parameter @a BinaryType provided to `basic_json`
  4501. with a subtype used by BSON and MessagePack. This type exists so that the user
  4502. does not have to specify a type themselves with a specific naming scheme in
  4503. order to override the binary type.
  4504. @tparam BinaryType container to store bytes (`std::vector<std::uint8_t>` by
  4505. default)
  4506. @since version 3.8.0; changed type of subtypes to std::uint64_t in 3.10.0.
  4507. */
  4508. template<typename BinaryType>
  4509. class byte_container_with_subtype : public BinaryType
  4510. {
  4511. public:
  4512. /// the type of the underlying container
  4513. using container_type = BinaryType;
  4514. /// the type of the subtype
  4515. using subtype_type = std::uint64_t;
  4516. byte_container_with_subtype() noexcept(noexcept(container_type()))
  4517. : container_type()
  4518. {}
  4519. byte_container_with_subtype(const container_type& b) noexcept(noexcept(container_type(b)))
  4520. : container_type(b)
  4521. {}
  4522. byte_container_with_subtype(container_type&& b) noexcept(noexcept(container_type(std::move(b))))
  4523. : container_type(std::move(b))
  4524. {}
  4525. byte_container_with_subtype(const container_type& b, subtype_type subtype_) noexcept(noexcept(container_type(b)))
  4526. : container_type(b)
  4527. , m_subtype(subtype_)
  4528. , m_has_subtype(true)
  4529. {}
  4530. byte_container_with_subtype(container_type&& b, subtype_type subtype_) noexcept(noexcept(container_type(std::move(b))))
  4531. : container_type(std::move(b))
  4532. , m_subtype(subtype_)
  4533. , m_has_subtype(true)
  4534. {}
  4535. bool operator==(const byte_container_with_subtype& rhs) const
  4536. {
  4537. return std::tie(static_cast<const BinaryType&>(*this), m_subtype, m_has_subtype) ==
  4538. std::tie(static_cast<const BinaryType&>(rhs), rhs.m_subtype, rhs.m_has_subtype);
  4539. }
  4540. bool operator!=(const byte_container_with_subtype& rhs) const
  4541. {
  4542. return !(rhs == *this);
  4543. }
  4544. /*!
  4545. @brief sets the binary subtype
  4546. Sets the binary subtype of the value, also flags a binary JSON value as
  4547. having a subtype, which has implications for serialization.
  4548. @complexity Constant.
  4549. @exceptionsafety No-throw guarantee: this member function never throws
  4550. exceptions.
  4551. @sa see @ref subtype() -- return the binary subtype
  4552. @sa see @ref clear_subtype() -- clears the binary subtype
  4553. @sa see @ref has_subtype() -- returns whether or not the binary value has a
  4554. subtype
  4555. @since version 3.8.0
  4556. */
  4557. void set_subtype(subtype_type subtype_) noexcept
  4558. {
  4559. m_subtype = subtype_;
  4560. m_has_subtype = true;
  4561. }
  4562. /*!
  4563. @brief return the binary subtype
  4564. Returns the numerical subtype of the value if it has a subtype. If it does
  4565. not have a subtype, this function will return subtype_type(-1) as a sentinel
  4566. value.
  4567. @return the numerical subtype of the binary value
  4568. @complexity Constant.
  4569. @exceptionsafety No-throw guarantee: this member function never throws
  4570. exceptions.
  4571. @sa see @ref set_subtype() -- sets the binary subtype
  4572. @sa see @ref clear_subtype() -- clears the binary subtype
  4573. @sa see @ref has_subtype() -- returns whether or not the binary value has a
  4574. subtype
  4575. @since version 3.8.0; fixed return value to properly return
  4576. subtype_type(-1) as documented in version 3.10.0
  4577. */
  4578. constexpr subtype_type subtype() const noexcept
  4579. {
  4580. return m_has_subtype ? m_subtype : subtype_type(-1);
  4581. }
  4582. /*!
  4583. @brief return whether the value has a subtype
  4584. @return whether the value has a subtype
  4585. @complexity Constant.
  4586. @exceptionsafety No-throw guarantee: this member function never throws
  4587. exceptions.
  4588. @sa see @ref subtype() -- return the binary subtype
  4589. @sa see @ref set_subtype() -- sets the binary subtype
  4590. @sa see @ref clear_subtype() -- clears the binary subtype
  4591. @since version 3.8.0
  4592. */
  4593. constexpr bool has_subtype() const noexcept
  4594. {
  4595. return m_has_subtype;
  4596. }
  4597. /*!
  4598. @brief clears the binary subtype
  4599. Clears the binary subtype and flags the value as not having a subtype, which
  4600. has implications for serialization; for instance MessagePack will prefer the
  4601. bin family over the ext family.
  4602. @complexity Constant.
  4603. @exceptionsafety No-throw guarantee: this member function never throws
  4604. exceptions.
  4605. @sa see @ref subtype() -- return the binary subtype
  4606. @sa see @ref set_subtype() -- sets the binary subtype
  4607. @sa see @ref has_subtype() -- returns whether or not the binary value has a
  4608. subtype
  4609. @since version 3.8.0
  4610. */
  4611. void clear_subtype() noexcept
  4612. {
  4613. m_subtype = 0;
  4614. m_has_subtype = false;
  4615. }
  4616. private:
  4617. subtype_type m_subtype = 0;
  4618. bool m_has_subtype = false;
  4619. };
  4620. } // namespace nlohmann
  4621. // #include <nlohmann/detail/conversions/from_json.hpp>
  4622. // #include <nlohmann/detail/conversions/to_json.hpp>
  4623. // #include <nlohmann/detail/exceptions.hpp>
  4624. // #include <nlohmann/detail/hash.hpp>
  4625. #include <cstdint> // uint8_t
  4626. #include <cstddef> // size_t
  4627. #include <functional> // hash
  4628. // #include <nlohmann/detail/macro_scope.hpp>
  4629. // #include <nlohmann/detail/value_t.hpp>
  4630. namespace nlohmann
  4631. {
  4632. namespace detail
  4633. {
  4634. // boost::hash_combine
  4635. inline std::size_t combine(std::size_t seed, std::size_t h) noexcept
  4636. {
  4637. seed ^= h + 0x9e3779b9 + (seed << 6U) + (seed >> 2U);
  4638. return seed;
  4639. }
  4640. /*!
  4641. @brief hash a JSON value
  4642. The hash function tries to rely on std::hash where possible. Furthermore, the
  4643. type of the JSON value is taken into account to have different hash values for
  4644. null, 0, 0U, and false, etc.
  4645. @tparam BasicJsonType basic_json specialization
  4646. @param j JSON value to hash
  4647. @return hash value of j
  4648. */
  4649. template<typename BasicJsonType>
  4650. std::size_t hash(const BasicJsonType& j)
  4651. {
  4652. using string_t = typename BasicJsonType::string_t;
  4653. using number_integer_t = typename BasicJsonType::number_integer_t;
  4654. using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
  4655. using number_float_t = typename BasicJsonType::number_float_t;
  4656. const auto type = static_cast<std::size_t>(j.type());
  4657. switch (j.type())
  4658. {
  4659. case BasicJsonType::value_t::null:
  4660. case BasicJsonType::value_t::discarded:
  4661. {
  4662. return combine(type, 0);
  4663. }
  4664. case BasicJsonType::value_t::object:
  4665. {
  4666. auto seed = combine(type, j.size());
  4667. for (const auto& element : j.items())
  4668. {
  4669. const auto h = std::hash<string_t> {}(element.key());
  4670. seed = combine(seed, h);
  4671. seed = combine(seed, hash(element.value()));
  4672. }
  4673. return seed;
  4674. }
  4675. case BasicJsonType::value_t::array:
  4676. {
  4677. auto seed = combine(type, j.size());
  4678. for (const auto& element : j)
  4679. {
  4680. seed = combine(seed, hash(element));
  4681. }
  4682. return seed;
  4683. }
  4684. case BasicJsonType::value_t::string:
  4685. {
  4686. const auto h = std::hash<string_t> {}(j.template get_ref<const string_t&>());
  4687. return combine(type, h);
  4688. }
  4689. case BasicJsonType::value_t::boolean:
  4690. {
  4691. const auto h = std::hash<bool> {}(j.template get<bool>());
  4692. return combine(type, h);
  4693. }
  4694. case BasicJsonType::value_t::number_integer:
  4695. {
  4696. const auto h = std::hash<number_integer_t> {}(j.template get<number_integer_t>());
  4697. return combine(type, h);
  4698. }
  4699. case BasicJsonType::value_t::number_unsigned:
  4700. {
  4701. const auto h = std::hash<number_unsigned_t> {}(j.template get<number_unsigned_t>());
  4702. return combine(type, h);
  4703. }
  4704. case BasicJsonType::value_t::number_float:
  4705. {
  4706. const auto h = std::hash<number_float_t> {}(j.template get<number_float_t>());
  4707. return combine(type, h);
  4708. }
  4709. case BasicJsonType::value_t::binary:
  4710. {
  4711. auto seed = combine(type, j.get_binary().size());
  4712. const auto h = std::hash<bool> {}(j.get_binary().has_subtype());
  4713. seed = combine(seed, h);
  4714. seed = combine(seed, static_cast<std::size_t>(j.get_binary().subtype()));
  4715. for (const auto byte : j.get_binary())
  4716. {
  4717. seed = combine(seed, std::hash<std::uint8_t> {}(byte));
  4718. }
  4719. return seed;
  4720. }
  4721. default: // LCOV_EXCL_LINE
  4722. JSON_ASSERT(false); // NOLINT(cert-dcl03-c,hicpp-static-assert,misc-static-assert) LCOV_EXCL_LINE
  4723. return 0; // LCOV_EXCL_LINE
  4724. }
  4725. }
  4726. } // namespace detail
  4727. } // namespace nlohmann
  4728. // #include <nlohmann/detail/input/binary_reader.hpp>
  4729. #include <algorithm> // generate_n
  4730. #include <array> // array
  4731. #include <cmath> // ldexp
  4732. #include <cstddef> // size_t
  4733. #include <cstdint> // uint8_t, uint16_t, uint32_t, uint64_t
  4734. #include <cstdio> // snprintf
  4735. #include <cstring> // memcpy
  4736. #include <iterator> // back_inserter
  4737. #include <limits> // numeric_limits
  4738. #include <string> // char_traits, string
  4739. #include <utility> // make_pair, move
  4740. #include <vector> // vector
  4741. // #include <nlohmann/detail/exceptions.hpp>
  4742. // #include <nlohmann/detail/input/input_adapters.hpp>
  4743. #include <array> // array
  4744. #include <cstddef> // size_t
  4745. #include <cstring> // strlen
  4746. #include <iterator> // begin, end, iterator_traits, random_access_iterator_tag, distance, next
  4747. #include <memory> // shared_ptr, make_shared, addressof
  4748. #include <numeric> // accumulate
  4749. #include <string> // string, char_traits
  4750. #include <type_traits> // enable_if, is_base_of, is_pointer, is_integral, remove_pointer
  4751. #include <utility> // pair, declval
  4752. #ifndef JSON_NO_IO
  4753. #include <cstdio> // FILE *
  4754. #include <istream> // istream
  4755. #endif // JSON_NO_IO
  4756. // #include <nlohmann/detail/iterators/iterator_traits.hpp>
  4757. // #include <nlohmann/detail/macro_scope.hpp>
  4758. namespace nlohmann
  4759. {
  4760. namespace detail
  4761. {
  4762. /// the supported input formats
  4763. enum class input_format_t { json, cbor, msgpack, ubjson, bson };
  4764. ////////////////////
  4765. // input adapters //
  4766. ////////////////////
  4767. #ifndef JSON_NO_IO
  4768. /*!
  4769. Input adapter for stdio file access. This adapter read only 1 byte and do not use any
  4770. buffer. This adapter is a very low level adapter.
  4771. */
  4772. class file_input_adapter
  4773. {
  4774. public:
  4775. using char_type = char;
  4776. JSON_HEDLEY_NON_NULL(2)
  4777. explicit file_input_adapter(std::FILE* f) noexcept
  4778. : m_file(f)
  4779. {}
  4780. // make class move-only
  4781. file_input_adapter(const file_input_adapter&) = delete;
  4782. file_input_adapter(file_input_adapter&&) noexcept = default;
  4783. file_input_adapter& operator=(const file_input_adapter&) = delete;
  4784. file_input_adapter& operator=(file_input_adapter&&) = delete;
  4785. ~file_input_adapter() = default;
  4786. std::char_traits<char>::int_type get_character() noexcept
  4787. {
  4788. return std::fgetc(m_file);
  4789. }
  4790. private:
  4791. /// the file pointer to read from
  4792. std::FILE* m_file;
  4793. };
  4794. /*!
  4795. Input adapter for a (caching) istream. Ignores a UFT Byte Order Mark at
  4796. beginning of input. Does not support changing the underlying std::streambuf
  4797. in mid-input. Maintains underlying std::istream and std::streambuf to support
  4798. subsequent use of standard std::istream operations to process any input
  4799. characters following those used in parsing the JSON input. Clears the
  4800. std::istream flags; any input errors (e.g., EOF) will be detected by the first
  4801. subsequent call for input from the std::istream.
  4802. */
  4803. class input_stream_adapter
  4804. {
  4805. public:
  4806. using char_type = char;
  4807. ~input_stream_adapter()
  4808. {
  4809. // clear stream flags; we use underlying streambuf I/O, do not
  4810. // maintain ifstream flags, except eof
  4811. if (is != nullptr)
  4812. {
  4813. is->clear(is->rdstate() & std::ios::eofbit);
  4814. }
  4815. }
  4816. explicit input_stream_adapter(std::istream& i)
  4817. : is(&i), sb(i.rdbuf())
  4818. {}
  4819. // delete because of pointer members
  4820. input_stream_adapter(const input_stream_adapter&) = delete;
  4821. input_stream_adapter& operator=(input_stream_adapter&) = delete;
  4822. input_stream_adapter& operator=(input_stream_adapter&&) = delete;
  4823. input_stream_adapter(input_stream_adapter&& rhs) noexcept
  4824. : is(rhs.is), sb(rhs.sb)
  4825. {
  4826. rhs.is = nullptr;
  4827. rhs.sb = nullptr;
  4828. }
  4829. // std::istream/std::streambuf use std::char_traits<char>::to_int_type, to
  4830. // ensure that std::char_traits<char>::eof() and the character 0xFF do not
  4831. // end up as the same value, eg. 0xFFFFFFFF.
  4832. std::char_traits<char>::int_type get_character()
  4833. {
  4834. auto res = sb->sbumpc();
  4835. // set eof manually, as we don't use the istream interface.
  4836. if (JSON_HEDLEY_UNLIKELY(res == std::char_traits<char>::eof()))
  4837. {
  4838. is->clear(is->rdstate() | std::ios::eofbit);
  4839. }
  4840. return res;
  4841. }
  4842. private:
  4843. /// the associated input stream
  4844. std::istream* is = nullptr;
  4845. std::streambuf* sb = nullptr;
  4846. };
  4847. #endif // JSON_NO_IO
  4848. // General-purpose iterator-based adapter. It might not be as fast as
  4849. // theoretically possible for some containers, but it is extremely versatile.
  4850. template<typename IteratorType>
  4851. class iterator_input_adapter
  4852. {
  4853. public:
  4854. using char_type = typename std::iterator_traits<IteratorType>::value_type;
  4855. iterator_input_adapter(IteratorType first, IteratorType last)
  4856. : current(std::move(first)), end(std::move(last))
  4857. {}
  4858. typename std::char_traits<char_type>::int_type get_character()
  4859. {
  4860. if (JSON_HEDLEY_LIKELY(current != end))
  4861. {
  4862. auto result = std::char_traits<char_type>::to_int_type(*current);
  4863. std::advance(current, 1);
  4864. return result;
  4865. }
  4866. return std::char_traits<char_type>::eof();
  4867. }
  4868. private:
  4869. IteratorType current;
  4870. IteratorType end;
  4871. template<typename BaseInputAdapter, size_t T>
  4872. friend struct wide_string_input_helper;
  4873. bool empty() const
  4874. {
  4875. return current == end;
  4876. }
  4877. };
  4878. template<typename BaseInputAdapter, size_t T>
  4879. struct wide_string_input_helper;
  4880. template<typename BaseInputAdapter>
  4881. struct wide_string_input_helper<BaseInputAdapter, 4>
  4882. {
  4883. // UTF-32
  4884. static void fill_buffer(BaseInputAdapter& input,
  4885. std::array<std::char_traits<char>::int_type, 4>& utf8_bytes,
  4886. size_t& utf8_bytes_index,
  4887. size_t& utf8_bytes_filled)
  4888. {
  4889. utf8_bytes_index = 0;
  4890. if (JSON_HEDLEY_UNLIKELY(input.empty()))
  4891. {
  4892. utf8_bytes[0] = std::char_traits<char>::eof();
  4893. utf8_bytes_filled = 1;
  4894. }
  4895. else
  4896. {
  4897. // get the current character
  4898. const auto wc = input.get_character();
  4899. // UTF-32 to UTF-8 encoding
  4900. if (wc < 0x80)
  4901. {
  4902. utf8_bytes[0] = static_cast<std::char_traits<char>::int_type>(wc);
  4903. utf8_bytes_filled = 1;
  4904. }
  4905. else if (wc <= 0x7FF)
  4906. {
  4907. utf8_bytes[0] = static_cast<std::char_traits<char>::int_type>(0xC0u | ((static_cast<unsigned int>(wc) >> 6u) & 0x1Fu));
  4908. utf8_bytes[1] = static_cast<std::char_traits<char>::int_type>(0x80u | (static_cast<unsigned int>(wc) & 0x3Fu));
  4909. utf8_bytes_filled = 2;
  4910. }
  4911. else if (wc <= 0xFFFF)
  4912. {
  4913. utf8_bytes[0] = static_cast<std::char_traits<char>::int_type>(0xE0u | ((static_cast<unsigned int>(wc) >> 12u) & 0x0Fu));
  4914. utf8_bytes[1] = static_cast<std::char_traits<char>::int_type>(0x80u | ((static_cast<unsigned int>(wc) >> 6u) & 0x3Fu));
  4915. utf8_bytes[2] = static_cast<std::char_traits<char>::int_type>(0x80u | (static_cast<unsigned int>(wc) & 0x3Fu));
  4916. utf8_bytes_filled = 3;
  4917. }
  4918. else if (wc <= 0x10FFFF)
  4919. {
  4920. utf8_bytes[0] = static_cast<std::char_traits<char>::int_type>(0xF0u | ((static_cast<unsigned int>(wc) >> 18u) & 0x07u));
  4921. utf8_bytes[1] = static_cast<std::char_traits<char>::int_type>(0x80u | ((static_cast<unsigned int>(wc) >> 12u) & 0x3Fu));
  4922. utf8_bytes[2] = static_cast<std::char_traits<char>::int_type>(0x80u | ((static_cast<unsigned int>(wc) >> 6u) & 0x3Fu));
  4923. utf8_bytes[3] = static_cast<std::char_traits<char>::int_type>(0x80u | (static_cast<unsigned int>(wc) & 0x3Fu));
  4924. utf8_bytes_filled = 4;
  4925. }
  4926. else
  4927. {
  4928. // unknown character
  4929. utf8_bytes[0] = static_cast<std::char_traits<char>::int_type>(wc);
  4930. utf8_bytes_filled = 1;
  4931. }
  4932. }
  4933. }
  4934. };
  4935. template<typename BaseInputAdapter>
  4936. struct wide_string_input_helper<BaseInputAdapter, 2>
  4937. {
  4938. // UTF-16
  4939. static void fill_buffer(BaseInputAdapter& input,
  4940. std::array<std::char_traits<char>::int_type, 4>& utf8_bytes,
  4941. size_t& utf8_bytes_index,
  4942. size_t& utf8_bytes_filled)
  4943. {
  4944. utf8_bytes_index = 0;
  4945. if (JSON_HEDLEY_UNLIKELY(input.empty()))
  4946. {
  4947. utf8_bytes[0] = std::char_traits<char>::eof();
  4948. utf8_bytes_filled = 1;
  4949. }
  4950. else
  4951. {
  4952. // get the current character
  4953. const auto wc = input.get_character();
  4954. // UTF-16 to UTF-8 encoding
  4955. if (wc < 0x80)
  4956. {
  4957. utf8_bytes[0] = static_cast<std::char_traits<char>::int_type>(wc);
  4958. utf8_bytes_filled = 1;
  4959. }
  4960. else if (wc <= 0x7FF)
  4961. {
  4962. utf8_bytes[0] = static_cast<std::char_traits<char>::int_type>(0xC0u | ((static_cast<unsigned int>(wc) >> 6u)));
  4963. utf8_bytes[1] = static_cast<std::char_traits<char>::int_type>(0x80u | (static_cast<unsigned int>(wc) & 0x3Fu));
  4964. utf8_bytes_filled = 2;
  4965. }
  4966. else if (0xD800 > wc || wc >= 0xE000)
  4967. {
  4968. utf8_bytes[0] = static_cast<std::char_traits<char>::int_type>(0xE0u | ((static_cast<unsigned int>(wc) >> 12u)));
  4969. utf8_bytes[1] = static_cast<std::char_traits<char>::int_type>(0x80u | ((static_cast<unsigned int>(wc) >> 6u) & 0x3Fu));
  4970. utf8_bytes[2] = static_cast<std::char_traits<char>::int_type>(0x80u | (static_cast<unsigned int>(wc) & 0x3Fu));
  4971. utf8_bytes_filled = 3;
  4972. }
  4973. else
  4974. {
  4975. if (JSON_HEDLEY_UNLIKELY(!input.empty()))
  4976. {
  4977. const auto wc2 = static_cast<unsigned int>(input.get_character());
  4978. const auto charcode = 0x10000u + (((static_cast<unsigned int>(wc) & 0x3FFu) << 10u) | (wc2 & 0x3FFu));
  4979. utf8_bytes[0] = static_cast<std::char_traits<char>::int_type>(0xF0u | (charcode >> 18u));
  4980. utf8_bytes[1] = static_cast<std::char_traits<char>::int_type>(0x80u | ((charcode >> 12u) & 0x3Fu));
  4981. utf8_bytes[2] = static_cast<std::char_traits<char>::int_type>(0x80u | ((charcode >> 6u) & 0x3Fu));
  4982. utf8_bytes[3] = static_cast<std::char_traits<char>::int_type>(0x80u | (charcode & 0x3Fu));
  4983. utf8_bytes_filled = 4;
  4984. }
  4985. else
  4986. {
  4987. utf8_bytes[0] = static_cast<std::char_traits<char>::int_type>(wc);
  4988. utf8_bytes_filled = 1;
  4989. }
  4990. }
  4991. }
  4992. }
  4993. };
  4994. // Wraps another input apdater to convert wide character types into individual bytes.
  4995. template<typename BaseInputAdapter, typename WideCharType>
  4996. class wide_string_input_adapter
  4997. {
  4998. public:
  4999. using char_type = char;
  5000. wide_string_input_adapter(BaseInputAdapter base)
  5001. : base_adapter(base) {}
  5002. typename std::char_traits<char>::int_type get_character() noexcept
  5003. {
  5004. // check if buffer needs to be filled
  5005. if (utf8_bytes_index == utf8_bytes_filled)
  5006. {
  5007. fill_buffer<sizeof(WideCharType)>();
  5008. JSON_ASSERT(utf8_bytes_filled > 0);
  5009. JSON_ASSERT(utf8_bytes_index == 0);
  5010. }
  5011. // use buffer
  5012. JSON_ASSERT(utf8_bytes_filled > 0);
  5013. JSON_ASSERT(utf8_bytes_index < utf8_bytes_filled);
  5014. return utf8_bytes[utf8_bytes_index++];
  5015. }
  5016. private:
  5017. BaseInputAdapter base_adapter;
  5018. template<size_t T>
  5019. void fill_buffer()
  5020. {
  5021. wide_string_input_helper<BaseInputAdapter, T>::fill_buffer(base_adapter, utf8_bytes, utf8_bytes_index, utf8_bytes_filled);
  5022. }
  5023. /// a buffer for UTF-8 bytes
  5024. std::array<std::char_traits<char>::int_type, 4> utf8_bytes = {{0, 0, 0, 0}};
  5025. /// index to the utf8_codes array for the next valid byte
  5026. std::size_t utf8_bytes_index = 0;
  5027. /// number of valid bytes in the utf8_codes array
  5028. std::size_t utf8_bytes_filled = 0;
  5029. };
  5030. template<typename IteratorType, typename Enable = void>
  5031. struct iterator_input_adapter_factory
  5032. {
  5033. using iterator_type = IteratorType;
  5034. using char_type = typename std::iterator_traits<iterator_type>::value_type;
  5035. using adapter_type = iterator_input_adapter<iterator_type>;
  5036. static adapter_type create(IteratorType first, IteratorType last)
  5037. {
  5038. return adapter_type(std::move(first), std::move(last));
  5039. }
  5040. };
  5041. template<typename T>
  5042. struct is_iterator_of_multibyte
  5043. {
  5044. using value_type = typename std::iterator_traits<T>::value_type;
  5045. enum
  5046. {
  5047. value = sizeof(value_type) > 1
  5048. };
  5049. };
  5050. template<typename IteratorType>
  5051. struct iterator_input_adapter_factory<IteratorType, enable_if_t<is_iterator_of_multibyte<IteratorType>::value>>
  5052. {
  5053. using iterator_type = IteratorType;
  5054. using char_type = typename std::iterator_traits<iterator_type>::value_type;
  5055. using base_adapter_type = iterator_input_adapter<iterator_type>;
  5056. using adapter_type = wide_string_input_adapter<base_adapter_type, char_type>;
  5057. static adapter_type create(IteratorType first, IteratorType last)
  5058. {
  5059. return adapter_type(base_adapter_type(std::move(first), std::move(last)));
  5060. }
  5061. };
  5062. // General purpose iterator-based input
  5063. template<typename IteratorType>
  5064. typename iterator_input_adapter_factory<IteratorType>::adapter_type input_adapter(IteratorType first, IteratorType last)
  5065. {
  5066. using factory_type = iterator_input_adapter_factory<IteratorType>;
  5067. return factory_type::create(first, last);
  5068. }
  5069. // Convenience shorthand from container to iterator
  5070. // Enables ADL on begin(container) and end(container)
  5071. // Encloses the using declarations in namespace for not to leak them to outside scope
  5072. namespace container_input_adapter_factory_impl
  5073. {
  5074. using std::begin;
  5075. using std::end;
  5076. template<typename ContainerType, typename Enable = void>
  5077. struct container_input_adapter_factory {};
  5078. template<typename ContainerType>
  5079. struct container_input_adapter_factory< ContainerType,
  5080. void_t<decltype(begin(std::declval<ContainerType>()), end(std::declval<ContainerType>()))>>
  5081. {
  5082. using adapter_type = decltype(input_adapter(begin(std::declval<ContainerType>()), end(std::declval<ContainerType>())));
  5083. static adapter_type create(const ContainerType& container)
  5084. {
  5085. return input_adapter(begin(container), end(container));
  5086. }
  5087. };
  5088. } // namespace container_input_adapter_factory_impl
  5089. template<typename ContainerType>
  5090. typename container_input_adapter_factory_impl::container_input_adapter_factory<ContainerType>::adapter_type input_adapter(const ContainerType& container)
  5091. {
  5092. return container_input_adapter_factory_impl::container_input_adapter_factory<ContainerType>::create(container);
  5093. }
  5094. #ifndef JSON_NO_IO
  5095. // Special cases with fast paths
  5096. inline file_input_adapter input_adapter(std::FILE* file)
  5097. {
  5098. return file_input_adapter(file);
  5099. }
  5100. inline input_stream_adapter input_adapter(std::istream& stream)
  5101. {
  5102. return input_stream_adapter(stream);
  5103. }
  5104. inline input_stream_adapter input_adapter(std::istream&& stream)
  5105. {
  5106. return input_stream_adapter(stream);
  5107. }
  5108. #endif // JSON_NO_IO
  5109. using contiguous_bytes_input_adapter = decltype(input_adapter(std::declval<const char*>(), std::declval<const char*>()));
  5110. // Null-delimited strings, and the like.
  5111. template < typename CharT,
  5112. typename std::enable_if <
  5113. std::is_pointer<CharT>::value&&
  5114. !std::is_array<CharT>::value&&
  5115. std::is_integral<typename std::remove_pointer<CharT>::type>::value&&
  5116. sizeof(typename std::remove_pointer<CharT>::type) == 1,
  5117. int >::type = 0 >
  5118. contiguous_bytes_input_adapter input_adapter(CharT b)
  5119. {
  5120. auto length = std::strlen(reinterpret_cast<const char*>(b));
  5121. const auto* ptr = reinterpret_cast<const char*>(b);
  5122. return input_adapter(ptr, ptr + length);
  5123. }
  5124. template<typename T, std::size_t N>
  5125. auto input_adapter(T (&array)[N]) -> decltype(input_adapter(array, array + N)) // NOLINT(cppcoreguidelines-avoid-c-arrays,hicpp-avoid-c-arrays,modernize-avoid-c-arrays)
  5126. {
  5127. return input_adapter(array, array + N);
  5128. }
  5129. // This class only handles inputs of input_buffer_adapter type.
  5130. // It's required so that expressions like {ptr, len} can be implicitely casted
  5131. // to the correct adapter.
  5132. class span_input_adapter
  5133. {
  5134. public:
  5135. template < typename CharT,
  5136. typename std::enable_if <
  5137. std::is_pointer<CharT>::value&&
  5138. std::is_integral<typename std::remove_pointer<CharT>::type>::value&&
  5139. sizeof(typename std::remove_pointer<CharT>::type) == 1,
  5140. int >::type = 0 >
  5141. span_input_adapter(CharT b, std::size_t l)
  5142. : ia(reinterpret_cast<const char*>(b), reinterpret_cast<const char*>(b) + l) {}
  5143. template<class IteratorType,
  5144. typename std::enable_if<
  5145. std::is_same<typename iterator_traits<IteratorType>::iterator_category, std::random_access_iterator_tag>::value,
  5146. int>::type = 0>
  5147. span_input_adapter(IteratorType first, IteratorType last)
  5148. : ia(input_adapter(first, last)) {}
  5149. contiguous_bytes_input_adapter&& get()
  5150. {
  5151. return std::move(ia); // NOLINT(hicpp-move-const-arg,performance-move-const-arg)
  5152. }
  5153. private:
  5154. contiguous_bytes_input_adapter ia;
  5155. };
  5156. } // namespace detail
  5157. } // namespace nlohmann
  5158. // #include <nlohmann/detail/input/json_sax.hpp>
  5159. #include <cstddef>
  5160. #include <string> // string
  5161. #include <utility> // move
  5162. #include <vector> // vector
  5163. // #include <nlohmann/detail/exceptions.hpp>
  5164. // #include <nlohmann/detail/macro_scope.hpp>
  5165. namespace nlohmann
  5166. {
  5167. /*!
  5168. @brief SAX interface
  5169. This class describes the SAX interface used by @ref nlohmann::json::sax_parse.
  5170. Each function is called in different situations while the input is parsed. The
  5171. boolean return value informs the parser whether to continue processing the
  5172. input.
  5173. */
  5174. template<typename BasicJsonType>
  5175. struct json_sax
  5176. {
  5177. using number_integer_t = typename BasicJsonType::number_integer_t;
  5178. using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
  5179. using number_float_t = typename BasicJsonType::number_float_t;
  5180. using string_t = typename BasicJsonType::string_t;
  5181. using binary_t = typename BasicJsonType::binary_t;
  5182. /*!
  5183. @brief a null value was read
  5184. @return whether parsing should proceed
  5185. */
  5186. virtual bool null() = 0;
  5187. /*!
  5188. @brief a boolean value was read
  5189. @param[in] val boolean value
  5190. @return whether parsing should proceed
  5191. */
  5192. virtual bool boolean(bool val) = 0;
  5193. /*!
  5194. @brief an integer number was read
  5195. @param[in] val integer value
  5196. @return whether parsing should proceed
  5197. */
  5198. virtual bool number_integer(number_integer_t val) = 0;
  5199. /*!
  5200. @brief an unsigned integer number was read
  5201. @param[in] val unsigned integer value
  5202. @return whether parsing should proceed
  5203. */
  5204. virtual bool number_unsigned(number_unsigned_t val) = 0;
  5205. /*!
  5206. @brief an floating-point number was read
  5207. @param[in] val floating-point value
  5208. @param[in] s raw token value
  5209. @return whether parsing should proceed
  5210. */
  5211. virtual bool number_float(number_float_t val, const string_t& s) = 0;
  5212. /*!
  5213. @brief a string was read
  5214. @param[in] val string value
  5215. @return whether parsing should proceed
  5216. @note It is safe to move the passed string.
  5217. */
  5218. virtual bool string(string_t& val) = 0;
  5219. /*!
  5220. @brief a binary string was read
  5221. @param[in] val binary value
  5222. @return whether parsing should proceed
  5223. @note It is safe to move the passed binary.
  5224. */
  5225. virtual bool binary(binary_t& val) = 0;
  5226. /*!
  5227. @brief the beginning of an object was read
  5228. @param[in] elements number of object elements or -1 if unknown
  5229. @return whether parsing should proceed
  5230. @note binary formats may report the number of elements
  5231. */
  5232. virtual bool start_object(std::size_t elements) = 0;
  5233. /*!
  5234. @brief an object key was read
  5235. @param[in] val object key
  5236. @return whether parsing should proceed
  5237. @note It is safe to move the passed string.
  5238. */
  5239. virtual bool key(string_t& val) = 0;
  5240. /*!
  5241. @brief the end of an object was read
  5242. @return whether parsing should proceed
  5243. */
  5244. virtual bool end_object() = 0;
  5245. /*!
  5246. @brief the beginning of an array was read
  5247. @param[in] elements number of array elements or -1 if unknown
  5248. @return whether parsing should proceed
  5249. @note binary formats may report the number of elements
  5250. */
  5251. virtual bool start_array(std::size_t elements) = 0;
  5252. /*!
  5253. @brief the end of an array was read
  5254. @return whether parsing should proceed
  5255. */
  5256. virtual bool end_array() = 0;
  5257. /*!
  5258. @brief a parse error occurred
  5259. @param[in] position the position in the input where the error occurs
  5260. @param[in] last_token the last read token
  5261. @param[in] ex an exception object describing the error
  5262. @return whether parsing should proceed (must return false)
  5263. */
  5264. virtual bool parse_error(std::size_t position,
  5265. const std::string& last_token,
  5266. const detail::exception& ex) = 0;
  5267. json_sax() = default;
  5268. json_sax(const json_sax&) = default;
  5269. json_sax(json_sax&&) noexcept = default;
  5270. json_sax& operator=(const json_sax&) = default;
  5271. json_sax& operator=(json_sax&&) noexcept = default;
  5272. virtual ~json_sax() = default;
  5273. };
  5274. namespace detail
  5275. {
  5276. /*!
  5277. @brief SAX implementation to create a JSON value from SAX events
  5278. This class implements the @ref json_sax interface and processes the SAX events
  5279. to create a JSON value which makes it basically a DOM parser. The structure or
  5280. hierarchy of the JSON value is managed by the stack `ref_stack` which contains
  5281. a pointer to the respective array or object for each recursion depth.
  5282. After successful parsing, the value that is passed by reference to the
  5283. constructor contains the parsed value.
  5284. @tparam BasicJsonType the JSON type
  5285. */
  5286. template<typename BasicJsonType>
  5287. class json_sax_dom_parser
  5288. {
  5289. public:
  5290. using number_integer_t = typename BasicJsonType::number_integer_t;
  5291. using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
  5292. using number_float_t = typename BasicJsonType::number_float_t;
  5293. using string_t = typename BasicJsonType::string_t;
  5294. using binary_t = typename BasicJsonType::binary_t;
  5295. /*!
  5296. @param[in,out] r reference to a JSON value that is manipulated while
  5297. parsing
  5298. @param[in] allow_exceptions_ whether parse errors yield exceptions
  5299. */
  5300. explicit json_sax_dom_parser(BasicJsonType& r, const bool allow_exceptions_ = true)
  5301. : root(r), allow_exceptions(allow_exceptions_)
  5302. {}
  5303. // make class move-only
  5304. json_sax_dom_parser(const json_sax_dom_parser&) = delete;
  5305. json_sax_dom_parser(json_sax_dom_parser&&) = default; // NOLINT(hicpp-noexcept-move,performance-noexcept-move-constructor)
  5306. json_sax_dom_parser& operator=(const json_sax_dom_parser&) = delete;
  5307. json_sax_dom_parser& operator=(json_sax_dom_parser&&) = default; // NOLINT(hicpp-noexcept-move,performance-noexcept-move-constructor)
  5308. ~json_sax_dom_parser() = default;
  5309. bool null()
  5310. {
  5311. handle_value(nullptr);
  5312. return true;
  5313. }
  5314. bool boolean(bool val)
  5315. {
  5316. handle_value(val);
  5317. return true;
  5318. }
  5319. bool number_integer(number_integer_t val)
  5320. {
  5321. handle_value(val);
  5322. return true;
  5323. }
  5324. bool number_unsigned(number_unsigned_t val)
  5325. {
  5326. handle_value(val);
  5327. return true;
  5328. }
  5329. bool number_float(number_float_t val, const string_t& /*unused*/)
  5330. {
  5331. handle_value(val);
  5332. return true;
  5333. }
  5334. bool string(string_t& val)
  5335. {
  5336. handle_value(val);
  5337. return true;
  5338. }
  5339. bool binary(binary_t& val)
  5340. {
  5341. handle_value(std::move(val));
  5342. return true;
  5343. }
  5344. bool start_object(std::size_t len)
  5345. {
  5346. ref_stack.push_back(handle_value(BasicJsonType::value_t::object));
  5347. if (JSON_HEDLEY_UNLIKELY(len != std::size_t(-1) && len > ref_stack.back()->max_size()))
  5348. {
  5349. JSON_THROW(out_of_range::create(408, "excessive object size: " + std::to_string(len), *ref_stack.back()));
  5350. }
  5351. return true;
  5352. }
  5353. bool key(string_t& val)
  5354. {
  5355. // add null at given key and store the reference for later
  5356. object_element = &(ref_stack.back()->m_value.object->operator[](val));
  5357. return true;
  5358. }
  5359. bool end_object()
  5360. {
  5361. ref_stack.back()->set_parents();
  5362. ref_stack.pop_back();
  5363. return true;
  5364. }
  5365. bool start_array(std::size_t len)
  5366. {
  5367. ref_stack.push_back(handle_value(BasicJsonType::value_t::array));
  5368. if (JSON_HEDLEY_UNLIKELY(len != std::size_t(-1) && len > ref_stack.back()->max_size()))
  5369. {
  5370. JSON_THROW(out_of_range::create(408, "excessive array size: " + std::to_string(len), *ref_stack.back()));
  5371. }
  5372. return true;
  5373. }
  5374. bool end_array()
  5375. {
  5376. ref_stack.back()->set_parents();
  5377. ref_stack.pop_back();
  5378. return true;
  5379. }
  5380. template<class Exception>
  5381. bool parse_error(std::size_t /*unused*/, const std::string& /*unused*/,
  5382. const Exception& ex)
  5383. {
  5384. errored = true;
  5385. static_cast<void>(ex);
  5386. if (allow_exceptions)
  5387. {
  5388. JSON_THROW(ex);
  5389. }
  5390. return false;
  5391. }
  5392. constexpr bool is_errored() const
  5393. {
  5394. return errored;
  5395. }
  5396. private:
  5397. /*!
  5398. @invariant If the ref stack is empty, then the passed value will be the new
  5399. root.
  5400. @invariant If the ref stack contains a value, then it is an array or an
  5401. object to which we can add elements
  5402. */
  5403. template<typename Value>
  5404. JSON_HEDLEY_RETURNS_NON_NULL
  5405. BasicJsonType* handle_value(Value&& v)
  5406. {
  5407. if (ref_stack.empty())
  5408. {
  5409. root = BasicJsonType(std::forward<Value>(v));
  5410. return &root;
  5411. }
  5412. JSON_ASSERT(ref_stack.back()->is_array() || ref_stack.back()->is_object());
  5413. if (ref_stack.back()->is_array())
  5414. {
  5415. ref_stack.back()->m_value.array->emplace_back(std::forward<Value>(v));
  5416. return &(ref_stack.back()->m_value.array->back());
  5417. }
  5418. JSON_ASSERT(ref_stack.back()->is_object());
  5419. JSON_ASSERT(object_element);
  5420. *object_element = BasicJsonType(std::forward<Value>(v));
  5421. return object_element;
  5422. }
  5423. /// the parsed JSON value
  5424. BasicJsonType& root;
  5425. /// stack to model hierarchy of values
  5426. std::vector<BasicJsonType*> ref_stack {};
  5427. /// helper to hold the reference for the next object element
  5428. BasicJsonType* object_element = nullptr;
  5429. /// whether a syntax error occurred
  5430. bool errored = false;
  5431. /// whether to throw exceptions in case of errors
  5432. const bool allow_exceptions = true;
  5433. };
  5434. template<typename BasicJsonType>
  5435. class json_sax_dom_callback_parser
  5436. {
  5437. public:
  5438. using number_integer_t = typename BasicJsonType::number_integer_t;
  5439. using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
  5440. using number_float_t = typename BasicJsonType::number_float_t;
  5441. using string_t = typename BasicJsonType::string_t;
  5442. using binary_t = typename BasicJsonType::binary_t;
  5443. using parser_callback_t = typename BasicJsonType::parser_callback_t;
  5444. using parse_event_t = typename BasicJsonType::parse_event_t;
  5445. json_sax_dom_callback_parser(BasicJsonType& r,
  5446. const parser_callback_t cb,
  5447. const bool allow_exceptions_ = true)
  5448. : root(r), callback(cb), allow_exceptions(allow_exceptions_)
  5449. {
  5450. keep_stack.push_back(true);
  5451. }
  5452. // make class move-only
  5453. json_sax_dom_callback_parser(const json_sax_dom_callback_parser&) = delete;
  5454. json_sax_dom_callback_parser(json_sax_dom_callback_parser&&) = default; // NOLINT(hicpp-noexcept-move,performance-noexcept-move-constructor)
  5455. json_sax_dom_callback_parser& operator=(const json_sax_dom_callback_parser&) = delete;
  5456. json_sax_dom_callback_parser& operator=(json_sax_dom_callback_parser&&) = default; // NOLINT(hicpp-noexcept-move,performance-noexcept-move-constructor)
  5457. ~json_sax_dom_callback_parser() = default;
  5458. bool null()
  5459. {
  5460. handle_value(nullptr);
  5461. return true;
  5462. }
  5463. bool boolean(bool val)
  5464. {
  5465. handle_value(val);
  5466. return true;
  5467. }
  5468. bool number_integer(number_integer_t val)
  5469. {
  5470. handle_value(val);
  5471. return true;
  5472. }
  5473. bool number_unsigned(number_unsigned_t val)
  5474. {
  5475. handle_value(val);
  5476. return true;
  5477. }
  5478. bool number_float(number_float_t val, const string_t& /*unused*/)
  5479. {
  5480. handle_value(val);
  5481. return true;
  5482. }
  5483. bool string(string_t& val)
  5484. {
  5485. handle_value(val);
  5486. return true;
  5487. }
  5488. bool binary(binary_t& val)
  5489. {
  5490. handle_value(std::move(val));
  5491. return true;
  5492. }
  5493. bool start_object(std::size_t len)
  5494. {
  5495. // check callback for object start
  5496. const bool keep = callback(static_cast<int>(ref_stack.size()), parse_event_t::object_start, discarded);
  5497. keep_stack.push_back(keep);
  5498. auto val = handle_value(BasicJsonType::value_t::object, true);
  5499. ref_stack.push_back(val.second);
  5500. // check object limit
  5501. if (ref_stack.back() && JSON_HEDLEY_UNLIKELY(len != std::size_t(-1) && len > ref_stack.back()->max_size()))
  5502. {
  5503. JSON_THROW(out_of_range::create(408, "excessive object size: " + std::to_string(len), *ref_stack.back()));
  5504. }
  5505. return true;
  5506. }
  5507. bool key(string_t& val)
  5508. {
  5509. BasicJsonType k = BasicJsonType(val);
  5510. // check callback for key
  5511. const bool keep = callback(static_cast<int>(ref_stack.size()), parse_event_t::key, k);
  5512. key_keep_stack.push_back(keep);
  5513. // add discarded value at given key and store the reference for later
  5514. if (keep && ref_stack.back())
  5515. {
  5516. object_element = &(ref_stack.back()->m_value.object->operator[](val) = discarded);
  5517. }
  5518. return true;
  5519. }
  5520. bool end_object()
  5521. {
  5522. if (ref_stack.back())
  5523. {
  5524. if (!callback(static_cast<int>(ref_stack.size()) - 1, parse_event_t::object_end, *ref_stack.back()))
  5525. {
  5526. // discard object
  5527. *ref_stack.back() = discarded;
  5528. }
  5529. else
  5530. {
  5531. ref_stack.back()->set_parents();
  5532. }
  5533. }
  5534. JSON_ASSERT(!ref_stack.empty());
  5535. JSON_ASSERT(!keep_stack.empty());
  5536. ref_stack.pop_back();
  5537. keep_stack.pop_back();
  5538. if (!ref_stack.empty() && ref_stack.back() && ref_stack.back()->is_structured())
  5539. {
  5540. // remove discarded value
  5541. for (auto it = ref_stack.back()->begin(); it != ref_stack.back()->end(); ++it)
  5542. {
  5543. if (it->is_discarded())
  5544. {
  5545. ref_stack.back()->erase(it);
  5546. break;
  5547. }
  5548. }
  5549. }
  5550. return true;
  5551. }
  5552. bool start_array(std::size_t len)
  5553. {
  5554. const bool keep = callback(static_cast<int>(ref_stack.size()), parse_event_t::array_start, discarded);
  5555. keep_stack.push_back(keep);
  5556. auto val = handle_value(BasicJsonType::value_t::array, true);
  5557. ref_stack.push_back(val.second);
  5558. // check array limit
  5559. if (ref_stack.back() && JSON_HEDLEY_UNLIKELY(len != std::size_t(-1) && len > ref_stack.back()->max_size()))
  5560. {
  5561. JSON_THROW(out_of_range::create(408, "excessive array size: " + std::to_string(len), *ref_stack.back()));
  5562. }
  5563. return true;
  5564. }
  5565. bool end_array()
  5566. {
  5567. bool keep = true;
  5568. if (ref_stack.back())
  5569. {
  5570. keep = callback(static_cast<int>(ref_stack.size()) - 1, parse_event_t::array_end, *ref_stack.back());
  5571. if (keep)
  5572. {
  5573. ref_stack.back()->set_parents();
  5574. }
  5575. else
  5576. {
  5577. // discard array
  5578. *ref_stack.back() = discarded;
  5579. }
  5580. }
  5581. JSON_ASSERT(!ref_stack.empty());
  5582. JSON_ASSERT(!keep_stack.empty());
  5583. ref_stack.pop_back();
  5584. keep_stack.pop_back();
  5585. // remove discarded value
  5586. if (!keep && !ref_stack.empty() && ref_stack.back()->is_array())
  5587. {
  5588. ref_stack.back()->m_value.array->pop_back();
  5589. }
  5590. return true;
  5591. }
  5592. template<class Exception>
  5593. bool parse_error(std::size_t /*unused*/, const std::string& /*unused*/,
  5594. const Exception& ex)
  5595. {
  5596. errored = true;
  5597. static_cast<void>(ex);
  5598. if (allow_exceptions)
  5599. {
  5600. JSON_THROW(ex);
  5601. }
  5602. return false;
  5603. }
  5604. constexpr bool is_errored() const
  5605. {
  5606. return errored;
  5607. }
  5608. private:
  5609. /*!
  5610. @param[in] v value to add to the JSON value we build during parsing
  5611. @param[in] skip_callback whether we should skip calling the callback
  5612. function; this is required after start_array() and
  5613. start_object() SAX events, because otherwise we would call the
  5614. callback function with an empty array or object, respectively.
  5615. @invariant If the ref stack is empty, then the passed value will be the new
  5616. root.
  5617. @invariant If the ref stack contains a value, then it is an array or an
  5618. object to which we can add elements
  5619. @return pair of boolean (whether value should be kept) and pointer (to the
  5620. passed value in the ref_stack hierarchy; nullptr if not kept)
  5621. */
  5622. template<typename Value>
  5623. std::pair<bool, BasicJsonType*> handle_value(Value&& v, const bool skip_callback = false)
  5624. {
  5625. JSON_ASSERT(!keep_stack.empty());
  5626. // do not handle this value if we know it would be added to a discarded
  5627. // container
  5628. if (!keep_stack.back())
  5629. {
  5630. return {false, nullptr};
  5631. }
  5632. // create value
  5633. auto value = BasicJsonType(std::forward<Value>(v));
  5634. // check callback
  5635. const bool keep = skip_callback || callback(static_cast<int>(ref_stack.size()), parse_event_t::value, value);
  5636. // do not handle this value if we just learnt it shall be discarded
  5637. if (!keep)
  5638. {
  5639. return {false, nullptr};
  5640. }
  5641. if (ref_stack.empty())
  5642. {
  5643. root = std::move(value);
  5644. return {true, &root};
  5645. }
  5646. // skip this value if we already decided to skip the parent
  5647. // (https://github.com/nlohmann/json/issues/971#issuecomment-413678360)
  5648. if (!ref_stack.back())
  5649. {
  5650. return {false, nullptr};
  5651. }
  5652. // we now only expect arrays and objects
  5653. JSON_ASSERT(ref_stack.back()->is_array() || ref_stack.back()->is_object());
  5654. // array
  5655. if (ref_stack.back()->is_array())
  5656. {
  5657. ref_stack.back()->m_value.array->emplace_back(std::move(value));
  5658. return {true, &(ref_stack.back()->m_value.array->back())};
  5659. }
  5660. // object
  5661. JSON_ASSERT(ref_stack.back()->is_object());
  5662. // check if we should store an element for the current key
  5663. JSON_ASSERT(!key_keep_stack.empty());
  5664. const bool store_element = key_keep_stack.back();
  5665. key_keep_stack.pop_back();
  5666. if (!store_element)
  5667. {
  5668. return {false, nullptr};
  5669. }
  5670. JSON_ASSERT(object_element);
  5671. *object_element = std::move(value);
  5672. return {true, object_element};
  5673. }
  5674. /// the parsed JSON value
  5675. BasicJsonType& root;
  5676. /// stack to model hierarchy of values
  5677. std::vector<BasicJsonType*> ref_stack {};
  5678. /// stack to manage which values to keep
  5679. std::vector<bool> keep_stack {};
  5680. /// stack to manage which object keys to keep
  5681. std::vector<bool> key_keep_stack {};
  5682. /// helper to hold the reference for the next object element
  5683. BasicJsonType* object_element = nullptr;
  5684. /// whether a syntax error occurred
  5685. bool errored = false;
  5686. /// callback function
  5687. const parser_callback_t callback = nullptr;
  5688. /// whether to throw exceptions in case of errors
  5689. const bool allow_exceptions = true;
  5690. /// a discarded value for the callback
  5691. BasicJsonType discarded = BasicJsonType::value_t::discarded;
  5692. };
  5693. template<typename BasicJsonType>
  5694. class json_sax_acceptor
  5695. {
  5696. public:
  5697. using number_integer_t = typename BasicJsonType::number_integer_t;
  5698. using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
  5699. using number_float_t = typename BasicJsonType::number_float_t;
  5700. using string_t = typename BasicJsonType::string_t;
  5701. using binary_t = typename BasicJsonType::binary_t;
  5702. bool null()
  5703. {
  5704. return true;
  5705. }
  5706. bool boolean(bool /*unused*/)
  5707. {
  5708. return true;
  5709. }
  5710. bool number_integer(number_integer_t /*unused*/)
  5711. {
  5712. return true;
  5713. }
  5714. bool number_unsigned(number_unsigned_t /*unused*/)
  5715. {
  5716. return true;
  5717. }
  5718. bool number_float(number_float_t /*unused*/, const string_t& /*unused*/)
  5719. {
  5720. return true;
  5721. }
  5722. bool string(string_t& /*unused*/)
  5723. {
  5724. return true;
  5725. }
  5726. bool binary(binary_t& /*unused*/)
  5727. {
  5728. return true;
  5729. }
  5730. bool start_object(std::size_t /*unused*/ = std::size_t(-1))
  5731. {
  5732. return true;
  5733. }
  5734. bool key(string_t& /*unused*/)
  5735. {
  5736. return true;
  5737. }
  5738. bool end_object()
  5739. {
  5740. return true;
  5741. }
  5742. bool start_array(std::size_t /*unused*/ = std::size_t(-1))
  5743. {
  5744. return true;
  5745. }
  5746. bool end_array()
  5747. {
  5748. return true;
  5749. }
  5750. bool parse_error(std::size_t /*unused*/, const std::string& /*unused*/, const detail::exception& /*unused*/)
  5751. {
  5752. return false;
  5753. }
  5754. };
  5755. } // namespace detail
  5756. } // namespace nlohmann
  5757. // #include <nlohmann/detail/input/lexer.hpp>
  5758. #include <array> // array
  5759. #include <clocale> // localeconv
  5760. #include <cstddef> // size_t
  5761. #include <cstdio> // snprintf
  5762. #include <cstdlib> // strtof, strtod, strtold, strtoll, strtoull
  5763. #include <initializer_list> // initializer_list
  5764. #include <string> // char_traits, string
  5765. #include <utility> // move
  5766. #include <vector> // vector
  5767. // #include <nlohmann/detail/input/input_adapters.hpp>
  5768. // #include <nlohmann/detail/input/position_t.hpp>
  5769. // #include <nlohmann/detail/macro_scope.hpp>
  5770. namespace nlohmann
  5771. {
  5772. namespace detail
  5773. {
  5774. ///////////
  5775. // lexer //
  5776. ///////////
  5777. template<typename BasicJsonType>
  5778. class lexer_base
  5779. {
  5780. public:
  5781. /// token types for the parser
  5782. enum class token_type
  5783. {
  5784. uninitialized, ///< indicating the scanner is uninitialized
  5785. literal_true, ///< the `true` literal
  5786. literal_false, ///< the `false` literal
  5787. literal_null, ///< the `null` literal
  5788. value_string, ///< a string -- use get_string() for actual value
  5789. value_unsigned, ///< an unsigned integer -- use get_number_unsigned() for actual value
  5790. value_integer, ///< a signed integer -- use get_number_integer() for actual value
  5791. value_float, ///< an floating point number -- use get_number_float() for actual value
  5792. begin_array, ///< the character for array begin `[`
  5793. begin_object, ///< the character for object begin `{`
  5794. end_array, ///< the character for array end `]`
  5795. end_object, ///< the character for object end `}`
  5796. name_separator, ///< the name separator `:`
  5797. value_separator, ///< the value separator `,`
  5798. parse_error, ///< indicating a parse error
  5799. end_of_input, ///< indicating the end of the input buffer
  5800. literal_or_value ///< a literal or the begin of a value (only for diagnostics)
  5801. };
  5802. /// return name of values of type token_type (only used for errors)
  5803. JSON_HEDLEY_RETURNS_NON_NULL
  5804. JSON_HEDLEY_CONST
  5805. static const char* token_type_name(const token_type t) noexcept
  5806. {
  5807. switch (t)
  5808. {
  5809. case token_type::uninitialized:
  5810. return "<uninitialized>";
  5811. case token_type::literal_true:
  5812. return "true literal";
  5813. case token_type::literal_false:
  5814. return "false literal";
  5815. case token_type::literal_null:
  5816. return "null literal";
  5817. case token_type::value_string:
  5818. return "string literal";
  5819. case token_type::value_unsigned:
  5820. case token_type::value_integer:
  5821. case token_type::value_float:
  5822. return "number literal";
  5823. case token_type::begin_array:
  5824. return "'['";
  5825. case token_type::begin_object:
  5826. return "'{'";
  5827. case token_type::end_array:
  5828. return "']'";
  5829. case token_type::end_object:
  5830. return "'}'";
  5831. case token_type::name_separator:
  5832. return "':'";
  5833. case token_type::value_separator:
  5834. return "','";
  5835. case token_type::parse_error:
  5836. return "<parse error>";
  5837. case token_type::end_of_input:
  5838. return "end of input";
  5839. case token_type::literal_or_value:
  5840. return "'[', '{', or a literal";
  5841. // LCOV_EXCL_START
  5842. default: // catch non-enum values
  5843. return "unknown token";
  5844. // LCOV_EXCL_STOP
  5845. }
  5846. }
  5847. };
  5848. /*!
  5849. @brief lexical analysis
  5850. This class organizes the lexical analysis during JSON deserialization.
  5851. */
  5852. template<typename BasicJsonType, typename InputAdapterType>
  5853. class lexer : public lexer_base<BasicJsonType>
  5854. {
  5855. using number_integer_t = typename BasicJsonType::number_integer_t;
  5856. using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
  5857. using number_float_t = typename BasicJsonType::number_float_t;
  5858. using string_t = typename BasicJsonType::string_t;
  5859. using char_type = typename InputAdapterType::char_type;
  5860. using char_int_type = typename std::char_traits<char_type>::int_type;
  5861. public:
  5862. using token_type = typename lexer_base<BasicJsonType>::token_type;
  5863. explicit lexer(InputAdapterType&& adapter, bool ignore_comments_ = false) noexcept
  5864. : ia(std::move(adapter))
  5865. , ignore_comments(ignore_comments_)
  5866. , decimal_point_char(static_cast<char_int_type>(get_decimal_point()))
  5867. {}
  5868. // delete because of pointer members
  5869. lexer(const lexer&) = delete;
  5870. lexer(lexer&&) = default; // NOLINT(hicpp-noexcept-move,performance-noexcept-move-constructor)
  5871. lexer& operator=(lexer&) = delete;
  5872. lexer& operator=(lexer&&) = default; // NOLINT(hicpp-noexcept-move,performance-noexcept-move-constructor)
  5873. ~lexer() = default;
  5874. private:
  5875. /////////////////////
  5876. // locales
  5877. /////////////////////
  5878. /// return the locale-dependent decimal point
  5879. JSON_HEDLEY_PURE
  5880. static char get_decimal_point() noexcept
  5881. {
  5882. const auto* loc = localeconv();
  5883. JSON_ASSERT(loc != nullptr);
  5884. return (loc->decimal_point == nullptr) ? '.' : *(loc->decimal_point);
  5885. }
  5886. /////////////////////
  5887. // scan functions
  5888. /////////////////////
  5889. /*!
  5890. @brief get codepoint from 4 hex characters following `\u`
  5891. For input "\u c1 c2 c3 c4" the codepoint is:
  5892. (c1 * 0x1000) + (c2 * 0x0100) + (c3 * 0x0010) + c4
  5893. = (c1 << 12) + (c2 << 8) + (c3 << 4) + (c4 << 0)
  5894. Furthermore, the possible characters '0'..'9', 'A'..'F', and 'a'..'f'
  5895. must be converted to the integers 0x0..0x9, 0xA..0xF, 0xA..0xF, resp. The
  5896. conversion is done by subtracting the offset (0x30, 0x37, and 0x57)
  5897. between the ASCII value of the character and the desired integer value.
  5898. @return codepoint (0x0000..0xFFFF) or -1 in case of an error (e.g. EOF or
  5899. non-hex character)
  5900. */
  5901. int get_codepoint()
  5902. {
  5903. // this function only makes sense after reading `\u`
  5904. JSON_ASSERT(current == 'u');
  5905. int codepoint = 0;
  5906. const auto factors = { 12u, 8u, 4u, 0u };
  5907. for (const auto factor : factors)
  5908. {
  5909. get();
  5910. if (current >= '0' && current <= '9')
  5911. {
  5912. codepoint += static_cast<int>((static_cast<unsigned int>(current) - 0x30u) << factor);
  5913. }
  5914. else if (current >= 'A' && current <= 'F')
  5915. {
  5916. codepoint += static_cast<int>((static_cast<unsigned int>(current) - 0x37u) << factor);
  5917. }
  5918. else if (current >= 'a' && current <= 'f')
  5919. {
  5920. codepoint += static_cast<int>((static_cast<unsigned int>(current) - 0x57u) << factor);
  5921. }
  5922. else
  5923. {
  5924. return -1;
  5925. }
  5926. }
  5927. JSON_ASSERT(0x0000 <= codepoint && codepoint <= 0xFFFF);
  5928. return codepoint;
  5929. }
  5930. /*!
  5931. @brief check if the next byte(s) are inside a given range
  5932. Adds the current byte and, for each passed range, reads a new byte and
  5933. checks if it is inside the range. If a violation was detected, set up an
  5934. error message and return false. Otherwise, return true.
  5935. @param[in] ranges list of integers; interpreted as list of pairs of
  5936. inclusive lower and upper bound, respectively
  5937. @pre The passed list @a ranges must have 2, 4, or 6 elements; that is,
  5938. 1, 2, or 3 pairs. This precondition is enforced by an assertion.
  5939. @return true if and only if no range violation was detected
  5940. */
  5941. bool next_byte_in_range(std::initializer_list<char_int_type> ranges)
  5942. {
  5943. JSON_ASSERT(ranges.size() == 2 || ranges.size() == 4 || ranges.size() == 6);
  5944. add(current);
  5945. for (auto range = ranges.begin(); range != ranges.end(); ++range)
  5946. {
  5947. get();
  5948. if (JSON_HEDLEY_LIKELY(*range <= current && current <= *(++range)))
  5949. {
  5950. add(current);
  5951. }
  5952. else
  5953. {
  5954. error_message = "invalid string: ill-formed UTF-8 byte";
  5955. return false;
  5956. }
  5957. }
  5958. return true;
  5959. }
  5960. /*!
  5961. @brief scan a string literal
  5962. This function scans a string according to Sect. 7 of RFC 8259. While
  5963. scanning, bytes are escaped and copied into buffer token_buffer. Then the
  5964. function returns successfully, token_buffer is *not* null-terminated (as it
  5965. may contain \0 bytes), and token_buffer.size() is the number of bytes in the
  5966. string.
  5967. @return token_type::value_string if string could be successfully scanned,
  5968. token_type::parse_error otherwise
  5969. @note In case of errors, variable error_message contains a textual
  5970. description.
  5971. */
  5972. token_type scan_string()
  5973. {
  5974. // reset token_buffer (ignore opening quote)
  5975. reset();
  5976. // we entered the function by reading an open quote
  5977. JSON_ASSERT(current == '\"');
  5978. while (true)
  5979. {
  5980. // get next character
  5981. switch (get())
  5982. {
  5983. // end of file while parsing string
  5984. case std::char_traits<char_type>::eof():
  5985. {
  5986. error_message = "invalid string: missing closing quote";
  5987. return token_type::parse_error;
  5988. }
  5989. // closing quote
  5990. case '\"':
  5991. {
  5992. return token_type::value_string;
  5993. }
  5994. // escapes
  5995. case '\\':
  5996. {
  5997. switch (get())
  5998. {
  5999. // quotation mark
  6000. case '\"':
  6001. add('\"');
  6002. break;
  6003. // reverse solidus
  6004. case '\\':
  6005. add('\\');
  6006. break;
  6007. // solidus
  6008. case '/':
  6009. add('/');
  6010. break;
  6011. // backspace
  6012. case 'b':
  6013. add('\b');
  6014. break;
  6015. // form feed
  6016. case 'f':
  6017. add('\f');
  6018. break;
  6019. // line feed
  6020. case 'n':
  6021. add('\n');
  6022. break;
  6023. // carriage return
  6024. case 'r':
  6025. add('\r');
  6026. break;
  6027. // tab
  6028. case 't':
  6029. add('\t');
  6030. break;
  6031. // unicode escapes
  6032. case 'u':
  6033. {
  6034. const int codepoint1 = get_codepoint();
  6035. int codepoint = codepoint1; // start with codepoint1
  6036. if (JSON_HEDLEY_UNLIKELY(codepoint1 == -1))
  6037. {
  6038. error_message = "invalid string: '\\u' must be followed by 4 hex digits";
  6039. return token_type::parse_error;
  6040. }
  6041. // check if code point is a high surrogate
  6042. if (0xD800 <= codepoint1 && codepoint1 <= 0xDBFF)
  6043. {
  6044. // expect next \uxxxx entry
  6045. if (JSON_HEDLEY_LIKELY(get() == '\\' && get() == 'u'))
  6046. {
  6047. const int codepoint2 = get_codepoint();
  6048. if (JSON_HEDLEY_UNLIKELY(codepoint2 == -1))
  6049. {
  6050. error_message = "invalid string: '\\u' must be followed by 4 hex digits";
  6051. return token_type::parse_error;
  6052. }
  6053. // check if codepoint2 is a low surrogate
  6054. if (JSON_HEDLEY_LIKELY(0xDC00 <= codepoint2 && codepoint2 <= 0xDFFF))
  6055. {
  6056. // overwrite codepoint
  6057. codepoint = static_cast<int>(
  6058. // high surrogate occupies the most significant 22 bits
  6059. (static_cast<unsigned int>(codepoint1) << 10u)
  6060. // low surrogate occupies the least significant 15 bits
  6061. + static_cast<unsigned int>(codepoint2)
  6062. // there is still the 0xD800, 0xDC00 and 0x10000 noise
  6063. // in the result so we have to subtract with:
  6064. // (0xD800 << 10) + DC00 - 0x10000 = 0x35FDC00
  6065. - 0x35FDC00u);
  6066. }
  6067. else
  6068. {
  6069. error_message = "invalid string: surrogate U+D800..U+DBFF must be followed by U+DC00..U+DFFF";
  6070. return token_type::parse_error;
  6071. }
  6072. }
  6073. else
  6074. {
  6075. error_message = "invalid string: surrogate U+D800..U+DBFF must be followed by U+DC00..U+DFFF";
  6076. return token_type::parse_error;
  6077. }
  6078. }
  6079. else
  6080. {
  6081. if (JSON_HEDLEY_UNLIKELY(0xDC00 <= codepoint1 && codepoint1 <= 0xDFFF))
  6082. {
  6083. error_message = "invalid string: surrogate U+DC00..U+DFFF must follow U+D800..U+DBFF";
  6084. return token_type::parse_error;
  6085. }
  6086. }
  6087. // result of the above calculation yields a proper codepoint
  6088. JSON_ASSERT(0x00 <= codepoint && codepoint <= 0x10FFFF);
  6089. // translate codepoint into bytes
  6090. if (codepoint < 0x80)
  6091. {
  6092. // 1-byte characters: 0xxxxxxx (ASCII)
  6093. add(static_cast<char_int_type>(codepoint));
  6094. }
  6095. else if (codepoint <= 0x7FF)
  6096. {
  6097. // 2-byte characters: 110xxxxx 10xxxxxx
  6098. add(static_cast<char_int_type>(0xC0u | (static_cast<unsigned int>(codepoint) >> 6u)));
  6099. add(static_cast<char_int_type>(0x80u | (static_cast<unsigned int>(codepoint) & 0x3Fu)));
  6100. }
  6101. else if (codepoint <= 0xFFFF)
  6102. {
  6103. // 3-byte characters: 1110xxxx 10xxxxxx 10xxxxxx
  6104. add(static_cast<char_int_type>(0xE0u | (static_cast<unsigned int>(codepoint) >> 12u)));
  6105. add(static_cast<char_int_type>(0x80u | ((static_cast<unsigned int>(codepoint) >> 6u) & 0x3Fu)));
  6106. add(static_cast<char_int_type>(0x80u | (static_cast<unsigned int>(codepoint) & 0x3Fu)));
  6107. }
  6108. else
  6109. {
  6110. // 4-byte characters: 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
  6111. add(static_cast<char_int_type>(0xF0u | (static_cast<unsigned int>(codepoint) >> 18u)));
  6112. add(static_cast<char_int_type>(0x80u | ((static_cast<unsigned int>(codepoint) >> 12u) & 0x3Fu)));
  6113. add(static_cast<char_int_type>(0x80u | ((static_cast<unsigned int>(codepoint) >> 6u) & 0x3Fu)));
  6114. add(static_cast<char_int_type>(0x80u | (static_cast<unsigned int>(codepoint) & 0x3Fu)));
  6115. }
  6116. break;
  6117. }
  6118. // other characters after escape
  6119. default:
  6120. error_message = "invalid string: forbidden character after backslash";
  6121. return token_type::parse_error;
  6122. }
  6123. break;
  6124. }
  6125. // invalid control characters
  6126. case 0x00:
  6127. {
  6128. error_message = "invalid string: control character U+0000 (NUL) must be escaped to \\u0000";
  6129. return token_type::parse_error;
  6130. }
  6131. case 0x01:
  6132. {
  6133. error_message = "invalid string: control character U+0001 (SOH) must be escaped to \\u0001";
  6134. return token_type::parse_error;
  6135. }
  6136. case 0x02:
  6137. {
  6138. error_message = "invalid string: control character U+0002 (STX) must be escaped to \\u0002";
  6139. return token_type::parse_error;
  6140. }
  6141. case 0x03:
  6142. {
  6143. error_message = "invalid string: control character U+0003 (ETX) must be escaped to \\u0003";
  6144. return token_type::parse_error;
  6145. }
  6146. case 0x04:
  6147. {
  6148. error_message = "invalid string: control character U+0004 (EOT) must be escaped to \\u0004";
  6149. return token_type::parse_error;
  6150. }
  6151. case 0x05:
  6152. {
  6153. error_message = "invalid string: control character U+0005 (ENQ) must be escaped to \\u0005";
  6154. return token_type::parse_error;
  6155. }
  6156. case 0x06:
  6157. {
  6158. error_message = "invalid string: control character U+0006 (ACK) must be escaped to \\u0006";
  6159. return token_type::parse_error;
  6160. }
  6161. case 0x07:
  6162. {
  6163. error_message = "invalid string: control character U+0007 (BEL) must be escaped to \\u0007";
  6164. return token_type::parse_error;
  6165. }
  6166. case 0x08:
  6167. {
  6168. error_message = "invalid string: control character U+0008 (BS) must be escaped to \\u0008 or \\b";
  6169. return token_type::parse_error;
  6170. }
  6171. case 0x09:
  6172. {
  6173. error_message = "invalid string: control character U+0009 (HT) must be escaped to \\u0009 or \\t";
  6174. return token_type::parse_error;
  6175. }
  6176. case 0x0A:
  6177. {
  6178. error_message = "invalid string: control character U+000A (LF) must be escaped to \\u000A or \\n";
  6179. return token_type::parse_error;
  6180. }
  6181. case 0x0B:
  6182. {
  6183. error_message = "invalid string: control character U+000B (VT) must be escaped to \\u000B";
  6184. return token_type::parse_error;
  6185. }
  6186. case 0x0C:
  6187. {
  6188. error_message = "invalid string: control character U+000C (FF) must be escaped to \\u000C or \\f";
  6189. return token_type::parse_error;
  6190. }
  6191. case 0x0D:
  6192. {
  6193. error_message = "invalid string: control character U+000D (CR) must be escaped to \\u000D or \\r";
  6194. return token_type::parse_error;
  6195. }
  6196. case 0x0E:
  6197. {
  6198. error_message = "invalid string: control character U+000E (SO) must be escaped to \\u000E";
  6199. return token_type::parse_error;
  6200. }
  6201. case 0x0F:
  6202. {
  6203. error_message = "invalid string: control character U+000F (SI) must be escaped to \\u000F";
  6204. return token_type::parse_error;
  6205. }
  6206. case 0x10:
  6207. {
  6208. error_message = "invalid string: control character U+0010 (DLE) must be escaped to \\u0010";
  6209. return token_type::parse_error;
  6210. }
  6211. case 0x11:
  6212. {
  6213. error_message = "invalid string: control character U+0011 (DC1) must be escaped to \\u0011";
  6214. return token_type::parse_error;
  6215. }
  6216. case 0x12:
  6217. {
  6218. error_message = "invalid string: control character U+0012 (DC2) must be escaped to \\u0012";
  6219. return token_type::parse_error;
  6220. }
  6221. case 0x13:
  6222. {
  6223. error_message = "invalid string: control character U+0013 (DC3) must be escaped to \\u0013";
  6224. return token_type::parse_error;
  6225. }
  6226. case 0x14:
  6227. {
  6228. error_message = "invalid string: control character U+0014 (DC4) must be escaped to \\u0014";
  6229. return token_type::parse_error;
  6230. }
  6231. case 0x15:
  6232. {
  6233. error_message = "invalid string: control character U+0015 (NAK) must be escaped to \\u0015";
  6234. return token_type::parse_error;
  6235. }
  6236. case 0x16:
  6237. {
  6238. error_message = "invalid string: control character U+0016 (SYN) must be escaped to \\u0016";
  6239. return token_type::parse_error;
  6240. }
  6241. case 0x17:
  6242. {
  6243. error_message = "invalid string: control character U+0017 (ETB) must be escaped to \\u0017";
  6244. return token_type::parse_error;
  6245. }
  6246. case 0x18:
  6247. {
  6248. error_message = "invalid string: control character U+0018 (CAN) must be escaped to \\u0018";
  6249. return token_type::parse_error;
  6250. }
  6251. case 0x19:
  6252. {
  6253. error_message = "invalid string: control character U+0019 (EM) must be escaped to \\u0019";
  6254. return token_type::parse_error;
  6255. }
  6256. case 0x1A:
  6257. {
  6258. error_message = "invalid string: control character U+001A (SUB) must be escaped to \\u001A";
  6259. return token_type::parse_error;
  6260. }
  6261. case 0x1B:
  6262. {
  6263. error_message = "invalid string: control character U+001B (ESC) must be escaped to \\u001B";
  6264. return token_type::parse_error;
  6265. }
  6266. case 0x1C:
  6267. {
  6268. error_message = "invalid string: control character U+001C (FS) must be escaped to \\u001C";
  6269. return token_type::parse_error;
  6270. }
  6271. case 0x1D:
  6272. {
  6273. error_message = "invalid string: control character U+001D (GS) must be escaped to \\u001D";
  6274. return token_type::parse_error;
  6275. }
  6276. case 0x1E:
  6277. {
  6278. error_message = "invalid string: control character U+001E (RS) must be escaped to \\u001E";
  6279. return token_type::parse_error;
  6280. }
  6281. case 0x1F:
  6282. {
  6283. error_message = "invalid string: control character U+001F (US) must be escaped to \\u001F";
  6284. return token_type::parse_error;
  6285. }
  6286. // U+0020..U+007F (except U+0022 (quote) and U+005C (backspace))
  6287. case 0x20:
  6288. case 0x21:
  6289. case 0x23:
  6290. case 0x24:
  6291. case 0x25:
  6292. case 0x26:
  6293. case 0x27:
  6294. case 0x28:
  6295. case 0x29:
  6296. case 0x2A:
  6297. case 0x2B:
  6298. case 0x2C:
  6299. case 0x2D:
  6300. case 0x2E:
  6301. case 0x2F:
  6302. case 0x30:
  6303. case 0x31:
  6304. case 0x32:
  6305. case 0x33:
  6306. case 0x34:
  6307. case 0x35:
  6308. case 0x36:
  6309. case 0x37:
  6310. case 0x38:
  6311. case 0x39:
  6312. case 0x3A:
  6313. case 0x3B:
  6314. case 0x3C:
  6315. case 0x3D:
  6316. case 0x3E:
  6317. case 0x3F:
  6318. case 0x40:
  6319. case 0x41:
  6320. case 0x42:
  6321. case 0x43:
  6322. case 0x44:
  6323. case 0x45:
  6324. case 0x46:
  6325. case 0x47:
  6326. case 0x48:
  6327. case 0x49:
  6328. case 0x4A:
  6329. case 0x4B:
  6330. case 0x4C:
  6331. case 0x4D:
  6332. case 0x4E:
  6333. case 0x4F:
  6334. case 0x50:
  6335. case 0x51:
  6336. case 0x52:
  6337. case 0x53:
  6338. case 0x54:
  6339. case 0x55:
  6340. case 0x56:
  6341. case 0x57:
  6342. case 0x58:
  6343. case 0x59:
  6344. case 0x5A:
  6345. case 0x5B:
  6346. case 0x5D:
  6347. case 0x5E:
  6348. case 0x5F:
  6349. case 0x60:
  6350. case 0x61:
  6351. case 0x62:
  6352. case 0x63:
  6353. case 0x64:
  6354. case 0x65:
  6355. case 0x66:
  6356. case 0x67:
  6357. case 0x68:
  6358. case 0x69:
  6359. case 0x6A:
  6360. case 0x6B:
  6361. case 0x6C:
  6362. case 0x6D:
  6363. case 0x6E:
  6364. case 0x6F:
  6365. case 0x70:
  6366. case 0x71:
  6367. case 0x72:
  6368. case 0x73:
  6369. case 0x74:
  6370. case 0x75:
  6371. case 0x76:
  6372. case 0x77:
  6373. case 0x78:
  6374. case 0x79:
  6375. case 0x7A:
  6376. case 0x7B:
  6377. case 0x7C:
  6378. case 0x7D:
  6379. case 0x7E:
  6380. case 0x7F:
  6381. {
  6382. add(current);
  6383. break;
  6384. }
  6385. // U+0080..U+07FF: bytes C2..DF 80..BF
  6386. case 0xC2:
  6387. case 0xC3:
  6388. case 0xC4:
  6389. case 0xC5:
  6390. case 0xC6:
  6391. case 0xC7:
  6392. case 0xC8:
  6393. case 0xC9:
  6394. case 0xCA:
  6395. case 0xCB:
  6396. case 0xCC:
  6397. case 0xCD:
  6398. case 0xCE:
  6399. case 0xCF:
  6400. case 0xD0:
  6401. case 0xD1:
  6402. case 0xD2:
  6403. case 0xD3:
  6404. case 0xD4:
  6405. case 0xD5:
  6406. case 0xD6:
  6407. case 0xD7:
  6408. case 0xD8:
  6409. case 0xD9:
  6410. case 0xDA:
  6411. case 0xDB:
  6412. case 0xDC:
  6413. case 0xDD:
  6414. case 0xDE:
  6415. case 0xDF:
  6416. {
  6417. if (JSON_HEDLEY_UNLIKELY(!next_byte_in_range({0x80, 0xBF})))
  6418. {
  6419. return token_type::parse_error;
  6420. }
  6421. break;
  6422. }
  6423. // U+0800..U+0FFF: bytes E0 A0..BF 80..BF
  6424. case 0xE0:
  6425. {
  6426. if (JSON_HEDLEY_UNLIKELY(!(next_byte_in_range({0xA0, 0xBF, 0x80, 0xBF}))))
  6427. {
  6428. return token_type::parse_error;
  6429. }
  6430. break;
  6431. }
  6432. // U+1000..U+CFFF: bytes E1..EC 80..BF 80..BF
  6433. // U+E000..U+FFFF: bytes EE..EF 80..BF 80..BF
  6434. case 0xE1:
  6435. case 0xE2:
  6436. case 0xE3:
  6437. case 0xE4:
  6438. case 0xE5:
  6439. case 0xE6:
  6440. case 0xE7:
  6441. case 0xE8:
  6442. case 0xE9:
  6443. case 0xEA:
  6444. case 0xEB:
  6445. case 0xEC:
  6446. case 0xEE:
  6447. case 0xEF:
  6448. {
  6449. if (JSON_HEDLEY_UNLIKELY(!(next_byte_in_range({0x80, 0xBF, 0x80, 0xBF}))))
  6450. {
  6451. return token_type::parse_error;
  6452. }
  6453. break;
  6454. }
  6455. // U+D000..U+D7FF: bytes ED 80..9F 80..BF
  6456. case 0xED:
  6457. {
  6458. if (JSON_HEDLEY_UNLIKELY(!(next_byte_in_range({0x80, 0x9F, 0x80, 0xBF}))))
  6459. {
  6460. return token_type::parse_error;
  6461. }
  6462. break;
  6463. }
  6464. // U+10000..U+3FFFF F0 90..BF 80..BF 80..BF
  6465. case 0xF0:
  6466. {
  6467. if (JSON_HEDLEY_UNLIKELY(!(next_byte_in_range({0x90, 0xBF, 0x80, 0xBF, 0x80, 0xBF}))))
  6468. {
  6469. return token_type::parse_error;
  6470. }
  6471. break;
  6472. }
  6473. // U+40000..U+FFFFF F1..F3 80..BF 80..BF 80..BF
  6474. case 0xF1:
  6475. case 0xF2:
  6476. case 0xF3:
  6477. {
  6478. if (JSON_HEDLEY_UNLIKELY(!(next_byte_in_range({0x80, 0xBF, 0x80, 0xBF, 0x80, 0xBF}))))
  6479. {
  6480. return token_type::parse_error;
  6481. }
  6482. break;
  6483. }
  6484. // U+100000..U+10FFFF F4 80..8F 80..BF 80..BF
  6485. case 0xF4:
  6486. {
  6487. if (JSON_HEDLEY_UNLIKELY(!(next_byte_in_range({0x80, 0x8F, 0x80, 0xBF, 0x80, 0xBF}))))
  6488. {
  6489. return token_type::parse_error;
  6490. }
  6491. break;
  6492. }
  6493. // remaining bytes (80..C1 and F5..FF) are ill-formed
  6494. default:
  6495. {
  6496. error_message = "invalid string: ill-formed UTF-8 byte";
  6497. return token_type::parse_error;
  6498. }
  6499. }
  6500. }
  6501. }
  6502. /*!
  6503. * @brief scan a comment
  6504. * @return whether comment could be scanned successfully
  6505. */
  6506. bool scan_comment()
  6507. {
  6508. switch (get())
  6509. {
  6510. // single-line comments skip input until a newline or EOF is read
  6511. case '/':
  6512. {
  6513. while (true)
  6514. {
  6515. switch (get())
  6516. {
  6517. case '\n':
  6518. case '\r':
  6519. case std::char_traits<char_type>::eof():
  6520. case '\0':
  6521. return true;
  6522. default:
  6523. break;
  6524. }
  6525. }
  6526. }
  6527. // multi-line comments skip input until */ is read
  6528. case '*':
  6529. {
  6530. while (true)
  6531. {
  6532. switch (get())
  6533. {
  6534. case std::char_traits<char_type>::eof():
  6535. case '\0':
  6536. {
  6537. error_message = "invalid comment; missing closing '*/'";
  6538. return false;
  6539. }
  6540. case '*':
  6541. {
  6542. switch (get())
  6543. {
  6544. case '/':
  6545. return true;
  6546. default:
  6547. {
  6548. unget();
  6549. continue;
  6550. }
  6551. }
  6552. }
  6553. default:
  6554. continue;
  6555. }
  6556. }
  6557. }
  6558. // unexpected character after reading '/'
  6559. default:
  6560. {
  6561. error_message = "invalid comment; expecting '/' or '*' after '/'";
  6562. return false;
  6563. }
  6564. }
  6565. }
  6566. JSON_HEDLEY_NON_NULL(2)
  6567. static void strtof(float& f, const char* str, char** endptr) noexcept
  6568. {
  6569. f = std::strtof(str, endptr);
  6570. }
  6571. JSON_HEDLEY_NON_NULL(2)
  6572. static void strtof(double& f, const char* str, char** endptr) noexcept
  6573. {
  6574. f = std::strtod(str, endptr);
  6575. }
  6576. JSON_HEDLEY_NON_NULL(2)
  6577. static void strtof(long double& f, const char* str, char** endptr) noexcept
  6578. {
  6579. f = std::strtold(str, endptr);
  6580. }
  6581. /*!
  6582. @brief scan a number literal
  6583. This function scans a string according to Sect. 6 of RFC 8259.
  6584. The function is realized with a deterministic finite state machine derived
  6585. from the grammar described in RFC 8259. Starting in state "init", the
  6586. input is read and used to determined the next state. Only state "done"
  6587. accepts the number. State "error" is a trap state to model errors. In the
  6588. table below, "anything" means any character but the ones listed before.
  6589. state | 0 | 1-9 | e E | + | - | . | anything
  6590. ---------|----------|----------|----------|---------|---------|----------|-----------
  6591. init | zero | any1 | [error] | [error] | minus | [error] | [error]
  6592. minus | zero | any1 | [error] | [error] | [error] | [error] | [error]
  6593. zero | done | done | exponent | done | done | decimal1 | done
  6594. any1 | any1 | any1 | exponent | done | done | decimal1 | done
  6595. decimal1 | decimal2 | decimal2 | [error] | [error] | [error] | [error] | [error]
  6596. decimal2 | decimal2 | decimal2 | exponent | done | done | done | done
  6597. exponent | any2 | any2 | [error] | sign | sign | [error] | [error]
  6598. sign | any2 | any2 | [error] | [error] | [error] | [error] | [error]
  6599. any2 | any2 | any2 | done | done | done | done | done
  6600. The state machine is realized with one label per state (prefixed with
  6601. "scan_number_") and `goto` statements between them. The state machine
  6602. contains cycles, but any cycle can be left when EOF is read. Therefore,
  6603. the function is guaranteed to terminate.
  6604. During scanning, the read bytes are stored in token_buffer. This string is
  6605. then converted to a signed integer, an unsigned integer, or a
  6606. floating-point number.
  6607. @return token_type::value_unsigned, token_type::value_integer, or
  6608. token_type::value_float if number could be successfully scanned,
  6609. token_type::parse_error otherwise
  6610. @note The scanner is independent of the current locale. Internally, the
  6611. locale's decimal point is used instead of `.` to work with the
  6612. locale-dependent converters.
  6613. */
  6614. token_type scan_number() // lgtm [cpp/use-of-goto]
  6615. {
  6616. // reset token_buffer to store the number's bytes
  6617. reset();
  6618. // the type of the parsed number; initially set to unsigned; will be
  6619. // changed if minus sign, decimal point or exponent is read
  6620. token_type number_type = token_type::value_unsigned;
  6621. // state (init): we just found out we need to scan a number
  6622. switch (current)
  6623. {
  6624. case '-':
  6625. {
  6626. add(current);
  6627. goto scan_number_minus;
  6628. }
  6629. case '0':
  6630. {
  6631. add(current);
  6632. goto scan_number_zero;
  6633. }
  6634. case '1':
  6635. case '2':
  6636. case '3':
  6637. case '4':
  6638. case '5':
  6639. case '6':
  6640. case '7':
  6641. case '8':
  6642. case '9':
  6643. {
  6644. add(current);
  6645. goto scan_number_any1;
  6646. }
  6647. // all other characters are rejected outside scan_number()
  6648. default: // LCOV_EXCL_LINE
  6649. JSON_ASSERT(false); // NOLINT(cert-dcl03-c,hicpp-static-assert,misc-static-assert) LCOV_EXCL_LINE
  6650. }
  6651. scan_number_minus:
  6652. // state: we just parsed a leading minus sign
  6653. number_type = token_type::value_integer;
  6654. switch (get())
  6655. {
  6656. case '0':
  6657. {
  6658. add(current);
  6659. goto scan_number_zero;
  6660. }
  6661. case '1':
  6662. case '2':
  6663. case '3':
  6664. case '4':
  6665. case '5':
  6666. case '6':
  6667. case '7':
  6668. case '8':
  6669. case '9':
  6670. {
  6671. add(current);
  6672. goto scan_number_any1;
  6673. }
  6674. default:
  6675. {
  6676. error_message = "invalid number; expected digit after '-'";
  6677. return token_type::parse_error;
  6678. }
  6679. }
  6680. scan_number_zero:
  6681. // state: we just parse a zero (maybe with a leading minus sign)
  6682. switch (get())
  6683. {
  6684. case '.':
  6685. {
  6686. add(decimal_point_char);
  6687. goto scan_number_decimal1;
  6688. }
  6689. case 'e':
  6690. case 'E':
  6691. {
  6692. add(current);
  6693. goto scan_number_exponent;
  6694. }
  6695. default:
  6696. goto scan_number_done;
  6697. }
  6698. scan_number_any1:
  6699. // state: we just parsed a number 0-9 (maybe with a leading minus sign)
  6700. switch (get())
  6701. {
  6702. case '0':
  6703. case '1':
  6704. case '2':
  6705. case '3':
  6706. case '4':
  6707. case '5':
  6708. case '6':
  6709. case '7':
  6710. case '8':
  6711. case '9':
  6712. {
  6713. add(current);
  6714. goto scan_number_any1;
  6715. }
  6716. case '.':
  6717. {
  6718. add(decimal_point_char);
  6719. goto scan_number_decimal1;
  6720. }
  6721. case 'e':
  6722. case 'E':
  6723. {
  6724. add(current);
  6725. goto scan_number_exponent;
  6726. }
  6727. default:
  6728. goto scan_number_done;
  6729. }
  6730. scan_number_decimal1:
  6731. // state: we just parsed a decimal point
  6732. number_type = token_type::value_float;
  6733. switch (get())
  6734. {
  6735. case '0':
  6736. case '1':
  6737. case '2':
  6738. case '3':
  6739. case '4':
  6740. case '5':
  6741. case '6':
  6742. case '7':
  6743. case '8':
  6744. case '9':
  6745. {
  6746. add(current);
  6747. goto scan_number_decimal2;
  6748. }
  6749. default:
  6750. {
  6751. error_message = "invalid number; expected digit after '.'";
  6752. return token_type::parse_error;
  6753. }
  6754. }
  6755. scan_number_decimal2:
  6756. // we just parsed at least one number after a decimal point
  6757. switch (get())
  6758. {
  6759. case '0':
  6760. case '1':
  6761. case '2':
  6762. case '3':
  6763. case '4':
  6764. case '5':
  6765. case '6':
  6766. case '7':
  6767. case '8':
  6768. case '9':
  6769. {
  6770. add(current);
  6771. goto scan_number_decimal2;
  6772. }
  6773. case 'e':
  6774. case 'E':
  6775. {
  6776. add(current);
  6777. goto scan_number_exponent;
  6778. }
  6779. default:
  6780. goto scan_number_done;
  6781. }
  6782. scan_number_exponent:
  6783. // we just parsed an exponent
  6784. number_type = token_type::value_float;
  6785. switch (get())
  6786. {
  6787. case '+':
  6788. case '-':
  6789. {
  6790. add(current);
  6791. goto scan_number_sign;
  6792. }
  6793. case '0':
  6794. case '1':
  6795. case '2':
  6796. case '3':
  6797. case '4':
  6798. case '5':
  6799. case '6':
  6800. case '7':
  6801. case '8':
  6802. case '9':
  6803. {
  6804. add(current);
  6805. goto scan_number_any2;
  6806. }
  6807. default:
  6808. {
  6809. error_message =
  6810. "invalid number; expected '+', '-', or digit after exponent";
  6811. return token_type::parse_error;
  6812. }
  6813. }
  6814. scan_number_sign:
  6815. // we just parsed an exponent sign
  6816. switch (get())
  6817. {
  6818. case '0':
  6819. case '1':
  6820. case '2':
  6821. case '3':
  6822. case '4':
  6823. case '5':
  6824. case '6':
  6825. case '7':
  6826. case '8':
  6827. case '9':
  6828. {
  6829. add(current);
  6830. goto scan_number_any2;
  6831. }
  6832. default:
  6833. {
  6834. error_message = "invalid number; expected digit after exponent sign";
  6835. return token_type::parse_error;
  6836. }
  6837. }
  6838. scan_number_any2:
  6839. // we just parsed a number after the exponent or exponent sign
  6840. switch (get())
  6841. {
  6842. case '0':
  6843. case '1':
  6844. case '2':
  6845. case '3':
  6846. case '4':
  6847. case '5':
  6848. case '6':
  6849. case '7':
  6850. case '8':
  6851. case '9':
  6852. {
  6853. add(current);
  6854. goto scan_number_any2;
  6855. }
  6856. default:
  6857. goto scan_number_done;
  6858. }
  6859. scan_number_done:
  6860. // unget the character after the number (we only read it to know that
  6861. // we are done scanning a number)
  6862. unget();
  6863. char* endptr = nullptr; // NOLINT(cppcoreguidelines-pro-type-vararg,hicpp-vararg)
  6864. errno = 0;
  6865. // try to parse integers first and fall back to floats
  6866. if (number_type == token_type::value_unsigned)
  6867. {
  6868. const auto x = std::strtoull(token_buffer.data(), &endptr, 10);
  6869. // we checked the number format before
  6870. JSON_ASSERT(endptr == token_buffer.data() + token_buffer.size());
  6871. if (errno == 0)
  6872. {
  6873. value_unsigned = static_cast<number_unsigned_t>(x);
  6874. if (value_unsigned == x)
  6875. {
  6876. return token_type::value_unsigned;
  6877. }
  6878. }
  6879. }
  6880. else if (number_type == token_type::value_integer)
  6881. {
  6882. const auto x = std::strtoll(token_buffer.data(), &endptr, 10);
  6883. // we checked the number format before
  6884. JSON_ASSERT(endptr == token_buffer.data() + token_buffer.size());
  6885. if (errno == 0)
  6886. {
  6887. value_integer = static_cast<number_integer_t>(x);
  6888. if (value_integer == x)
  6889. {
  6890. return token_type::value_integer;
  6891. }
  6892. }
  6893. }
  6894. // this code is reached if we parse a floating-point number or if an
  6895. // integer conversion above failed
  6896. strtof(value_float, token_buffer.data(), &endptr);
  6897. // we checked the number format before
  6898. JSON_ASSERT(endptr == token_buffer.data() + token_buffer.size());
  6899. return token_type::value_float;
  6900. }
  6901. /*!
  6902. @param[in] literal_text the literal text to expect
  6903. @param[in] length the length of the passed literal text
  6904. @param[in] return_type the token type to return on success
  6905. */
  6906. JSON_HEDLEY_NON_NULL(2)
  6907. token_type scan_literal(const char_type* literal_text, const std::size_t length,
  6908. token_type return_type)
  6909. {
  6910. JSON_ASSERT(std::char_traits<char_type>::to_char_type(current) == literal_text[0]);
  6911. for (std::size_t i = 1; i < length; ++i)
  6912. {
  6913. if (JSON_HEDLEY_UNLIKELY(std::char_traits<char_type>::to_char_type(get()) != literal_text[i]))
  6914. {
  6915. error_message = "invalid literal";
  6916. return token_type::parse_error;
  6917. }
  6918. }
  6919. return return_type;
  6920. }
  6921. /////////////////////
  6922. // input management
  6923. /////////////////////
  6924. /// reset token_buffer; current character is beginning of token
  6925. void reset() noexcept
  6926. {
  6927. token_buffer.clear();
  6928. token_string.clear();
  6929. token_string.push_back(std::char_traits<char_type>::to_char_type(current));
  6930. }
  6931. /*
  6932. @brief get next character from the input
  6933. This function provides the interface to the used input adapter. It does
  6934. not throw in case the input reached EOF, but returns a
  6935. `std::char_traits<char>::eof()` in that case. Stores the scanned characters
  6936. for use in error messages.
  6937. @return character read from the input
  6938. */
  6939. char_int_type get()
  6940. {
  6941. ++position.chars_read_total;
  6942. ++position.chars_read_current_line;
  6943. if (next_unget)
  6944. {
  6945. // just reset the next_unget variable and work with current
  6946. next_unget = false;
  6947. }
  6948. else
  6949. {
  6950. current = ia.get_character();
  6951. }
  6952. if (JSON_HEDLEY_LIKELY(current != std::char_traits<char_type>::eof()))
  6953. {
  6954. token_string.push_back(std::char_traits<char_type>::to_char_type(current));
  6955. }
  6956. if (current == '\n')
  6957. {
  6958. ++position.lines_read;
  6959. position.chars_read_current_line = 0;
  6960. }
  6961. return current;
  6962. }
  6963. /*!
  6964. @brief unget current character (read it again on next get)
  6965. We implement unget by setting variable next_unget to true. The input is not
  6966. changed - we just simulate ungetting by modifying chars_read_total,
  6967. chars_read_current_line, and token_string. The next call to get() will
  6968. behave as if the unget character is read again.
  6969. */
  6970. void unget()
  6971. {
  6972. next_unget = true;
  6973. --position.chars_read_total;
  6974. // in case we "unget" a newline, we have to also decrement the lines_read
  6975. if (position.chars_read_current_line == 0)
  6976. {
  6977. if (position.lines_read > 0)
  6978. {
  6979. --position.lines_read;
  6980. }
  6981. }
  6982. else
  6983. {
  6984. --position.chars_read_current_line;
  6985. }
  6986. if (JSON_HEDLEY_LIKELY(current != std::char_traits<char_type>::eof()))
  6987. {
  6988. JSON_ASSERT(!token_string.empty());
  6989. token_string.pop_back();
  6990. }
  6991. }
  6992. /// add a character to token_buffer
  6993. void add(char_int_type c)
  6994. {
  6995. token_buffer.push_back(static_cast<typename string_t::value_type>(c));
  6996. }
  6997. public:
  6998. /////////////////////
  6999. // value getters
  7000. /////////////////////
  7001. /// return integer value
  7002. constexpr number_integer_t get_number_integer() const noexcept
  7003. {
  7004. return value_integer;
  7005. }
  7006. /// return unsigned integer value
  7007. constexpr number_unsigned_t get_number_unsigned() const noexcept
  7008. {
  7009. return value_unsigned;
  7010. }
  7011. /// return floating-point value
  7012. constexpr number_float_t get_number_float() const noexcept
  7013. {
  7014. return value_float;
  7015. }
  7016. /// return current string value (implicitly resets the token; useful only once)
  7017. string_t& get_string()
  7018. {
  7019. return token_buffer;
  7020. }
  7021. /////////////////////
  7022. // diagnostics
  7023. /////////////////////
  7024. /// return position of last read token
  7025. constexpr position_t get_position() const noexcept
  7026. {
  7027. return position;
  7028. }
  7029. /// return the last read token (for errors only). Will never contain EOF
  7030. /// (an arbitrary value that is not a valid char value, often -1), because
  7031. /// 255 may legitimately occur. May contain NUL, which should be escaped.
  7032. std::string get_token_string() const
  7033. {
  7034. // escape control characters
  7035. std::string result;
  7036. for (const auto c : token_string)
  7037. {
  7038. if (static_cast<unsigned char>(c) <= '\x1F')
  7039. {
  7040. // escape control characters
  7041. std::array<char, 9> cs{{}};
  7042. (std::snprintf)(cs.data(), cs.size(), "<U+%.4X>", static_cast<unsigned char>(c)); // NOLINT(cppcoreguidelines-pro-type-vararg,hicpp-vararg)
  7043. result += cs.data();
  7044. }
  7045. else
  7046. {
  7047. // add character as is
  7048. result.push_back(static_cast<std::string::value_type>(c));
  7049. }
  7050. }
  7051. return result;
  7052. }
  7053. /// return syntax error message
  7054. JSON_HEDLEY_RETURNS_NON_NULL
  7055. constexpr const char* get_error_message() const noexcept
  7056. {
  7057. return error_message;
  7058. }
  7059. /////////////////////
  7060. // actual scanner
  7061. /////////////////////
  7062. /*!
  7063. @brief skip the UTF-8 byte order mark
  7064. @return true iff there is no BOM or the correct BOM has been skipped
  7065. */
  7066. bool skip_bom()
  7067. {
  7068. if (get() == 0xEF)
  7069. {
  7070. // check if we completely parse the BOM
  7071. return get() == 0xBB && get() == 0xBF;
  7072. }
  7073. // the first character is not the beginning of the BOM; unget it to
  7074. // process is later
  7075. unget();
  7076. return true;
  7077. }
  7078. void skip_whitespace()
  7079. {
  7080. do
  7081. {
  7082. get();
  7083. }
  7084. while (current == ' ' || current == '\t' || current == '\n' || current == '\r');
  7085. }
  7086. token_type scan()
  7087. {
  7088. // initially, skip the BOM
  7089. if (position.chars_read_total == 0 && !skip_bom())
  7090. {
  7091. error_message = "invalid BOM; must be 0xEF 0xBB 0xBF if given";
  7092. return token_type::parse_error;
  7093. }
  7094. // read next character and ignore whitespace
  7095. skip_whitespace();
  7096. // ignore comments
  7097. while (ignore_comments && current == '/')
  7098. {
  7099. if (!scan_comment())
  7100. {
  7101. return token_type::parse_error;
  7102. }
  7103. // skip following whitespace
  7104. skip_whitespace();
  7105. }
  7106. switch (current)
  7107. {
  7108. // structural characters
  7109. case '[':
  7110. return token_type::begin_array;
  7111. case ']':
  7112. return token_type::end_array;
  7113. case '{':
  7114. return token_type::begin_object;
  7115. case '}':
  7116. return token_type::end_object;
  7117. case ':':
  7118. return token_type::name_separator;
  7119. case ',':
  7120. return token_type::value_separator;
  7121. // literals
  7122. case 't':
  7123. {
  7124. std::array<char_type, 4> true_literal = {{char_type('t'), char_type('r'), char_type('u'), char_type('e')}};
  7125. return scan_literal(true_literal.data(), true_literal.size(), token_type::literal_true);
  7126. }
  7127. case 'f':
  7128. {
  7129. std::array<char_type, 5> false_literal = {{char_type('f'), char_type('a'), char_type('l'), char_type('s'), char_type('e')}};
  7130. return scan_literal(false_literal.data(), false_literal.size(), token_type::literal_false);
  7131. }
  7132. case 'n':
  7133. {
  7134. std::array<char_type, 4> null_literal = {{char_type('n'), char_type('u'), char_type('l'), char_type('l')}};
  7135. return scan_literal(null_literal.data(), null_literal.size(), token_type::literal_null);
  7136. }
  7137. // string
  7138. case '\"':
  7139. return scan_string();
  7140. // number
  7141. case '-':
  7142. case '0':
  7143. case '1':
  7144. case '2':
  7145. case '3':
  7146. case '4':
  7147. case '5':
  7148. case '6':
  7149. case '7':
  7150. case '8':
  7151. case '9':
  7152. return scan_number();
  7153. // end of input (the null byte is needed when parsing from
  7154. // string literals)
  7155. case '\0':
  7156. case std::char_traits<char_type>::eof():
  7157. return token_type::end_of_input;
  7158. // error
  7159. default:
  7160. error_message = "invalid literal";
  7161. return token_type::parse_error;
  7162. }
  7163. }
  7164. private:
  7165. /// input adapter
  7166. InputAdapterType ia;
  7167. /// whether comments should be ignored (true) or signaled as errors (false)
  7168. const bool ignore_comments = false;
  7169. /// the current character
  7170. char_int_type current = std::char_traits<char_type>::eof();
  7171. /// whether the next get() call should just return current
  7172. bool next_unget = false;
  7173. /// the start position of the current token
  7174. position_t position {};
  7175. /// raw input token string (for error messages)
  7176. std::vector<char_type> token_string {};
  7177. /// buffer for variable-length tokens (numbers, strings)
  7178. string_t token_buffer {};
  7179. /// a description of occurred lexer errors
  7180. const char* error_message = "";
  7181. // number values
  7182. number_integer_t value_integer = 0;
  7183. number_unsigned_t value_unsigned = 0;
  7184. number_float_t value_float = 0;
  7185. /// the decimal point
  7186. const char_int_type decimal_point_char = '.';
  7187. };
  7188. } // namespace detail
  7189. } // namespace nlohmann
  7190. // #include <nlohmann/detail/macro_scope.hpp>
  7191. // #include <nlohmann/detail/meta/is_sax.hpp>
  7192. #include <cstdint> // size_t
  7193. #include <utility> // declval
  7194. #include <string> // string
  7195. // #include <nlohmann/detail/meta/detected.hpp>
  7196. // #include <nlohmann/detail/meta/type_traits.hpp>
  7197. namespace nlohmann
  7198. {
  7199. namespace detail
  7200. {
  7201. template<typename T>
  7202. using null_function_t = decltype(std::declval<T&>().null());
  7203. template<typename T>
  7204. using boolean_function_t =
  7205. decltype(std::declval<T&>().boolean(std::declval<bool>()));
  7206. template<typename T, typename Integer>
  7207. using number_integer_function_t =
  7208. decltype(std::declval<T&>().number_integer(std::declval<Integer>()));
  7209. template<typename T, typename Unsigned>
  7210. using number_unsigned_function_t =
  7211. decltype(std::declval<T&>().number_unsigned(std::declval<Unsigned>()));
  7212. template<typename T, typename Float, typename String>
  7213. using number_float_function_t = decltype(std::declval<T&>().number_float(
  7214. std::declval<Float>(), std::declval<const String&>()));
  7215. template<typename T, typename String>
  7216. using string_function_t =
  7217. decltype(std::declval<T&>().string(std::declval<String&>()));
  7218. template<typename T, typename Binary>
  7219. using binary_function_t =
  7220. decltype(std::declval<T&>().binary(std::declval<Binary&>()));
  7221. template<typename T>
  7222. using start_object_function_t =
  7223. decltype(std::declval<T&>().start_object(std::declval<std::size_t>()));
  7224. template<typename T, typename String>
  7225. using key_function_t =
  7226. decltype(std::declval<T&>().key(std::declval<String&>()));
  7227. template<typename T>
  7228. using end_object_function_t = decltype(std::declval<T&>().end_object());
  7229. template<typename T>
  7230. using start_array_function_t =
  7231. decltype(std::declval<T&>().start_array(std::declval<std::size_t>()));
  7232. template<typename T>
  7233. using end_array_function_t = decltype(std::declval<T&>().end_array());
  7234. template<typename T, typename Exception>
  7235. using parse_error_function_t = decltype(std::declval<T&>().parse_error(
  7236. std::declval<std::size_t>(), std::declval<const std::string&>(),
  7237. std::declval<const Exception&>()));
  7238. template<typename SAX, typename BasicJsonType>
  7239. struct is_sax
  7240. {
  7241. private:
  7242. static_assert(is_basic_json<BasicJsonType>::value,
  7243. "BasicJsonType must be of type basic_json<...>");
  7244. using number_integer_t = typename BasicJsonType::number_integer_t;
  7245. using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
  7246. using number_float_t = typename BasicJsonType::number_float_t;
  7247. using string_t = typename BasicJsonType::string_t;
  7248. using binary_t = typename BasicJsonType::binary_t;
  7249. using exception_t = typename BasicJsonType::exception;
  7250. public:
  7251. static constexpr bool value =
  7252. is_detected_exact<bool, null_function_t, SAX>::value &&
  7253. is_detected_exact<bool, boolean_function_t, SAX>::value &&
  7254. is_detected_exact<bool, number_integer_function_t, SAX, number_integer_t>::value &&
  7255. is_detected_exact<bool, number_unsigned_function_t, SAX, number_unsigned_t>::value &&
  7256. is_detected_exact<bool, number_float_function_t, SAX, number_float_t, string_t>::value &&
  7257. is_detected_exact<bool, string_function_t, SAX, string_t>::value &&
  7258. is_detected_exact<bool, binary_function_t, SAX, binary_t>::value &&
  7259. is_detected_exact<bool, start_object_function_t, SAX>::value &&
  7260. is_detected_exact<bool, key_function_t, SAX, string_t>::value &&
  7261. is_detected_exact<bool, end_object_function_t, SAX>::value &&
  7262. is_detected_exact<bool, start_array_function_t, SAX>::value &&
  7263. is_detected_exact<bool, end_array_function_t, SAX>::value &&
  7264. is_detected_exact<bool, parse_error_function_t, SAX, exception_t>::value;
  7265. };
  7266. template<typename SAX, typename BasicJsonType>
  7267. struct is_sax_static_asserts
  7268. {
  7269. private:
  7270. static_assert(is_basic_json<BasicJsonType>::value,
  7271. "BasicJsonType must be of type basic_json<...>");
  7272. using number_integer_t = typename BasicJsonType::number_integer_t;
  7273. using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
  7274. using number_float_t = typename BasicJsonType::number_float_t;
  7275. using string_t = typename BasicJsonType::string_t;
  7276. using binary_t = typename BasicJsonType::binary_t;
  7277. using exception_t = typename BasicJsonType::exception;
  7278. public:
  7279. static_assert(is_detected_exact<bool, null_function_t, SAX>::value,
  7280. "Missing/invalid function: bool null()");
  7281. static_assert(is_detected_exact<bool, boolean_function_t, SAX>::value,
  7282. "Missing/invalid function: bool boolean(bool)");
  7283. static_assert(is_detected_exact<bool, boolean_function_t, SAX>::value,
  7284. "Missing/invalid function: bool boolean(bool)");
  7285. static_assert(
  7286. is_detected_exact<bool, number_integer_function_t, SAX,
  7287. number_integer_t>::value,
  7288. "Missing/invalid function: bool number_integer(number_integer_t)");
  7289. static_assert(
  7290. is_detected_exact<bool, number_unsigned_function_t, SAX,
  7291. number_unsigned_t>::value,
  7292. "Missing/invalid function: bool number_unsigned(number_unsigned_t)");
  7293. static_assert(is_detected_exact<bool, number_float_function_t, SAX,
  7294. number_float_t, string_t>::value,
  7295. "Missing/invalid function: bool number_float(number_float_t, const string_t&)");
  7296. static_assert(
  7297. is_detected_exact<bool, string_function_t, SAX, string_t>::value,
  7298. "Missing/invalid function: bool string(string_t&)");
  7299. static_assert(
  7300. is_detected_exact<bool, binary_function_t, SAX, binary_t>::value,
  7301. "Missing/invalid function: bool binary(binary_t&)");
  7302. static_assert(is_detected_exact<bool, start_object_function_t, SAX>::value,
  7303. "Missing/invalid function: bool start_object(std::size_t)");
  7304. static_assert(is_detected_exact<bool, key_function_t, SAX, string_t>::value,
  7305. "Missing/invalid function: bool key(string_t&)");
  7306. static_assert(is_detected_exact<bool, end_object_function_t, SAX>::value,
  7307. "Missing/invalid function: bool end_object()");
  7308. static_assert(is_detected_exact<bool, start_array_function_t, SAX>::value,
  7309. "Missing/invalid function: bool start_array(std::size_t)");
  7310. static_assert(is_detected_exact<bool, end_array_function_t, SAX>::value,
  7311. "Missing/invalid function: bool end_array()");
  7312. static_assert(
  7313. is_detected_exact<bool, parse_error_function_t, SAX, exception_t>::value,
  7314. "Missing/invalid function: bool parse_error(std::size_t, const "
  7315. "std::string&, const exception&)");
  7316. };
  7317. } // namespace detail
  7318. } // namespace nlohmann
  7319. // #include <nlohmann/detail/meta/type_traits.hpp>
  7320. // #include <nlohmann/detail/value_t.hpp>
  7321. namespace nlohmann
  7322. {
  7323. namespace detail
  7324. {
  7325. /// how to treat CBOR tags
  7326. enum class cbor_tag_handler_t
  7327. {
  7328. error, ///< throw a parse_error exception in case of a tag
  7329. ignore, ///< ignore tags
  7330. store ///< store tags as binary type
  7331. };
  7332. /*!
  7333. @brief determine system byte order
  7334. @return true if and only if system's byte order is little endian
  7335. @note from https://stackoverflow.com/a/1001328/266378
  7336. */
  7337. static inline bool little_endianess(int num = 1) noexcept
  7338. {
  7339. return *reinterpret_cast<char*>(&num) == 1;
  7340. }
  7341. ///////////////////
  7342. // binary reader //
  7343. ///////////////////
  7344. /*!
  7345. @brief deserialization of CBOR, MessagePack, and UBJSON values
  7346. */
  7347. template<typename BasicJsonType, typename InputAdapterType, typename SAX = json_sax_dom_parser<BasicJsonType>>
  7348. class binary_reader
  7349. {
  7350. using number_integer_t = typename BasicJsonType::number_integer_t;
  7351. using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
  7352. using number_float_t = typename BasicJsonType::number_float_t;
  7353. using string_t = typename BasicJsonType::string_t;
  7354. using binary_t = typename BasicJsonType::binary_t;
  7355. using json_sax_t = SAX;
  7356. using char_type = typename InputAdapterType::char_type;
  7357. using char_int_type = typename std::char_traits<char_type>::int_type;
  7358. public:
  7359. /*!
  7360. @brief create a binary reader
  7361. @param[in] adapter input adapter to read from
  7362. */
  7363. explicit binary_reader(InputAdapterType&& adapter) noexcept : ia(std::move(adapter))
  7364. {
  7365. (void)detail::is_sax_static_asserts<SAX, BasicJsonType> {};
  7366. }
  7367. // make class move-only
  7368. binary_reader(const binary_reader&) = delete;
  7369. binary_reader(binary_reader&&) = default; // NOLINT(hicpp-noexcept-move,performance-noexcept-move-constructor)
  7370. binary_reader& operator=(const binary_reader&) = delete;
  7371. binary_reader& operator=(binary_reader&&) = default; // NOLINT(hicpp-noexcept-move,performance-noexcept-move-constructor)
  7372. ~binary_reader() = default;
  7373. /*!
  7374. @param[in] format the binary format to parse
  7375. @param[in] sax_ a SAX event processor
  7376. @param[in] strict whether to expect the input to be consumed completed
  7377. @param[in] tag_handler how to treat CBOR tags
  7378. @return whether parsing was successful
  7379. */
  7380. JSON_HEDLEY_NON_NULL(3)
  7381. bool sax_parse(const input_format_t format,
  7382. json_sax_t* sax_,
  7383. const bool strict = true,
  7384. const cbor_tag_handler_t tag_handler = cbor_tag_handler_t::error)
  7385. {
  7386. sax = sax_;
  7387. bool result = false;
  7388. switch (format)
  7389. {
  7390. case input_format_t::bson:
  7391. result = parse_bson_internal();
  7392. break;
  7393. case input_format_t::cbor:
  7394. result = parse_cbor_internal(true, tag_handler);
  7395. break;
  7396. case input_format_t::msgpack:
  7397. result = parse_msgpack_internal();
  7398. break;
  7399. case input_format_t::ubjson:
  7400. result = parse_ubjson_internal();
  7401. break;
  7402. case input_format_t::json: // LCOV_EXCL_LINE
  7403. default: // LCOV_EXCL_LINE
  7404. JSON_ASSERT(false); // NOLINT(cert-dcl03-c,hicpp-static-assert,misc-static-assert) LCOV_EXCL_LINE
  7405. }
  7406. // strict mode: next byte must be EOF
  7407. if (result && strict)
  7408. {
  7409. if (format == input_format_t::ubjson)
  7410. {
  7411. get_ignore_noop();
  7412. }
  7413. else
  7414. {
  7415. get();
  7416. }
  7417. if (JSON_HEDLEY_UNLIKELY(current != std::char_traits<char_type>::eof()))
  7418. {
  7419. return sax->parse_error(chars_read, get_token_string(),
  7420. parse_error::create(110, chars_read, exception_message(format, "expected end of input; last byte: 0x" + get_token_string(), "value"), BasicJsonType()));
  7421. }
  7422. }
  7423. return result;
  7424. }
  7425. private:
  7426. //////////
  7427. // BSON //
  7428. //////////
  7429. /*!
  7430. @brief Reads in a BSON-object and passes it to the SAX-parser.
  7431. @return whether a valid BSON-value was passed to the SAX parser
  7432. */
  7433. bool parse_bson_internal()
  7434. {
  7435. std::int32_t document_size{};
  7436. get_number<std::int32_t, true>(input_format_t::bson, document_size);
  7437. if (JSON_HEDLEY_UNLIKELY(!sax->start_object(std::size_t(-1))))
  7438. {
  7439. return false;
  7440. }
  7441. if (JSON_HEDLEY_UNLIKELY(!parse_bson_element_list(/*is_array*/false)))
  7442. {
  7443. return false;
  7444. }
  7445. return sax->end_object();
  7446. }
  7447. /*!
  7448. @brief Parses a C-style string from the BSON input.
  7449. @param[in,out] result A reference to the string variable where the read
  7450. string is to be stored.
  7451. @return `true` if the \x00-byte indicating the end of the string was
  7452. encountered before the EOF; false` indicates an unexpected EOF.
  7453. */
  7454. bool get_bson_cstr(string_t& result)
  7455. {
  7456. auto out = std::back_inserter(result);
  7457. while (true)
  7458. {
  7459. get();
  7460. if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(input_format_t::bson, "cstring")))
  7461. {
  7462. return false;
  7463. }
  7464. if (current == 0x00)
  7465. {
  7466. return true;
  7467. }
  7468. *out++ = static_cast<typename string_t::value_type>(current);
  7469. }
  7470. }
  7471. /*!
  7472. @brief Parses a zero-terminated string of length @a len from the BSON
  7473. input.
  7474. @param[in] len The length (including the zero-byte at the end) of the
  7475. string to be read.
  7476. @param[in,out] result A reference to the string variable where the read
  7477. string is to be stored.
  7478. @tparam NumberType The type of the length @a len
  7479. @pre len >= 1
  7480. @return `true` if the string was successfully parsed
  7481. */
  7482. template<typename NumberType>
  7483. bool get_bson_string(const NumberType len, string_t& result)
  7484. {
  7485. if (JSON_HEDLEY_UNLIKELY(len < 1))
  7486. {
  7487. auto last_token = get_token_string();
  7488. 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"), BasicJsonType()));
  7489. }
  7490. return get_string(input_format_t::bson, len - static_cast<NumberType>(1), result) && get() != std::char_traits<char_type>::eof();
  7491. }
  7492. /*!
  7493. @brief Parses a byte array input of length @a len from the BSON input.
  7494. @param[in] len The length of the byte array to be read.
  7495. @param[in,out] result A reference to the binary variable where the read
  7496. array is to be stored.
  7497. @tparam NumberType The type of the length @a len
  7498. @pre len >= 0
  7499. @return `true` if the byte array was successfully parsed
  7500. */
  7501. template<typename NumberType>
  7502. bool get_bson_binary(const NumberType len, binary_t& result)
  7503. {
  7504. if (JSON_HEDLEY_UNLIKELY(len < 0))
  7505. {
  7506. auto last_token = get_token_string();
  7507. return sax->parse_error(chars_read, last_token, parse_error::create(112, chars_read, exception_message(input_format_t::bson, "byte array length cannot be negative, is " + std::to_string(len), "binary"), BasicJsonType()));
  7508. }
  7509. // All BSON binary values have a subtype
  7510. std::uint8_t subtype{};
  7511. get_number<std::uint8_t>(input_format_t::bson, subtype);
  7512. result.set_subtype(subtype);
  7513. return get_binary(input_format_t::bson, len, result);
  7514. }
  7515. /*!
  7516. @brief Read a BSON document element of the given @a element_type.
  7517. @param[in] element_type The BSON element type, c.f. http://bsonspec.org/spec.html
  7518. @param[in] element_type_parse_position The position in the input stream,
  7519. where the `element_type` was read.
  7520. @warning Not all BSON element types are supported yet. An unsupported
  7521. @a element_type will give rise to a parse_error.114:
  7522. Unsupported BSON record type 0x...
  7523. @return whether a valid BSON-object/array was passed to the SAX parser
  7524. */
  7525. bool parse_bson_element_internal(const char_int_type element_type,
  7526. const std::size_t element_type_parse_position)
  7527. {
  7528. switch (element_type)
  7529. {
  7530. case 0x01: // double
  7531. {
  7532. double number{};
  7533. return get_number<double, true>(input_format_t::bson, number) && sax->number_float(static_cast<number_float_t>(number), "");
  7534. }
  7535. case 0x02: // string
  7536. {
  7537. std::int32_t len{};
  7538. string_t value;
  7539. return get_number<std::int32_t, true>(input_format_t::bson, len) && get_bson_string(len, value) && sax->string(value);
  7540. }
  7541. case 0x03: // object
  7542. {
  7543. return parse_bson_internal();
  7544. }
  7545. case 0x04: // array
  7546. {
  7547. return parse_bson_array();
  7548. }
  7549. case 0x05: // binary
  7550. {
  7551. std::int32_t len{};
  7552. binary_t value;
  7553. return get_number<std::int32_t, true>(input_format_t::bson, len) && get_bson_binary(len, value) && sax->binary(value);
  7554. }
  7555. case 0x08: // boolean
  7556. {
  7557. return sax->boolean(get() != 0);
  7558. }
  7559. case 0x0A: // null
  7560. {
  7561. return sax->null();
  7562. }
  7563. case 0x10: // int32
  7564. {
  7565. std::int32_t value{};
  7566. return get_number<std::int32_t, true>(input_format_t::bson, value) && sax->number_integer(value);
  7567. }
  7568. case 0x12: // int64
  7569. {
  7570. std::int64_t value{};
  7571. return get_number<std::int64_t, true>(input_format_t::bson, value) && sax->number_integer(value);
  7572. }
  7573. default: // anything else not supported (yet)
  7574. {
  7575. std::array<char, 3> cr{{}};
  7576. (std::snprintf)(cr.data(), cr.size(), "%.2hhX", static_cast<unsigned char>(element_type)); // NOLINT(cppcoreguidelines-pro-type-vararg,hicpp-vararg)
  7577. return sax->parse_error(element_type_parse_position, std::string(cr.data()), parse_error::create(114, element_type_parse_position, "Unsupported BSON record type 0x" + std::string(cr.data()), BasicJsonType()));
  7578. }
  7579. }
  7580. }
  7581. /*!
  7582. @brief Read a BSON element list (as specified in the BSON-spec)
  7583. The same binary layout is used for objects and arrays, hence it must be
  7584. indicated with the argument @a is_array which one is expected
  7585. (true --> array, false --> object).
  7586. @param[in] is_array Determines if the element list being read is to be
  7587. treated as an object (@a is_array == false), or as an
  7588. array (@a is_array == true).
  7589. @return whether a valid BSON-object/array was passed to the SAX parser
  7590. */
  7591. bool parse_bson_element_list(const bool is_array)
  7592. {
  7593. string_t key;
  7594. while (auto element_type = get())
  7595. {
  7596. if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(input_format_t::bson, "element list")))
  7597. {
  7598. return false;
  7599. }
  7600. const std::size_t element_type_parse_position = chars_read;
  7601. if (JSON_HEDLEY_UNLIKELY(!get_bson_cstr(key)))
  7602. {
  7603. return false;
  7604. }
  7605. if (!is_array && !sax->key(key))
  7606. {
  7607. return false;
  7608. }
  7609. if (JSON_HEDLEY_UNLIKELY(!parse_bson_element_internal(element_type, element_type_parse_position)))
  7610. {
  7611. return false;
  7612. }
  7613. // get_bson_cstr only appends
  7614. key.clear();
  7615. }
  7616. return true;
  7617. }
  7618. /*!
  7619. @brief Reads an array from the BSON input and passes it to the SAX-parser.
  7620. @return whether a valid BSON-array was passed to the SAX parser
  7621. */
  7622. bool parse_bson_array()
  7623. {
  7624. std::int32_t document_size{};
  7625. get_number<std::int32_t, true>(input_format_t::bson, document_size);
  7626. if (JSON_HEDLEY_UNLIKELY(!sax->start_array(std::size_t(-1))))
  7627. {
  7628. return false;
  7629. }
  7630. if (JSON_HEDLEY_UNLIKELY(!parse_bson_element_list(/*is_array*/true)))
  7631. {
  7632. return false;
  7633. }
  7634. return sax->end_array();
  7635. }
  7636. //////////
  7637. // CBOR //
  7638. //////////
  7639. /*!
  7640. @param[in] get_char whether a new character should be retrieved from the
  7641. input (true) or whether the last read character should
  7642. be considered instead (false)
  7643. @param[in] tag_handler how CBOR tags should be treated
  7644. @return whether a valid CBOR value was passed to the SAX parser
  7645. */
  7646. bool parse_cbor_internal(const bool get_char,
  7647. const cbor_tag_handler_t tag_handler)
  7648. {
  7649. switch (get_char ? get() : current)
  7650. {
  7651. // EOF
  7652. case std::char_traits<char_type>::eof():
  7653. return unexpect_eof(input_format_t::cbor, "value");
  7654. // Integer 0x00..0x17 (0..23)
  7655. case 0x00:
  7656. case 0x01:
  7657. case 0x02:
  7658. case 0x03:
  7659. case 0x04:
  7660. case 0x05:
  7661. case 0x06:
  7662. case 0x07:
  7663. case 0x08:
  7664. case 0x09:
  7665. case 0x0A:
  7666. case 0x0B:
  7667. case 0x0C:
  7668. case 0x0D:
  7669. case 0x0E:
  7670. case 0x0F:
  7671. case 0x10:
  7672. case 0x11:
  7673. case 0x12:
  7674. case 0x13:
  7675. case 0x14:
  7676. case 0x15:
  7677. case 0x16:
  7678. case 0x17:
  7679. return sax->number_unsigned(static_cast<number_unsigned_t>(current));
  7680. case 0x18: // Unsigned integer (one-byte uint8_t follows)
  7681. {
  7682. std::uint8_t number{};
  7683. return get_number(input_format_t::cbor, number) && sax->number_unsigned(number);
  7684. }
  7685. case 0x19: // Unsigned integer (two-byte uint16_t follows)
  7686. {
  7687. std::uint16_t number{};
  7688. return get_number(input_format_t::cbor, number) && sax->number_unsigned(number);
  7689. }
  7690. case 0x1A: // Unsigned integer (four-byte uint32_t follows)
  7691. {
  7692. std::uint32_t number{};
  7693. return get_number(input_format_t::cbor, number) && sax->number_unsigned(number);
  7694. }
  7695. case 0x1B: // Unsigned integer (eight-byte uint64_t follows)
  7696. {
  7697. std::uint64_t number{};
  7698. return get_number(input_format_t::cbor, number) && sax->number_unsigned(number);
  7699. }
  7700. // Negative integer -1-0x00..-1-0x17 (-1..-24)
  7701. case 0x20:
  7702. case 0x21:
  7703. case 0x22:
  7704. case 0x23:
  7705. case 0x24:
  7706. case 0x25:
  7707. case 0x26:
  7708. case 0x27:
  7709. case 0x28:
  7710. case 0x29:
  7711. case 0x2A:
  7712. case 0x2B:
  7713. case 0x2C:
  7714. case 0x2D:
  7715. case 0x2E:
  7716. case 0x2F:
  7717. case 0x30:
  7718. case 0x31:
  7719. case 0x32:
  7720. case 0x33:
  7721. case 0x34:
  7722. case 0x35:
  7723. case 0x36:
  7724. case 0x37:
  7725. return sax->number_integer(static_cast<std::int8_t>(0x20 - 1 - current));
  7726. case 0x38: // Negative integer (one-byte uint8_t follows)
  7727. {
  7728. std::uint8_t number{};
  7729. return get_number(input_format_t::cbor, number) && sax->number_integer(static_cast<number_integer_t>(-1) - number);
  7730. }
  7731. case 0x39: // Negative integer -1-n (two-byte uint16_t follows)
  7732. {
  7733. std::uint16_t number{};
  7734. return get_number(input_format_t::cbor, number) && sax->number_integer(static_cast<number_integer_t>(-1) - number);
  7735. }
  7736. case 0x3A: // Negative integer -1-n (four-byte uint32_t follows)
  7737. {
  7738. std::uint32_t number{};
  7739. return get_number(input_format_t::cbor, number) && sax->number_integer(static_cast<number_integer_t>(-1) - number);
  7740. }
  7741. case 0x3B: // Negative integer -1-n (eight-byte uint64_t follows)
  7742. {
  7743. std::uint64_t number{};
  7744. return get_number(input_format_t::cbor, number) && sax->number_integer(static_cast<number_integer_t>(-1)
  7745. - static_cast<number_integer_t>(number));
  7746. }
  7747. // Binary data (0x00..0x17 bytes follow)
  7748. case 0x40:
  7749. case 0x41:
  7750. case 0x42:
  7751. case 0x43:
  7752. case 0x44:
  7753. case 0x45:
  7754. case 0x46:
  7755. case 0x47:
  7756. case 0x48:
  7757. case 0x49:
  7758. case 0x4A:
  7759. case 0x4B:
  7760. case 0x4C:
  7761. case 0x4D:
  7762. case 0x4E:
  7763. case 0x4F:
  7764. case 0x50:
  7765. case 0x51:
  7766. case 0x52:
  7767. case 0x53:
  7768. case 0x54:
  7769. case 0x55:
  7770. case 0x56:
  7771. case 0x57:
  7772. case 0x58: // Binary data (one-byte uint8_t for n follows)
  7773. case 0x59: // Binary data (two-byte uint16_t for n follow)
  7774. case 0x5A: // Binary data (four-byte uint32_t for n follow)
  7775. case 0x5B: // Binary data (eight-byte uint64_t for n follow)
  7776. case 0x5F: // Binary data (indefinite length)
  7777. {
  7778. binary_t b;
  7779. return get_cbor_binary(b) && sax->binary(b);
  7780. }
  7781. // UTF-8 string (0x00..0x17 bytes follow)
  7782. case 0x60:
  7783. case 0x61:
  7784. case 0x62:
  7785. case 0x63:
  7786. case 0x64:
  7787. case 0x65:
  7788. case 0x66:
  7789. case 0x67:
  7790. case 0x68:
  7791. case 0x69:
  7792. case 0x6A:
  7793. case 0x6B:
  7794. case 0x6C:
  7795. case 0x6D:
  7796. case 0x6E:
  7797. case 0x6F:
  7798. case 0x70:
  7799. case 0x71:
  7800. case 0x72:
  7801. case 0x73:
  7802. case 0x74:
  7803. case 0x75:
  7804. case 0x76:
  7805. case 0x77:
  7806. case 0x78: // UTF-8 string (one-byte uint8_t for n follows)
  7807. case 0x79: // UTF-8 string (two-byte uint16_t for n follow)
  7808. case 0x7A: // UTF-8 string (four-byte uint32_t for n follow)
  7809. case 0x7B: // UTF-8 string (eight-byte uint64_t for n follow)
  7810. case 0x7F: // UTF-8 string (indefinite length)
  7811. {
  7812. string_t s;
  7813. return get_cbor_string(s) && sax->string(s);
  7814. }
  7815. // array (0x00..0x17 data items follow)
  7816. case 0x80:
  7817. case 0x81:
  7818. case 0x82:
  7819. case 0x83:
  7820. case 0x84:
  7821. case 0x85:
  7822. case 0x86:
  7823. case 0x87:
  7824. case 0x88:
  7825. case 0x89:
  7826. case 0x8A:
  7827. case 0x8B:
  7828. case 0x8C:
  7829. case 0x8D:
  7830. case 0x8E:
  7831. case 0x8F:
  7832. case 0x90:
  7833. case 0x91:
  7834. case 0x92:
  7835. case 0x93:
  7836. case 0x94:
  7837. case 0x95:
  7838. case 0x96:
  7839. case 0x97:
  7840. return get_cbor_array(static_cast<std::size_t>(static_cast<unsigned int>(current) & 0x1Fu), tag_handler);
  7841. case 0x98: // array (one-byte uint8_t for n follows)
  7842. {
  7843. std::uint8_t len{};
  7844. return get_number(input_format_t::cbor, len) && get_cbor_array(static_cast<std::size_t>(len), tag_handler);
  7845. }
  7846. case 0x99: // array (two-byte uint16_t for n follow)
  7847. {
  7848. std::uint16_t len{};
  7849. return get_number(input_format_t::cbor, len) && get_cbor_array(static_cast<std::size_t>(len), tag_handler);
  7850. }
  7851. case 0x9A: // array (four-byte uint32_t for n follow)
  7852. {
  7853. std::uint32_t len{};
  7854. return get_number(input_format_t::cbor, len) && get_cbor_array(static_cast<std::size_t>(len), tag_handler);
  7855. }
  7856. case 0x9B: // array (eight-byte uint64_t for n follow)
  7857. {
  7858. std::uint64_t len{};
  7859. return get_number(input_format_t::cbor, len) && get_cbor_array(detail::conditional_static_cast<std::size_t>(len), tag_handler);
  7860. }
  7861. case 0x9F: // array (indefinite length)
  7862. return get_cbor_array(std::size_t(-1), tag_handler);
  7863. // map (0x00..0x17 pairs of data items follow)
  7864. case 0xA0:
  7865. case 0xA1:
  7866. case 0xA2:
  7867. case 0xA3:
  7868. case 0xA4:
  7869. case 0xA5:
  7870. case 0xA6:
  7871. case 0xA7:
  7872. case 0xA8:
  7873. case 0xA9:
  7874. case 0xAA:
  7875. case 0xAB:
  7876. case 0xAC:
  7877. case 0xAD:
  7878. case 0xAE:
  7879. case 0xAF:
  7880. case 0xB0:
  7881. case 0xB1:
  7882. case 0xB2:
  7883. case 0xB3:
  7884. case 0xB4:
  7885. case 0xB5:
  7886. case 0xB6:
  7887. case 0xB7:
  7888. return get_cbor_object(static_cast<std::size_t>(static_cast<unsigned int>(current) & 0x1Fu), tag_handler);
  7889. case 0xB8: // map (one-byte uint8_t for n follows)
  7890. {
  7891. std::uint8_t len{};
  7892. return get_number(input_format_t::cbor, len) && get_cbor_object(static_cast<std::size_t>(len), tag_handler);
  7893. }
  7894. case 0xB9: // map (two-byte uint16_t for n follow)
  7895. {
  7896. std::uint16_t len{};
  7897. return get_number(input_format_t::cbor, len) && get_cbor_object(static_cast<std::size_t>(len), tag_handler);
  7898. }
  7899. case 0xBA: // map (four-byte uint32_t for n follow)
  7900. {
  7901. std::uint32_t len{};
  7902. return get_number(input_format_t::cbor, len) && get_cbor_object(static_cast<std::size_t>(len), tag_handler);
  7903. }
  7904. case 0xBB: // map (eight-byte uint64_t for n follow)
  7905. {
  7906. std::uint64_t len{};
  7907. return get_number(input_format_t::cbor, len) && get_cbor_object(detail::conditional_static_cast<std::size_t>(len), tag_handler);
  7908. }
  7909. case 0xBF: // map (indefinite length)
  7910. return get_cbor_object(std::size_t(-1), tag_handler);
  7911. case 0xC6: // tagged item
  7912. case 0xC7:
  7913. case 0xC8:
  7914. case 0xC9:
  7915. case 0xCA:
  7916. case 0xCB:
  7917. case 0xCC:
  7918. case 0xCD:
  7919. case 0xCE:
  7920. case 0xCF:
  7921. case 0xD0:
  7922. case 0xD1:
  7923. case 0xD2:
  7924. case 0xD3:
  7925. case 0xD4:
  7926. case 0xD8: // tagged item (1 bytes follow)
  7927. case 0xD9: // tagged item (2 bytes follow)
  7928. case 0xDA: // tagged item (4 bytes follow)
  7929. case 0xDB: // tagged item (8 bytes follow)
  7930. {
  7931. switch (tag_handler)
  7932. {
  7933. case cbor_tag_handler_t::error:
  7934. {
  7935. auto last_token = get_token_string();
  7936. 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"), BasicJsonType()));
  7937. }
  7938. case cbor_tag_handler_t::ignore:
  7939. {
  7940. // ignore binary subtype
  7941. switch (current)
  7942. {
  7943. case 0xD8:
  7944. {
  7945. std::uint8_t subtype_to_ignore{};
  7946. get_number(input_format_t::cbor, subtype_to_ignore);
  7947. break;
  7948. }
  7949. case 0xD9:
  7950. {
  7951. std::uint16_t subtype_to_ignore{};
  7952. get_number(input_format_t::cbor, subtype_to_ignore);
  7953. break;
  7954. }
  7955. case 0xDA:
  7956. {
  7957. std::uint32_t subtype_to_ignore{};
  7958. get_number(input_format_t::cbor, subtype_to_ignore);
  7959. break;
  7960. }
  7961. case 0xDB:
  7962. {
  7963. std::uint64_t subtype_to_ignore{};
  7964. get_number(input_format_t::cbor, subtype_to_ignore);
  7965. break;
  7966. }
  7967. default:
  7968. break;
  7969. }
  7970. return parse_cbor_internal(true, tag_handler);
  7971. }
  7972. case cbor_tag_handler_t::store:
  7973. {
  7974. binary_t b;
  7975. // use binary subtype and store in binary container
  7976. switch (current)
  7977. {
  7978. case 0xD8:
  7979. {
  7980. std::uint8_t subtype{};
  7981. get_number(input_format_t::cbor, subtype);
  7982. b.set_subtype(detail::conditional_static_cast<typename binary_t::subtype_type>(subtype));
  7983. break;
  7984. }
  7985. case 0xD9:
  7986. {
  7987. std::uint16_t subtype{};
  7988. get_number(input_format_t::cbor, subtype);
  7989. b.set_subtype(detail::conditional_static_cast<typename binary_t::subtype_type>(subtype));
  7990. break;
  7991. }
  7992. case 0xDA:
  7993. {
  7994. std::uint32_t subtype{};
  7995. get_number(input_format_t::cbor, subtype);
  7996. b.set_subtype(detail::conditional_static_cast<typename binary_t::subtype_type>(subtype));
  7997. break;
  7998. }
  7999. case 0xDB:
  8000. {
  8001. std::uint64_t subtype{};
  8002. get_number(input_format_t::cbor, subtype);
  8003. b.set_subtype(detail::conditional_static_cast<typename binary_t::subtype_type>(subtype));
  8004. break;
  8005. }
  8006. default:
  8007. return parse_cbor_internal(true, tag_handler);
  8008. }
  8009. get();
  8010. return get_cbor_binary(b) && sax->binary(b);
  8011. }
  8012. default: // LCOV_EXCL_LINE
  8013. JSON_ASSERT(false); // NOLINT(cert-dcl03-c,hicpp-static-assert,misc-static-assert) LCOV_EXCL_LINE
  8014. return false; // LCOV_EXCL_LINE
  8015. }
  8016. }
  8017. case 0xF4: // false
  8018. return sax->boolean(false);
  8019. case 0xF5: // true
  8020. return sax->boolean(true);
  8021. case 0xF6: // null
  8022. return sax->null();
  8023. case 0xF9: // Half-Precision Float (two-byte IEEE 754)
  8024. {
  8025. const auto byte1_raw = get();
  8026. if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(input_format_t::cbor, "number")))
  8027. {
  8028. return false;
  8029. }
  8030. const auto byte2_raw = get();
  8031. if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(input_format_t::cbor, "number")))
  8032. {
  8033. return false;
  8034. }
  8035. const auto byte1 = static_cast<unsigned char>(byte1_raw);
  8036. const auto byte2 = static_cast<unsigned char>(byte2_raw);
  8037. // code from RFC 7049, Appendix D, Figure 3:
  8038. // As half-precision floating-point numbers were only added
  8039. // to IEEE 754 in 2008, today's programming platforms often
  8040. // still only have limited support for them. It is very
  8041. // easy to include at least decoding support for them even
  8042. // without such support. An example of a small decoder for
  8043. // half-precision floating-point numbers in the C language
  8044. // is shown in Fig. 3.
  8045. const auto half = static_cast<unsigned int>((byte1 << 8u) + byte2);
  8046. const double val = [&half]
  8047. {
  8048. const int exp = (half >> 10u) & 0x1Fu;
  8049. const unsigned int mant = half & 0x3FFu;
  8050. JSON_ASSERT(0 <= exp&& exp <= 32);
  8051. JSON_ASSERT(mant <= 1024);
  8052. switch (exp)
  8053. {
  8054. case 0:
  8055. return std::ldexp(mant, -24);
  8056. case 31:
  8057. return (mant == 0)
  8058. ? std::numeric_limits<double>::infinity()
  8059. : std::numeric_limits<double>::quiet_NaN();
  8060. default:
  8061. return std::ldexp(mant + 1024, exp - 25);
  8062. }
  8063. }();
  8064. return sax->number_float((half & 0x8000u) != 0
  8065. ? static_cast<number_float_t>(-val)
  8066. : static_cast<number_float_t>(val), "");
  8067. }
  8068. case 0xFA: // Single-Precision Float (four-byte IEEE 754)
  8069. {
  8070. float number{};
  8071. return get_number(input_format_t::cbor, number) && sax->number_float(static_cast<number_float_t>(number), "");
  8072. }
  8073. case 0xFB: // Double-Precision Float (eight-byte IEEE 754)
  8074. {
  8075. double number{};
  8076. return get_number(input_format_t::cbor, number) && sax->number_float(static_cast<number_float_t>(number), "");
  8077. }
  8078. default: // anything else (0xFF is handled inside the other types)
  8079. {
  8080. auto last_token = get_token_string();
  8081. 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"), BasicJsonType()));
  8082. }
  8083. }
  8084. }
  8085. /*!
  8086. @brief reads a CBOR string
  8087. This function first reads starting bytes to determine the expected
  8088. string length and then copies this number of bytes into a string.
  8089. Additionally, CBOR's strings with indefinite lengths are supported.
  8090. @param[out] result created string
  8091. @return whether string creation completed
  8092. */
  8093. bool get_cbor_string(string_t& result)
  8094. {
  8095. if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(input_format_t::cbor, "string")))
  8096. {
  8097. return false;
  8098. }
  8099. switch (current)
  8100. {
  8101. // UTF-8 string (0x00..0x17 bytes follow)
  8102. case 0x60:
  8103. case 0x61:
  8104. case 0x62:
  8105. case 0x63:
  8106. case 0x64:
  8107. case 0x65:
  8108. case 0x66:
  8109. case 0x67:
  8110. case 0x68:
  8111. case 0x69:
  8112. case 0x6A:
  8113. case 0x6B:
  8114. case 0x6C:
  8115. case 0x6D:
  8116. case 0x6E:
  8117. case 0x6F:
  8118. case 0x70:
  8119. case 0x71:
  8120. case 0x72:
  8121. case 0x73:
  8122. case 0x74:
  8123. case 0x75:
  8124. case 0x76:
  8125. case 0x77:
  8126. {
  8127. return get_string(input_format_t::cbor, static_cast<unsigned int>(current) & 0x1Fu, result);
  8128. }
  8129. case 0x78: // UTF-8 string (one-byte uint8_t for n follows)
  8130. {
  8131. std::uint8_t len{};
  8132. return get_number(input_format_t::cbor, len) && get_string(input_format_t::cbor, len, result);
  8133. }
  8134. case 0x79: // UTF-8 string (two-byte uint16_t for n follow)
  8135. {
  8136. std::uint16_t len{};
  8137. return get_number(input_format_t::cbor, len) && get_string(input_format_t::cbor, len, result);
  8138. }
  8139. case 0x7A: // UTF-8 string (four-byte uint32_t for n follow)
  8140. {
  8141. std::uint32_t len{};
  8142. return get_number(input_format_t::cbor, len) && get_string(input_format_t::cbor, len, result);
  8143. }
  8144. case 0x7B: // UTF-8 string (eight-byte uint64_t for n follow)
  8145. {
  8146. std::uint64_t len{};
  8147. return get_number(input_format_t::cbor, len) && get_string(input_format_t::cbor, len, result);
  8148. }
  8149. case 0x7F: // UTF-8 string (indefinite length)
  8150. {
  8151. while (get() != 0xFF)
  8152. {
  8153. string_t chunk;
  8154. if (!get_cbor_string(chunk))
  8155. {
  8156. return false;
  8157. }
  8158. result.append(chunk);
  8159. }
  8160. return true;
  8161. }
  8162. default:
  8163. {
  8164. auto last_token = get_token_string();
  8165. 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"), BasicJsonType()));
  8166. }
  8167. }
  8168. }
  8169. /*!
  8170. @brief reads a CBOR byte array
  8171. This function first reads starting bytes to determine the expected
  8172. byte array length and then copies this number of bytes into the byte array.
  8173. Additionally, CBOR's byte arrays with indefinite lengths are supported.
  8174. @param[out] result created byte array
  8175. @return whether byte array creation completed
  8176. */
  8177. bool get_cbor_binary(binary_t& result)
  8178. {
  8179. if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(input_format_t::cbor, "binary")))
  8180. {
  8181. return false;
  8182. }
  8183. switch (current)
  8184. {
  8185. // Binary data (0x00..0x17 bytes follow)
  8186. case 0x40:
  8187. case 0x41:
  8188. case 0x42:
  8189. case 0x43:
  8190. case 0x44:
  8191. case 0x45:
  8192. case 0x46:
  8193. case 0x47:
  8194. case 0x48:
  8195. case 0x49:
  8196. case 0x4A:
  8197. case 0x4B:
  8198. case 0x4C:
  8199. case 0x4D:
  8200. case 0x4E:
  8201. case 0x4F:
  8202. case 0x50:
  8203. case 0x51:
  8204. case 0x52:
  8205. case 0x53:
  8206. case 0x54:
  8207. case 0x55:
  8208. case 0x56:
  8209. case 0x57:
  8210. {
  8211. return get_binary(input_format_t::cbor, static_cast<unsigned int>(current) & 0x1Fu, result);
  8212. }
  8213. case 0x58: // Binary data (one-byte uint8_t for n follows)
  8214. {
  8215. std::uint8_t len{};
  8216. return get_number(input_format_t::cbor, len) &&
  8217. get_binary(input_format_t::cbor, len, result);
  8218. }
  8219. case 0x59: // Binary data (two-byte uint16_t for n follow)
  8220. {
  8221. std::uint16_t len{};
  8222. return get_number(input_format_t::cbor, len) &&
  8223. get_binary(input_format_t::cbor, len, result);
  8224. }
  8225. case 0x5A: // Binary data (four-byte uint32_t for n follow)
  8226. {
  8227. std::uint32_t len{};
  8228. return get_number(input_format_t::cbor, len) &&
  8229. get_binary(input_format_t::cbor, len, result);
  8230. }
  8231. case 0x5B: // Binary data (eight-byte uint64_t for n follow)
  8232. {
  8233. std::uint64_t len{};
  8234. return get_number(input_format_t::cbor, len) &&
  8235. get_binary(input_format_t::cbor, len, result);
  8236. }
  8237. case 0x5F: // Binary data (indefinite length)
  8238. {
  8239. while (get() != 0xFF)
  8240. {
  8241. binary_t chunk;
  8242. if (!get_cbor_binary(chunk))
  8243. {
  8244. return false;
  8245. }
  8246. result.insert(result.end(), chunk.begin(), chunk.end());
  8247. }
  8248. return true;
  8249. }
  8250. default:
  8251. {
  8252. auto last_token = get_token_string();
  8253. return sax->parse_error(chars_read, last_token, parse_error::create(113, chars_read, exception_message(input_format_t::cbor, "expected length specification (0x40-0x5B) or indefinite binary array type (0x5F); last byte: 0x" + last_token, "binary"), BasicJsonType()));
  8254. }
  8255. }
  8256. }
  8257. /*!
  8258. @param[in] len the length of the array or std::size_t(-1) for an
  8259. array of indefinite size
  8260. @param[in] tag_handler how CBOR tags should be treated
  8261. @return whether array creation completed
  8262. */
  8263. bool get_cbor_array(const std::size_t len,
  8264. const cbor_tag_handler_t tag_handler)
  8265. {
  8266. if (JSON_HEDLEY_UNLIKELY(!sax->start_array(len)))
  8267. {
  8268. return false;
  8269. }
  8270. if (len != std::size_t(-1))
  8271. {
  8272. for (std::size_t i = 0; i < len; ++i)
  8273. {
  8274. if (JSON_HEDLEY_UNLIKELY(!parse_cbor_internal(true, tag_handler)))
  8275. {
  8276. return false;
  8277. }
  8278. }
  8279. }
  8280. else
  8281. {
  8282. while (get() != 0xFF)
  8283. {
  8284. if (JSON_HEDLEY_UNLIKELY(!parse_cbor_internal(false, tag_handler)))
  8285. {
  8286. return false;
  8287. }
  8288. }
  8289. }
  8290. return sax->end_array();
  8291. }
  8292. /*!
  8293. @param[in] len the length of the object or std::size_t(-1) for an
  8294. object of indefinite size
  8295. @param[in] tag_handler how CBOR tags should be treated
  8296. @return whether object creation completed
  8297. */
  8298. bool get_cbor_object(const std::size_t len,
  8299. const cbor_tag_handler_t tag_handler)
  8300. {
  8301. if (JSON_HEDLEY_UNLIKELY(!sax->start_object(len)))
  8302. {
  8303. return false;
  8304. }
  8305. if (len != 0)
  8306. {
  8307. string_t key;
  8308. if (len != std::size_t(-1))
  8309. {
  8310. for (std::size_t i = 0; i < len; ++i)
  8311. {
  8312. get();
  8313. if (JSON_HEDLEY_UNLIKELY(!get_cbor_string(key) || !sax->key(key)))
  8314. {
  8315. return false;
  8316. }
  8317. if (JSON_HEDLEY_UNLIKELY(!parse_cbor_internal(true, tag_handler)))
  8318. {
  8319. return false;
  8320. }
  8321. key.clear();
  8322. }
  8323. }
  8324. else
  8325. {
  8326. while (get() != 0xFF)
  8327. {
  8328. if (JSON_HEDLEY_UNLIKELY(!get_cbor_string(key) || !sax->key(key)))
  8329. {
  8330. return false;
  8331. }
  8332. if (JSON_HEDLEY_UNLIKELY(!parse_cbor_internal(true, tag_handler)))
  8333. {
  8334. return false;
  8335. }
  8336. key.clear();
  8337. }
  8338. }
  8339. }
  8340. return sax->end_object();
  8341. }
  8342. /////////////
  8343. // MsgPack //
  8344. /////////////
  8345. /*!
  8346. @return whether a valid MessagePack value was passed to the SAX parser
  8347. */
  8348. bool parse_msgpack_internal()
  8349. {
  8350. switch (get())
  8351. {
  8352. // EOF
  8353. case std::char_traits<char_type>::eof():
  8354. return unexpect_eof(input_format_t::msgpack, "value");
  8355. // positive fixint
  8356. case 0x00:
  8357. case 0x01:
  8358. case 0x02:
  8359. case 0x03:
  8360. case 0x04:
  8361. case 0x05:
  8362. case 0x06:
  8363. case 0x07:
  8364. case 0x08:
  8365. case 0x09:
  8366. case 0x0A:
  8367. case 0x0B:
  8368. case 0x0C:
  8369. case 0x0D:
  8370. case 0x0E:
  8371. case 0x0F:
  8372. case 0x10:
  8373. case 0x11:
  8374. case 0x12:
  8375. case 0x13:
  8376. case 0x14:
  8377. case 0x15:
  8378. case 0x16:
  8379. case 0x17:
  8380. case 0x18:
  8381. case 0x19:
  8382. case 0x1A:
  8383. case 0x1B:
  8384. case 0x1C:
  8385. case 0x1D:
  8386. case 0x1E:
  8387. case 0x1F:
  8388. case 0x20:
  8389. case 0x21:
  8390. case 0x22:
  8391. case 0x23:
  8392. case 0x24:
  8393. case 0x25:
  8394. case 0x26:
  8395. case 0x27:
  8396. case 0x28:
  8397. case 0x29:
  8398. case 0x2A:
  8399. case 0x2B:
  8400. case 0x2C:
  8401. case 0x2D:
  8402. case 0x2E:
  8403. case 0x2F:
  8404. case 0x30:
  8405. case 0x31:
  8406. case 0x32:
  8407. case 0x33:
  8408. case 0x34:
  8409. case 0x35:
  8410. case 0x36:
  8411. case 0x37:
  8412. case 0x38:
  8413. case 0x39:
  8414. case 0x3A:
  8415. case 0x3B:
  8416. case 0x3C:
  8417. case 0x3D:
  8418. case 0x3E:
  8419. case 0x3F:
  8420. case 0x40:
  8421. case 0x41:
  8422. case 0x42:
  8423. case 0x43:
  8424. case 0x44:
  8425. case 0x45:
  8426. case 0x46:
  8427. case 0x47:
  8428. case 0x48:
  8429. case 0x49:
  8430. case 0x4A:
  8431. case 0x4B:
  8432. case 0x4C:
  8433. case 0x4D:
  8434. case 0x4E:
  8435. case 0x4F:
  8436. case 0x50:
  8437. case 0x51:
  8438. case 0x52:
  8439. case 0x53:
  8440. case 0x54:
  8441. case 0x55:
  8442. case 0x56:
  8443. case 0x57:
  8444. case 0x58:
  8445. case 0x59:
  8446. case 0x5A:
  8447. case 0x5B:
  8448. case 0x5C:
  8449. case 0x5D:
  8450. case 0x5E:
  8451. case 0x5F:
  8452. case 0x60:
  8453. case 0x61:
  8454. case 0x62:
  8455. case 0x63:
  8456. case 0x64:
  8457. case 0x65:
  8458. case 0x66:
  8459. case 0x67:
  8460. case 0x68:
  8461. case 0x69:
  8462. case 0x6A:
  8463. case 0x6B:
  8464. case 0x6C:
  8465. case 0x6D:
  8466. case 0x6E:
  8467. case 0x6F:
  8468. case 0x70:
  8469. case 0x71:
  8470. case 0x72:
  8471. case 0x73:
  8472. case 0x74:
  8473. case 0x75:
  8474. case 0x76:
  8475. case 0x77:
  8476. case 0x78:
  8477. case 0x79:
  8478. case 0x7A:
  8479. case 0x7B:
  8480. case 0x7C:
  8481. case 0x7D:
  8482. case 0x7E:
  8483. case 0x7F:
  8484. return sax->number_unsigned(static_cast<number_unsigned_t>(current));
  8485. // fixmap
  8486. case 0x80:
  8487. case 0x81:
  8488. case 0x82:
  8489. case 0x83:
  8490. case 0x84:
  8491. case 0x85:
  8492. case 0x86:
  8493. case 0x87:
  8494. case 0x88:
  8495. case 0x89:
  8496. case 0x8A:
  8497. case 0x8B:
  8498. case 0x8C:
  8499. case 0x8D:
  8500. case 0x8E:
  8501. case 0x8F:
  8502. return get_msgpack_object(static_cast<std::size_t>(static_cast<unsigned int>(current) & 0x0Fu));
  8503. // fixarray
  8504. case 0x90:
  8505. case 0x91:
  8506. case 0x92:
  8507. case 0x93:
  8508. case 0x94:
  8509. case 0x95:
  8510. case 0x96:
  8511. case 0x97:
  8512. case 0x98:
  8513. case 0x99:
  8514. case 0x9A:
  8515. case 0x9B:
  8516. case 0x9C:
  8517. case 0x9D:
  8518. case 0x9E:
  8519. case 0x9F:
  8520. return get_msgpack_array(static_cast<std::size_t>(static_cast<unsigned int>(current) & 0x0Fu));
  8521. // fixstr
  8522. case 0xA0:
  8523. case 0xA1:
  8524. case 0xA2:
  8525. case 0xA3:
  8526. case 0xA4:
  8527. case 0xA5:
  8528. case 0xA6:
  8529. case 0xA7:
  8530. case 0xA8:
  8531. case 0xA9:
  8532. case 0xAA:
  8533. case 0xAB:
  8534. case 0xAC:
  8535. case 0xAD:
  8536. case 0xAE:
  8537. case 0xAF:
  8538. case 0xB0:
  8539. case 0xB1:
  8540. case 0xB2:
  8541. case 0xB3:
  8542. case 0xB4:
  8543. case 0xB5:
  8544. case 0xB6:
  8545. case 0xB7:
  8546. case 0xB8:
  8547. case 0xB9:
  8548. case 0xBA:
  8549. case 0xBB:
  8550. case 0xBC:
  8551. case 0xBD:
  8552. case 0xBE:
  8553. case 0xBF:
  8554. case 0xD9: // str 8
  8555. case 0xDA: // str 16
  8556. case 0xDB: // str 32
  8557. {
  8558. string_t s;
  8559. return get_msgpack_string(s) && sax->string(s);
  8560. }
  8561. case 0xC0: // nil
  8562. return sax->null();
  8563. case 0xC2: // false
  8564. return sax->boolean(false);
  8565. case 0xC3: // true
  8566. return sax->boolean(true);
  8567. case 0xC4: // bin 8
  8568. case 0xC5: // bin 16
  8569. case 0xC6: // bin 32
  8570. case 0xC7: // ext 8
  8571. case 0xC8: // ext 16
  8572. case 0xC9: // ext 32
  8573. case 0xD4: // fixext 1
  8574. case 0xD5: // fixext 2
  8575. case 0xD6: // fixext 4
  8576. case 0xD7: // fixext 8
  8577. case 0xD8: // fixext 16
  8578. {
  8579. binary_t b;
  8580. return get_msgpack_binary(b) && sax->binary(b);
  8581. }
  8582. case 0xCA: // float 32
  8583. {
  8584. float number{};
  8585. return get_number(input_format_t::msgpack, number) && sax->number_float(static_cast<number_float_t>(number), "");
  8586. }
  8587. case 0xCB: // float 64
  8588. {
  8589. double number{};
  8590. return get_number(input_format_t::msgpack, number) && sax->number_float(static_cast<number_float_t>(number), "");
  8591. }
  8592. case 0xCC: // uint 8
  8593. {
  8594. std::uint8_t number{};
  8595. return get_number(input_format_t::msgpack, number) && sax->number_unsigned(number);
  8596. }
  8597. case 0xCD: // uint 16
  8598. {
  8599. std::uint16_t number{};
  8600. return get_number(input_format_t::msgpack, number) && sax->number_unsigned(number);
  8601. }
  8602. case 0xCE: // uint 32
  8603. {
  8604. std::uint32_t number{};
  8605. return get_number(input_format_t::msgpack, number) && sax->number_unsigned(number);
  8606. }
  8607. case 0xCF: // uint 64
  8608. {
  8609. std::uint64_t number{};
  8610. return get_number(input_format_t::msgpack, number) && sax->number_unsigned(number);
  8611. }
  8612. case 0xD0: // int 8
  8613. {
  8614. std::int8_t number{};
  8615. return get_number(input_format_t::msgpack, number) && sax->number_integer(number);
  8616. }
  8617. case 0xD1: // int 16
  8618. {
  8619. std::int16_t number{};
  8620. return get_number(input_format_t::msgpack, number) && sax->number_integer(number);
  8621. }
  8622. case 0xD2: // int 32
  8623. {
  8624. std::int32_t number{};
  8625. return get_number(input_format_t::msgpack, number) && sax->number_integer(number);
  8626. }
  8627. case 0xD3: // int 64
  8628. {
  8629. std::int64_t number{};
  8630. return get_number(input_format_t::msgpack, number) && sax->number_integer(number);
  8631. }
  8632. case 0xDC: // array 16
  8633. {
  8634. std::uint16_t len{};
  8635. return get_number(input_format_t::msgpack, len) && get_msgpack_array(static_cast<std::size_t>(len));
  8636. }
  8637. case 0xDD: // array 32
  8638. {
  8639. std::uint32_t len{};
  8640. return get_number(input_format_t::msgpack, len) && get_msgpack_array(static_cast<std::size_t>(len));
  8641. }
  8642. case 0xDE: // map 16
  8643. {
  8644. std::uint16_t len{};
  8645. return get_number(input_format_t::msgpack, len) && get_msgpack_object(static_cast<std::size_t>(len));
  8646. }
  8647. case 0xDF: // map 32
  8648. {
  8649. std::uint32_t len{};
  8650. return get_number(input_format_t::msgpack, len) && get_msgpack_object(static_cast<std::size_t>(len));
  8651. }
  8652. // negative fixint
  8653. case 0xE0:
  8654. case 0xE1:
  8655. case 0xE2:
  8656. case 0xE3:
  8657. case 0xE4:
  8658. case 0xE5:
  8659. case 0xE6:
  8660. case 0xE7:
  8661. case 0xE8:
  8662. case 0xE9:
  8663. case 0xEA:
  8664. case 0xEB:
  8665. case 0xEC:
  8666. case 0xED:
  8667. case 0xEE:
  8668. case 0xEF:
  8669. case 0xF0:
  8670. case 0xF1:
  8671. case 0xF2:
  8672. case 0xF3:
  8673. case 0xF4:
  8674. case 0xF5:
  8675. case 0xF6:
  8676. case 0xF7:
  8677. case 0xF8:
  8678. case 0xF9:
  8679. case 0xFA:
  8680. case 0xFB:
  8681. case 0xFC:
  8682. case 0xFD:
  8683. case 0xFE:
  8684. case 0xFF:
  8685. return sax->number_integer(static_cast<std::int8_t>(current));
  8686. default: // anything else
  8687. {
  8688. auto last_token = get_token_string();
  8689. 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"), BasicJsonType()));
  8690. }
  8691. }
  8692. }
  8693. /*!
  8694. @brief reads a MessagePack string
  8695. This function first reads starting bytes to determine the expected
  8696. string length and then copies this number of bytes into a string.
  8697. @param[out] result created string
  8698. @return whether string creation completed
  8699. */
  8700. bool get_msgpack_string(string_t& result)
  8701. {
  8702. if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(input_format_t::msgpack, "string")))
  8703. {
  8704. return false;
  8705. }
  8706. switch (current)
  8707. {
  8708. // fixstr
  8709. case 0xA0:
  8710. case 0xA1:
  8711. case 0xA2:
  8712. case 0xA3:
  8713. case 0xA4:
  8714. case 0xA5:
  8715. case 0xA6:
  8716. case 0xA7:
  8717. case 0xA8:
  8718. case 0xA9:
  8719. case 0xAA:
  8720. case 0xAB:
  8721. case 0xAC:
  8722. case 0xAD:
  8723. case 0xAE:
  8724. case 0xAF:
  8725. case 0xB0:
  8726. case 0xB1:
  8727. case 0xB2:
  8728. case 0xB3:
  8729. case 0xB4:
  8730. case 0xB5:
  8731. case 0xB6:
  8732. case 0xB7:
  8733. case 0xB8:
  8734. case 0xB9:
  8735. case 0xBA:
  8736. case 0xBB:
  8737. case 0xBC:
  8738. case 0xBD:
  8739. case 0xBE:
  8740. case 0xBF:
  8741. {
  8742. return get_string(input_format_t::msgpack, static_cast<unsigned int>(current) & 0x1Fu, result);
  8743. }
  8744. case 0xD9: // str 8
  8745. {
  8746. std::uint8_t len{};
  8747. return get_number(input_format_t::msgpack, len) && get_string(input_format_t::msgpack, len, result);
  8748. }
  8749. case 0xDA: // str 16
  8750. {
  8751. std::uint16_t len{};
  8752. return get_number(input_format_t::msgpack, len) && get_string(input_format_t::msgpack, len, result);
  8753. }
  8754. case 0xDB: // str 32
  8755. {
  8756. std::uint32_t len{};
  8757. return get_number(input_format_t::msgpack, len) && get_string(input_format_t::msgpack, len, result);
  8758. }
  8759. default:
  8760. {
  8761. auto last_token = get_token_string();
  8762. 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"), BasicJsonType()));
  8763. }
  8764. }
  8765. }
  8766. /*!
  8767. @brief reads a MessagePack byte array
  8768. This function first reads starting bytes to determine the expected
  8769. byte array length and then copies this number of bytes into a byte array.
  8770. @param[out] result created byte array
  8771. @return whether byte array creation completed
  8772. */
  8773. bool get_msgpack_binary(binary_t& result)
  8774. {
  8775. // helper function to set the subtype
  8776. auto assign_and_return_true = [&result](std::int8_t subtype)
  8777. {
  8778. result.set_subtype(static_cast<std::uint8_t>(subtype));
  8779. return true;
  8780. };
  8781. switch (current)
  8782. {
  8783. case 0xC4: // bin 8
  8784. {
  8785. std::uint8_t len{};
  8786. return get_number(input_format_t::msgpack, len) &&
  8787. get_binary(input_format_t::msgpack, len, result);
  8788. }
  8789. case 0xC5: // bin 16
  8790. {
  8791. std::uint16_t len{};
  8792. return get_number(input_format_t::msgpack, len) &&
  8793. get_binary(input_format_t::msgpack, len, result);
  8794. }
  8795. case 0xC6: // bin 32
  8796. {
  8797. std::uint32_t len{};
  8798. return get_number(input_format_t::msgpack, len) &&
  8799. get_binary(input_format_t::msgpack, len, result);
  8800. }
  8801. case 0xC7: // ext 8
  8802. {
  8803. std::uint8_t len{};
  8804. std::int8_t subtype{};
  8805. return get_number(input_format_t::msgpack, len) &&
  8806. get_number(input_format_t::msgpack, subtype) &&
  8807. get_binary(input_format_t::msgpack, len, result) &&
  8808. assign_and_return_true(subtype);
  8809. }
  8810. case 0xC8: // ext 16
  8811. {
  8812. std::uint16_t len{};
  8813. std::int8_t subtype{};
  8814. return get_number(input_format_t::msgpack, len) &&
  8815. get_number(input_format_t::msgpack, subtype) &&
  8816. get_binary(input_format_t::msgpack, len, result) &&
  8817. assign_and_return_true(subtype);
  8818. }
  8819. case 0xC9: // ext 32
  8820. {
  8821. std::uint32_t len{};
  8822. std::int8_t subtype{};
  8823. return get_number(input_format_t::msgpack, len) &&
  8824. get_number(input_format_t::msgpack, subtype) &&
  8825. get_binary(input_format_t::msgpack, len, result) &&
  8826. assign_and_return_true(subtype);
  8827. }
  8828. case 0xD4: // fixext 1
  8829. {
  8830. std::int8_t subtype{};
  8831. return get_number(input_format_t::msgpack, subtype) &&
  8832. get_binary(input_format_t::msgpack, 1, result) &&
  8833. assign_and_return_true(subtype);
  8834. }
  8835. case 0xD5: // fixext 2
  8836. {
  8837. std::int8_t subtype{};
  8838. return get_number(input_format_t::msgpack, subtype) &&
  8839. get_binary(input_format_t::msgpack, 2, result) &&
  8840. assign_and_return_true(subtype);
  8841. }
  8842. case 0xD6: // fixext 4
  8843. {
  8844. std::int8_t subtype{};
  8845. return get_number(input_format_t::msgpack, subtype) &&
  8846. get_binary(input_format_t::msgpack, 4, result) &&
  8847. assign_and_return_true(subtype);
  8848. }
  8849. case 0xD7: // fixext 8
  8850. {
  8851. std::int8_t subtype{};
  8852. return get_number(input_format_t::msgpack, subtype) &&
  8853. get_binary(input_format_t::msgpack, 8, result) &&
  8854. assign_and_return_true(subtype);
  8855. }
  8856. case 0xD8: // fixext 16
  8857. {
  8858. std::int8_t subtype{};
  8859. return get_number(input_format_t::msgpack, subtype) &&
  8860. get_binary(input_format_t::msgpack, 16, result) &&
  8861. assign_and_return_true(subtype);
  8862. }
  8863. default: // LCOV_EXCL_LINE
  8864. return false; // LCOV_EXCL_LINE
  8865. }
  8866. }
  8867. /*!
  8868. @param[in] len the length of the array
  8869. @return whether array creation completed
  8870. */
  8871. bool get_msgpack_array(const std::size_t len)
  8872. {
  8873. if (JSON_HEDLEY_UNLIKELY(!sax->start_array(len)))
  8874. {
  8875. return false;
  8876. }
  8877. for (std::size_t i = 0; i < len; ++i)
  8878. {
  8879. if (JSON_HEDLEY_UNLIKELY(!parse_msgpack_internal()))
  8880. {
  8881. return false;
  8882. }
  8883. }
  8884. return sax->end_array();
  8885. }
  8886. /*!
  8887. @param[in] len the length of the object
  8888. @return whether object creation completed
  8889. */
  8890. bool get_msgpack_object(const std::size_t len)
  8891. {
  8892. if (JSON_HEDLEY_UNLIKELY(!sax->start_object(len)))
  8893. {
  8894. return false;
  8895. }
  8896. string_t key;
  8897. for (std::size_t i = 0; i < len; ++i)
  8898. {
  8899. get();
  8900. if (JSON_HEDLEY_UNLIKELY(!get_msgpack_string(key) || !sax->key(key)))
  8901. {
  8902. return false;
  8903. }
  8904. if (JSON_HEDLEY_UNLIKELY(!parse_msgpack_internal()))
  8905. {
  8906. return false;
  8907. }
  8908. key.clear();
  8909. }
  8910. return sax->end_object();
  8911. }
  8912. ////////////
  8913. // UBJSON //
  8914. ////////////
  8915. /*!
  8916. @param[in] get_char whether a new character should be retrieved from the
  8917. input (true, default) or whether the last read
  8918. character should be considered instead
  8919. @return whether a valid UBJSON value was passed to the SAX parser
  8920. */
  8921. bool parse_ubjson_internal(const bool get_char = true)
  8922. {
  8923. return get_ubjson_value(get_char ? get_ignore_noop() : current);
  8924. }
  8925. /*!
  8926. @brief reads a UBJSON string
  8927. This function is either called after reading the 'S' byte explicitly
  8928. indicating a string, or in case of an object key where the 'S' byte can be
  8929. left out.
  8930. @param[out] result created string
  8931. @param[in] get_char whether a new character should be retrieved from the
  8932. input (true, default) or whether the last read
  8933. character should be considered instead
  8934. @return whether string creation completed
  8935. */
  8936. bool get_ubjson_string(string_t& result, const bool get_char = true)
  8937. {
  8938. if (get_char)
  8939. {
  8940. get(); // TODO(niels): may we ignore N here?
  8941. }
  8942. if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(input_format_t::ubjson, "value")))
  8943. {
  8944. return false;
  8945. }
  8946. switch (current)
  8947. {
  8948. case 'U':
  8949. {
  8950. std::uint8_t len{};
  8951. return get_number(input_format_t::ubjson, len) && get_string(input_format_t::ubjson, len, result);
  8952. }
  8953. case 'i':
  8954. {
  8955. std::int8_t len{};
  8956. return get_number(input_format_t::ubjson, len) && get_string(input_format_t::ubjson, len, result);
  8957. }
  8958. case 'I':
  8959. {
  8960. std::int16_t len{};
  8961. return get_number(input_format_t::ubjson, len) && get_string(input_format_t::ubjson, len, result);
  8962. }
  8963. case 'l':
  8964. {
  8965. std::int32_t len{};
  8966. return get_number(input_format_t::ubjson, len) && get_string(input_format_t::ubjson, len, result);
  8967. }
  8968. case 'L':
  8969. {
  8970. std::int64_t len{};
  8971. return get_number(input_format_t::ubjson, len) && get_string(input_format_t::ubjson, len, result);
  8972. }
  8973. default:
  8974. auto last_token = get_token_string();
  8975. 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"), BasicJsonType()));
  8976. }
  8977. }
  8978. /*!
  8979. @param[out] result determined size
  8980. @return whether size determination completed
  8981. */
  8982. bool get_ubjson_size_value(std::size_t& result)
  8983. {
  8984. switch (get_ignore_noop())
  8985. {
  8986. case 'U':
  8987. {
  8988. std::uint8_t number{};
  8989. if (JSON_HEDLEY_UNLIKELY(!get_number(input_format_t::ubjson, number)))
  8990. {
  8991. return false;
  8992. }
  8993. result = static_cast<std::size_t>(number);
  8994. return true;
  8995. }
  8996. case 'i':
  8997. {
  8998. std::int8_t number{};
  8999. if (JSON_HEDLEY_UNLIKELY(!get_number(input_format_t::ubjson, number)))
  9000. {
  9001. return false;
  9002. }
  9003. result = static_cast<std::size_t>(number); // NOLINT(bugprone-signed-char-misuse,cert-str34-c): number is not a char
  9004. return true;
  9005. }
  9006. case 'I':
  9007. {
  9008. std::int16_t number{};
  9009. if (JSON_HEDLEY_UNLIKELY(!get_number(input_format_t::ubjson, number)))
  9010. {
  9011. return false;
  9012. }
  9013. result = static_cast<std::size_t>(number);
  9014. return true;
  9015. }
  9016. case 'l':
  9017. {
  9018. std::int32_t number{};
  9019. if (JSON_HEDLEY_UNLIKELY(!get_number(input_format_t::ubjson, number)))
  9020. {
  9021. return false;
  9022. }
  9023. result = static_cast<std::size_t>(number);
  9024. return true;
  9025. }
  9026. case 'L':
  9027. {
  9028. std::int64_t number{};
  9029. if (JSON_HEDLEY_UNLIKELY(!get_number(input_format_t::ubjson, number)))
  9030. {
  9031. return false;
  9032. }
  9033. result = static_cast<std::size_t>(number);
  9034. return true;
  9035. }
  9036. default:
  9037. {
  9038. auto last_token = get_token_string();
  9039. 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"), BasicJsonType()));
  9040. }
  9041. }
  9042. }
  9043. /*!
  9044. @brief determine the type and size for a container
  9045. In the optimized UBJSON format, a type and a size can be provided to allow
  9046. for a more compact representation.
  9047. @param[out] result pair of the size and the type
  9048. @return whether pair creation completed
  9049. */
  9050. bool get_ubjson_size_type(std::pair<std::size_t, char_int_type>& result)
  9051. {
  9052. result.first = string_t::npos; // size
  9053. result.second = 0; // type
  9054. get_ignore_noop();
  9055. if (current == '$')
  9056. {
  9057. result.second = get(); // must not ignore 'N', because 'N' maybe the type
  9058. if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(input_format_t::ubjson, "type")))
  9059. {
  9060. return false;
  9061. }
  9062. get_ignore_noop();
  9063. if (JSON_HEDLEY_UNLIKELY(current != '#'))
  9064. {
  9065. if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(input_format_t::ubjson, "value")))
  9066. {
  9067. return false;
  9068. }
  9069. auto last_token = get_token_string();
  9070. 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"), BasicJsonType()));
  9071. }
  9072. return get_ubjson_size_value(result.first);
  9073. }
  9074. if (current == '#')
  9075. {
  9076. return get_ubjson_size_value(result.first);
  9077. }
  9078. return true;
  9079. }
  9080. /*!
  9081. @param prefix the previously read or set type prefix
  9082. @return whether value creation completed
  9083. */
  9084. bool get_ubjson_value(const char_int_type prefix)
  9085. {
  9086. switch (prefix)
  9087. {
  9088. case std::char_traits<char_type>::eof(): // EOF
  9089. return unexpect_eof(input_format_t::ubjson, "value");
  9090. case 'T': // true
  9091. return sax->boolean(true);
  9092. case 'F': // false
  9093. return sax->boolean(false);
  9094. case 'Z': // null
  9095. return sax->null();
  9096. case 'U':
  9097. {
  9098. std::uint8_t number{};
  9099. return get_number(input_format_t::ubjson, number) && sax->number_unsigned(number);
  9100. }
  9101. case 'i':
  9102. {
  9103. std::int8_t number{};
  9104. return get_number(input_format_t::ubjson, number) && sax->number_integer(number);
  9105. }
  9106. case 'I':
  9107. {
  9108. std::int16_t number{};
  9109. return get_number(input_format_t::ubjson, number) && sax->number_integer(number);
  9110. }
  9111. case 'l':
  9112. {
  9113. std::int32_t number{};
  9114. return get_number(input_format_t::ubjson, number) && sax->number_integer(number);
  9115. }
  9116. case 'L':
  9117. {
  9118. std::int64_t number{};
  9119. return get_number(input_format_t::ubjson, number) && sax->number_integer(number);
  9120. }
  9121. case 'd':
  9122. {
  9123. float number{};
  9124. return get_number(input_format_t::ubjson, number) && sax->number_float(static_cast<number_float_t>(number), "");
  9125. }
  9126. case 'D':
  9127. {
  9128. double number{};
  9129. return get_number(input_format_t::ubjson, number) && sax->number_float(static_cast<number_float_t>(number), "");
  9130. }
  9131. case 'H':
  9132. {
  9133. return get_ubjson_high_precision_number();
  9134. }
  9135. case 'C': // char
  9136. {
  9137. get();
  9138. if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(input_format_t::ubjson, "char")))
  9139. {
  9140. return false;
  9141. }
  9142. if (JSON_HEDLEY_UNLIKELY(current > 127))
  9143. {
  9144. auto last_token = get_token_string();
  9145. 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"), BasicJsonType()));
  9146. }
  9147. string_t s(1, static_cast<typename string_t::value_type>(current));
  9148. return sax->string(s);
  9149. }
  9150. case 'S': // string
  9151. {
  9152. string_t s;
  9153. return get_ubjson_string(s) && sax->string(s);
  9154. }
  9155. case '[': // array
  9156. return get_ubjson_array();
  9157. case '{': // object
  9158. return get_ubjson_object();
  9159. default: // anything else
  9160. {
  9161. auto last_token = get_token_string();
  9162. 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"), BasicJsonType()));
  9163. }
  9164. }
  9165. }
  9166. /*!
  9167. @return whether array creation completed
  9168. */
  9169. bool get_ubjson_array()
  9170. {
  9171. std::pair<std::size_t, char_int_type> size_and_type;
  9172. if (JSON_HEDLEY_UNLIKELY(!get_ubjson_size_type(size_and_type)))
  9173. {
  9174. return false;
  9175. }
  9176. if (size_and_type.first != string_t::npos)
  9177. {
  9178. if (JSON_HEDLEY_UNLIKELY(!sax->start_array(size_and_type.first)))
  9179. {
  9180. return false;
  9181. }
  9182. if (size_and_type.second != 0)
  9183. {
  9184. if (size_and_type.second != 'N')
  9185. {
  9186. for (std::size_t i = 0; i < size_and_type.first; ++i)
  9187. {
  9188. if (JSON_HEDLEY_UNLIKELY(!get_ubjson_value(size_and_type.second)))
  9189. {
  9190. return false;
  9191. }
  9192. }
  9193. }
  9194. }
  9195. else
  9196. {
  9197. for (std::size_t i = 0; i < size_and_type.first; ++i)
  9198. {
  9199. if (JSON_HEDLEY_UNLIKELY(!parse_ubjson_internal()))
  9200. {
  9201. return false;
  9202. }
  9203. }
  9204. }
  9205. }
  9206. else
  9207. {
  9208. if (JSON_HEDLEY_UNLIKELY(!sax->start_array(std::size_t(-1))))
  9209. {
  9210. return false;
  9211. }
  9212. while (current != ']')
  9213. {
  9214. if (JSON_HEDLEY_UNLIKELY(!parse_ubjson_internal(false)))
  9215. {
  9216. return false;
  9217. }
  9218. get_ignore_noop();
  9219. }
  9220. }
  9221. return sax->end_array();
  9222. }
  9223. /*!
  9224. @return whether object creation completed
  9225. */
  9226. bool get_ubjson_object()
  9227. {
  9228. std::pair<std::size_t, char_int_type> size_and_type;
  9229. if (JSON_HEDLEY_UNLIKELY(!get_ubjson_size_type(size_and_type)))
  9230. {
  9231. return false;
  9232. }
  9233. string_t key;
  9234. if (size_and_type.first != string_t::npos)
  9235. {
  9236. if (JSON_HEDLEY_UNLIKELY(!sax->start_object(size_and_type.first)))
  9237. {
  9238. return false;
  9239. }
  9240. if (size_and_type.second != 0)
  9241. {
  9242. for (std::size_t i = 0; i < size_and_type.first; ++i)
  9243. {
  9244. if (JSON_HEDLEY_UNLIKELY(!get_ubjson_string(key) || !sax->key(key)))
  9245. {
  9246. return false;
  9247. }
  9248. if (JSON_HEDLEY_UNLIKELY(!get_ubjson_value(size_and_type.second)))
  9249. {
  9250. return false;
  9251. }
  9252. key.clear();
  9253. }
  9254. }
  9255. else
  9256. {
  9257. for (std::size_t i = 0; i < size_and_type.first; ++i)
  9258. {
  9259. if (JSON_HEDLEY_UNLIKELY(!get_ubjson_string(key) || !sax->key(key)))
  9260. {
  9261. return false;
  9262. }
  9263. if (JSON_HEDLEY_UNLIKELY(!parse_ubjson_internal()))
  9264. {
  9265. return false;
  9266. }
  9267. key.clear();
  9268. }
  9269. }
  9270. }
  9271. else
  9272. {
  9273. if (JSON_HEDLEY_UNLIKELY(!sax->start_object(std::size_t(-1))))
  9274. {
  9275. return false;
  9276. }
  9277. while (current != '}')
  9278. {
  9279. if (JSON_HEDLEY_UNLIKELY(!get_ubjson_string(key, false) || !sax->key(key)))
  9280. {
  9281. return false;
  9282. }
  9283. if (JSON_HEDLEY_UNLIKELY(!parse_ubjson_internal()))
  9284. {
  9285. return false;
  9286. }
  9287. get_ignore_noop();
  9288. key.clear();
  9289. }
  9290. }
  9291. return sax->end_object();
  9292. }
  9293. // Note, no reader for UBJSON binary types is implemented because they do
  9294. // not exist
  9295. bool get_ubjson_high_precision_number()
  9296. {
  9297. // get size of following number string
  9298. std::size_t size{};
  9299. auto res = get_ubjson_size_value(size);
  9300. if (JSON_HEDLEY_UNLIKELY(!res))
  9301. {
  9302. return res;
  9303. }
  9304. // get number string
  9305. std::vector<char> number_vector;
  9306. for (std::size_t i = 0; i < size; ++i)
  9307. {
  9308. get();
  9309. if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(input_format_t::ubjson, "number")))
  9310. {
  9311. return false;
  9312. }
  9313. number_vector.push_back(static_cast<char>(current));
  9314. }
  9315. // parse number string
  9316. using ia_type = decltype(detail::input_adapter(number_vector));
  9317. auto number_lexer = detail::lexer<BasicJsonType, ia_type>(detail::input_adapter(number_vector), false);
  9318. const auto result_number = number_lexer.scan();
  9319. const auto number_string = number_lexer.get_token_string();
  9320. const auto result_remainder = number_lexer.scan();
  9321. using token_type = typename detail::lexer_base<BasicJsonType>::token_type;
  9322. if (JSON_HEDLEY_UNLIKELY(result_remainder != token_type::end_of_input))
  9323. {
  9324. return sax->parse_error(chars_read, number_string, parse_error::create(115, chars_read, exception_message(input_format_t::ubjson, "invalid number text: " + number_lexer.get_token_string(), "high-precision number"), BasicJsonType()));
  9325. }
  9326. switch (result_number)
  9327. {
  9328. case token_type::value_integer:
  9329. return sax->number_integer(number_lexer.get_number_integer());
  9330. case token_type::value_unsigned:
  9331. return sax->number_unsigned(number_lexer.get_number_unsigned());
  9332. case token_type::value_float:
  9333. return sax->number_float(number_lexer.get_number_float(), std::move(number_string));
  9334. case token_type::uninitialized:
  9335. case token_type::literal_true:
  9336. case token_type::literal_false:
  9337. case token_type::literal_null:
  9338. case token_type::value_string:
  9339. case token_type::begin_array:
  9340. case token_type::begin_object:
  9341. case token_type::end_array:
  9342. case token_type::end_object:
  9343. case token_type::name_separator:
  9344. case token_type::value_separator:
  9345. case token_type::parse_error:
  9346. case token_type::end_of_input:
  9347. case token_type::literal_or_value:
  9348. default:
  9349. return sax->parse_error(chars_read, number_string, parse_error::create(115, chars_read, exception_message(input_format_t::ubjson, "invalid number text: " + number_lexer.get_token_string(), "high-precision number"), BasicJsonType()));
  9350. }
  9351. }
  9352. ///////////////////////
  9353. // Utility functions //
  9354. ///////////////////////
  9355. /*!
  9356. @brief get next character from the input
  9357. This function provides the interface to the used input adapter. It does
  9358. not throw in case the input reached EOF, but returns a -'ve valued
  9359. `std::char_traits<char_type>::eof()` in that case.
  9360. @return character read from the input
  9361. */
  9362. char_int_type get()
  9363. {
  9364. ++chars_read;
  9365. return current = ia.get_character();
  9366. }
  9367. /*!
  9368. @return character read from the input after ignoring all 'N' entries
  9369. */
  9370. char_int_type get_ignore_noop()
  9371. {
  9372. do
  9373. {
  9374. get();
  9375. }
  9376. while (current == 'N');
  9377. return current;
  9378. }
  9379. /*
  9380. @brief read a number from the input
  9381. @tparam NumberType the type of the number
  9382. @param[in] format the current format (for diagnostics)
  9383. @param[out] result number of type @a NumberType
  9384. @return whether conversion completed
  9385. @note This function needs to respect the system's endianess, because
  9386. bytes in CBOR, MessagePack, and UBJSON are stored in network order
  9387. (big endian) and therefore need reordering on little endian systems.
  9388. */
  9389. template<typename NumberType, bool InputIsLittleEndian = false>
  9390. bool get_number(const input_format_t format, NumberType& result)
  9391. {
  9392. // step 1: read input into array with system's byte order
  9393. std::array<std::uint8_t, sizeof(NumberType)> vec{};
  9394. for (std::size_t i = 0; i < sizeof(NumberType); ++i)
  9395. {
  9396. get();
  9397. if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(format, "number")))
  9398. {
  9399. return false;
  9400. }
  9401. // reverse byte order prior to conversion if necessary
  9402. if (is_little_endian != InputIsLittleEndian)
  9403. {
  9404. vec[sizeof(NumberType) - i - 1] = static_cast<std::uint8_t>(current);
  9405. }
  9406. else
  9407. {
  9408. vec[i] = static_cast<std::uint8_t>(current); // LCOV_EXCL_LINE
  9409. }
  9410. }
  9411. // step 2: convert array into number of type T and return
  9412. std::memcpy(&result, vec.data(), sizeof(NumberType));
  9413. return true;
  9414. }
  9415. /*!
  9416. @brief create a string by reading characters from the input
  9417. @tparam NumberType the type of the number
  9418. @param[in] format the current format (for diagnostics)
  9419. @param[in] len number of characters to read
  9420. @param[out] result string created by reading @a len bytes
  9421. @return whether string creation completed
  9422. @note We can not reserve @a len bytes for the result, because @a len
  9423. may be too large. Usually, @ref unexpect_eof() detects the end of
  9424. the input before we run out of string memory.
  9425. */
  9426. template<typename NumberType>
  9427. bool get_string(const input_format_t format,
  9428. const NumberType len,
  9429. string_t& result)
  9430. {
  9431. bool success = true;
  9432. for (NumberType i = 0; i < len; i++)
  9433. {
  9434. get();
  9435. if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(format, "string")))
  9436. {
  9437. success = false;
  9438. break;
  9439. }
  9440. result.push_back(static_cast<typename string_t::value_type>(current));
  9441. }
  9442. return success;
  9443. }
  9444. /*!
  9445. @brief create a byte array by reading bytes from the input
  9446. @tparam NumberType the type of the number
  9447. @param[in] format the current format (for diagnostics)
  9448. @param[in] len number of bytes to read
  9449. @param[out] result byte array created by reading @a len bytes
  9450. @return whether byte array creation completed
  9451. @note We can not reserve @a len bytes for the result, because @a len
  9452. may be too large. Usually, @ref unexpect_eof() detects the end of
  9453. the input before we run out of memory.
  9454. */
  9455. template<typename NumberType>
  9456. bool get_binary(const input_format_t format,
  9457. const NumberType len,
  9458. binary_t& result)
  9459. {
  9460. bool success = true;
  9461. for (NumberType i = 0; i < len; i++)
  9462. {
  9463. get();
  9464. if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(format, "binary")))
  9465. {
  9466. success = false;
  9467. break;
  9468. }
  9469. result.push_back(static_cast<std::uint8_t>(current));
  9470. }
  9471. return success;
  9472. }
  9473. /*!
  9474. @param[in] format the current format (for diagnostics)
  9475. @param[in] context further context information (for diagnostics)
  9476. @return whether the last read character is not EOF
  9477. */
  9478. JSON_HEDLEY_NON_NULL(3)
  9479. bool unexpect_eof(const input_format_t format, const char* context) const
  9480. {
  9481. if (JSON_HEDLEY_UNLIKELY(current == std::char_traits<char_type>::eof()))
  9482. {
  9483. return sax->parse_error(chars_read, "<end of file>",
  9484. parse_error::create(110, chars_read, exception_message(format, "unexpected end of input", context), BasicJsonType()));
  9485. }
  9486. return true;
  9487. }
  9488. /*!
  9489. @return a string representation of the last read byte
  9490. */
  9491. std::string get_token_string() const
  9492. {
  9493. std::array<char, 3> cr{{}};
  9494. (std::snprintf)(cr.data(), cr.size(), "%.2hhX", static_cast<unsigned char>(current)); // NOLINT(cppcoreguidelines-pro-type-vararg,hicpp-vararg)
  9495. return std::string{cr.data()};
  9496. }
  9497. /*!
  9498. @param[in] format the current format
  9499. @param[in] detail a detailed error message
  9500. @param[in] context further context information
  9501. @return a message string to use in the parse_error exceptions
  9502. */
  9503. std::string exception_message(const input_format_t format,
  9504. const std::string& detail,
  9505. const std::string& context) const
  9506. {
  9507. std::string error_msg = "syntax error while parsing ";
  9508. switch (format)
  9509. {
  9510. case input_format_t::cbor:
  9511. error_msg += "CBOR";
  9512. break;
  9513. case input_format_t::msgpack:
  9514. error_msg += "MessagePack";
  9515. break;
  9516. case input_format_t::ubjson:
  9517. error_msg += "UBJSON";
  9518. break;
  9519. case input_format_t::bson:
  9520. error_msg += "BSON";
  9521. break;
  9522. case input_format_t::json: // LCOV_EXCL_LINE
  9523. default: // LCOV_EXCL_LINE
  9524. JSON_ASSERT(false); // NOLINT(cert-dcl03-c,hicpp-static-assert,misc-static-assert) LCOV_EXCL_LINE
  9525. }
  9526. return error_msg + " " + context + ": " + detail;
  9527. }
  9528. private:
  9529. /// input adapter
  9530. InputAdapterType ia;
  9531. /// the current character
  9532. char_int_type current = std::char_traits<char_type>::eof();
  9533. /// the number of characters read
  9534. std::size_t chars_read = 0;
  9535. /// whether we can assume little endianess
  9536. const bool is_little_endian = little_endianess();
  9537. /// the SAX parser
  9538. json_sax_t* sax = nullptr;
  9539. };
  9540. } // namespace detail
  9541. } // namespace nlohmann
  9542. // #include <nlohmann/detail/input/input_adapters.hpp>
  9543. // #include <nlohmann/detail/input/lexer.hpp>
  9544. // #include <nlohmann/detail/input/parser.hpp>
  9545. #include <cmath> // isfinite
  9546. #include <cstdint> // uint8_t
  9547. #include <functional> // function
  9548. #include <string> // string
  9549. #include <utility> // move
  9550. #include <vector> // vector
  9551. // #include <nlohmann/detail/exceptions.hpp>
  9552. // #include <nlohmann/detail/input/input_adapters.hpp>
  9553. // #include <nlohmann/detail/input/json_sax.hpp>
  9554. // #include <nlohmann/detail/input/lexer.hpp>
  9555. // #include <nlohmann/detail/macro_scope.hpp>
  9556. // #include <nlohmann/detail/meta/is_sax.hpp>
  9557. // #include <nlohmann/detail/value_t.hpp>
  9558. namespace nlohmann
  9559. {
  9560. namespace detail
  9561. {
  9562. ////////////
  9563. // parser //
  9564. ////////////
  9565. enum class parse_event_t : std::uint8_t
  9566. {
  9567. /// the parser read `{` and started to process a JSON object
  9568. object_start,
  9569. /// the parser read `}` and finished processing a JSON object
  9570. object_end,
  9571. /// the parser read `[` and started to process a JSON array
  9572. array_start,
  9573. /// the parser read `]` and finished processing a JSON array
  9574. array_end,
  9575. /// the parser read a key of a value in an object
  9576. key,
  9577. /// the parser finished reading a JSON value
  9578. value
  9579. };
  9580. template<typename BasicJsonType>
  9581. using parser_callback_t =
  9582. std::function<bool(int /*depth*/, parse_event_t /*event*/, BasicJsonType& /*parsed*/)>;
  9583. /*!
  9584. @brief syntax analysis
  9585. This class implements a recursive descent parser.
  9586. */
  9587. template<typename BasicJsonType, typename InputAdapterType>
  9588. class parser
  9589. {
  9590. using number_integer_t = typename BasicJsonType::number_integer_t;
  9591. using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
  9592. using number_float_t = typename BasicJsonType::number_float_t;
  9593. using string_t = typename BasicJsonType::string_t;
  9594. using lexer_t = lexer<BasicJsonType, InputAdapterType>;
  9595. using token_type = typename lexer_t::token_type;
  9596. public:
  9597. /// a parser reading from an input adapter
  9598. explicit parser(InputAdapterType&& adapter,
  9599. const parser_callback_t<BasicJsonType> cb = nullptr,
  9600. const bool allow_exceptions_ = true,
  9601. const bool skip_comments = false)
  9602. : callback(cb)
  9603. , m_lexer(std::move(adapter), skip_comments)
  9604. , allow_exceptions(allow_exceptions_)
  9605. {
  9606. // read first token
  9607. get_token();
  9608. }
  9609. /*!
  9610. @brief public parser interface
  9611. @param[in] strict whether to expect the last token to be EOF
  9612. @param[in,out] result parsed JSON value
  9613. @throw parse_error.101 in case of an unexpected token
  9614. @throw parse_error.102 if to_unicode fails or surrogate error
  9615. @throw parse_error.103 if to_unicode fails
  9616. */
  9617. void parse(const bool strict, BasicJsonType& result)
  9618. {
  9619. if (callback)
  9620. {
  9621. json_sax_dom_callback_parser<BasicJsonType> sdp(result, callback, allow_exceptions);
  9622. sax_parse_internal(&sdp);
  9623. // in strict mode, input must be completely read
  9624. if (strict && (get_token() != token_type::end_of_input))
  9625. {
  9626. sdp.parse_error(m_lexer.get_position(),
  9627. m_lexer.get_token_string(),
  9628. parse_error::create(101, m_lexer.get_position(),
  9629. exception_message(token_type::end_of_input, "value"), BasicJsonType()));
  9630. }
  9631. // in case of an error, return discarded value
  9632. if (sdp.is_errored())
  9633. {
  9634. result = value_t::discarded;
  9635. return;
  9636. }
  9637. // set top-level value to null if it was discarded by the callback
  9638. // function
  9639. if (result.is_discarded())
  9640. {
  9641. result = nullptr;
  9642. }
  9643. }
  9644. else
  9645. {
  9646. json_sax_dom_parser<BasicJsonType> sdp(result, allow_exceptions);
  9647. sax_parse_internal(&sdp);
  9648. // in strict mode, input must be completely read
  9649. if (strict && (get_token() != token_type::end_of_input))
  9650. {
  9651. sdp.parse_error(m_lexer.get_position(),
  9652. m_lexer.get_token_string(),
  9653. parse_error::create(101, m_lexer.get_position(), exception_message(token_type::end_of_input, "value"), BasicJsonType()));
  9654. }
  9655. // in case of an error, return discarded value
  9656. if (sdp.is_errored())
  9657. {
  9658. result = value_t::discarded;
  9659. return;
  9660. }
  9661. }
  9662. result.assert_invariant();
  9663. }
  9664. /*!
  9665. @brief public accept interface
  9666. @param[in] strict whether to expect the last token to be EOF
  9667. @return whether the input is a proper JSON text
  9668. */
  9669. bool accept(const bool strict = true)
  9670. {
  9671. json_sax_acceptor<BasicJsonType> sax_acceptor;
  9672. return sax_parse(&sax_acceptor, strict);
  9673. }
  9674. template<typename SAX>
  9675. JSON_HEDLEY_NON_NULL(2)
  9676. bool sax_parse(SAX* sax, const bool strict = true)
  9677. {
  9678. (void)detail::is_sax_static_asserts<SAX, BasicJsonType> {};
  9679. const bool result = sax_parse_internal(sax);
  9680. // strict mode: next byte must be EOF
  9681. if (result && strict && (get_token() != token_type::end_of_input))
  9682. {
  9683. return sax->parse_error(m_lexer.get_position(),
  9684. m_lexer.get_token_string(),
  9685. parse_error::create(101, m_lexer.get_position(), exception_message(token_type::end_of_input, "value"), BasicJsonType()));
  9686. }
  9687. return result;
  9688. }
  9689. private:
  9690. template<typename SAX>
  9691. JSON_HEDLEY_NON_NULL(2)
  9692. bool sax_parse_internal(SAX* sax)
  9693. {
  9694. // stack to remember the hierarchy of structured values we are parsing
  9695. // true = array; false = object
  9696. std::vector<bool> states;
  9697. // value to avoid a goto (see comment where set to true)
  9698. bool skip_to_state_evaluation = false;
  9699. while (true)
  9700. {
  9701. if (!skip_to_state_evaluation)
  9702. {
  9703. // invariant: get_token() was called before each iteration
  9704. switch (last_token)
  9705. {
  9706. case token_type::begin_object:
  9707. {
  9708. if (JSON_HEDLEY_UNLIKELY(!sax->start_object(std::size_t(-1))))
  9709. {
  9710. return false;
  9711. }
  9712. // closing } -> we are done
  9713. if (get_token() == token_type::end_object)
  9714. {
  9715. if (JSON_HEDLEY_UNLIKELY(!sax->end_object()))
  9716. {
  9717. return false;
  9718. }
  9719. break;
  9720. }
  9721. // parse key
  9722. if (JSON_HEDLEY_UNLIKELY(last_token != token_type::value_string))
  9723. {
  9724. return sax->parse_error(m_lexer.get_position(),
  9725. m_lexer.get_token_string(),
  9726. parse_error::create(101, m_lexer.get_position(), exception_message(token_type::value_string, "object key"), BasicJsonType()));
  9727. }
  9728. if (JSON_HEDLEY_UNLIKELY(!sax->key(m_lexer.get_string())))
  9729. {
  9730. return false;
  9731. }
  9732. // parse separator (:)
  9733. if (JSON_HEDLEY_UNLIKELY(get_token() != token_type::name_separator))
  9734. {
  9735. return sax->parse_error(m_lexer.get_position(),
  9736. m_lexer.get_token_string(),
  9737. parse_error::create(101, m_lexer.get_position(), exception_message(token_type::name_separator, "object separator"), BasicJsonType()));
  9738. }
  9739. // remember we are now inside an object
  9740. states.push_back(false);
  9741. // parse values
  9742. get_token();
  9743. continue;
  9744. }
  9745. case token_type::begin_array:
  9746. {
  9747. if (JSON_HEDLEY_UNLIKELY(!sax->start_array(std::size_t(-1))))
  9748. {
  9749. return false;
  9750. }
  9751. // closing ] -> we are done
  9752. if (get_token() == token_type::end_array)
  9753. {
  9754. if (JSON_HEDLEY_UNLIKELY(!sax->end_array()))
  9755. {
  9756. return false;
  9757. }
  9758. break;
  9759. }
  9760. // remember we are now inside an array
  9761. states.push_back(true);
  9762. // parse values (no need to call get_token)
  9763. continue;
  9764. }
  9765. case token_type::value_float:
  9766. {
  9767. const auto res = m_lexer.get_number_float();
  9768. if (JSON_HEDLEY_UNLIKELY(!std::isfinite(res)))
  9769. {
  9770. return sax->parse_error(m_lexer.get_position(),
  9771. m_lexer.get_token_string(),
  9772. out_of_range::create(406, "number overflow parsing '" + m_lexer.get_token_string() + "'", BasicJsonType()));
  9773. }
  9774. if (JSON_HEDLEY_UNLIKELY(!sax->number_float(res, m_lexer.get_string())))
  9775. {
  9776. return false;
  9777. }
  9778. break;
  9779. }
  9780. case token_type::literal_false:
  9781. {
  9782. if (JSON_HEDLEY_UNLIKELY(!sax->boolean(false)))
  9783. {
  9784. return false;
  9785. }
  9786. break;
  9787. }
  9788. case token_type::literal_null:
  9789. {
  9790. if (JSON_HEDLEY_UNLIKELY(!sax->null()))
  9791. {
  9792. return false;
  9793. }
  9794. break;
  9795. }
  9796. case token_type::literal_true:
  9797. {
  9798. if (JSON_HEDLEY_UNLIKELY(!sax->boolean(true)))
  9799. {
  9800. return false;
  9801. }
  9802. break;
  9803. }
  9804. case token_type::value_integer:
  9805. {
  9806. if (JSON_HEDLEY_UNLIKELY(!sax->number_integer(m_lexer.get_number_integer())))
  9807. {
  9808. return false;
  9809. }
  9810. break;
  9811. }
  9812. case token_type::value_string:
  9813. {
  9814. if (JSON_HEDLEY_UNLIKELY(!sax->string(m_lexer.get_string())))
  9815. {
  9816. return false;
  9817. }
  9818. break;
  9819. }
  9820. case token_type::value_unsigned:
  9821. {
  9822. if (JSON_HEDLEY_UNLIKELY(!sax->number_unsigned(m_lexer.get_number_unsigned())))
  9823. {
  9824. return false;
  9825. }
  9826. break;
  9827. }
  9828. case token_type::parse_error:
  9829. {
  9830. // using "uninitialized" to avoid "expected" message
  9831. return sax->parse_error(m_lexer.get_position(),
  9832. m_lexer.get_token_string(),
  9833. parse_error::create(101, m_lexer.get_position(), exception_message(token_type::uninitialized, "value"), BasicJsonType()));
  9834. }
  9835. case token_type::uninitialized:
  9836. case token_type::end_array:
  9837. case token_type::end_object:
  9838. case token_type::name_separator:
  9839. case token_type::value_separator:
  9840. case token_type::end_of_input:
  9841. case token_type::literal_or_value:
  9842. default: // the last token was unexpected
  9843. {
  9844. return sax->parse_error(m_lexer.get_position(),
  9845. m_lexer.get_token_string(),
  9846. parse_error::create(101, m_lexer.get_position(), exception_message(token_type::literal_or_value, "value"), BasicJsonType()));
  9847. }
  9848. }
  9849. }
  9850. else
  9851. {
  9852. skip_to_state_evaluation = false;
  9853. }
  9854. // we reached this line after we successfully parsed a value
  9855. if (states.empty())
  9856. {
  9857. // empty stack: we reached the end of the hierarchy: done
  9858. return true;
  9859. }
  9860. if (states.back()) // array
  9861. {
  9862. // comma -> next value
  9863. if (get_token() == token_type::value_separator)
  9864. {
  9865. // parse a new value
  9866. get_token();
  9867. continue;
  9868. }
  9869. // closing ]
  9870. if (JSON_HEDLEY_LIKELY(last_token == token_type::end_array))
  9871. {
  9872. if (JSON_HEDLEY_UNLIKELY(!sax->end_array()))
  9873. {
  9874. return false;
  9875. }
  9876. // We are done with this array. Before we can parse a
  9877. // new value, we need to evaluate the new state first.
  9878. // By setting skip_to_state_evaluation to false, we
  9879. // are effectively jumping to the beginning of this if.
  9880. JSON_ASSERT(!states.empty());
  9881. states.pop_back();
  9882. skip_to_state_evaluation = true;
  9883. continue;
  9884. }
  9885. return sax->parse_error(m_lexer.get_position(),
  9886. m_lexer.get_token_string(),
  9887. parse_error::create(101, m_lexer.get_position(), exception_message(token_type::end_array, "array"), BasicJsonType()));
  9888. }
  9889. // states.back() is false -> object
  9890. // comma -> next value
  9891. if (get_token() == token_type::value_separator)
  9892. {
  9893. // parse key
  9894. if (JSON_HEDLEY_UNLIKELY(get_token() != token_type::value_string))
  9895. {
  9896. return sax->parse_error(m_lexer.get_position(),
  9897. m_lexer.get_token_string(),
  9898. parse_error::create(101, m_lexer.get_position(), exception_message(token_type::value_string, "object key"), BasicJsonType()));
  9899. }
  9900. if (JSON_HEDLEY_UNLIKELY(!sax->key(m_lexer.get_string())))
  9901. {
  9902. return false;
  9903. }
  9904. // parse separator (:)
  9905. if (JSON_HEDLEY_UNLIKELY(get_token() != token_type::name_separator))
  9906. {
  9907. return sax->parse_error(m_lexer.get_position(),
  9908. m_lexer.get_token_string(),
  9909. parse_error::create(101, m_lexer.get_position(), exception_message(token_type::name_separator, "object separator"), BasicJsonType()));
  9910. }
  9911. // parse values
  9912. get_token();
  9913. continue;
  9914. }
  9915. // closing }
  9916. if (JSON_HEDLEY_LIKELY(last_token == token_type::end_object))
  9917. {
  9918. if (JSON_HEDLEY_UNLIKELY(!sax->end_object()))
  9919. {
  9920. return false;
  9921. }
  9922. // We are done with this object. Before we can parse a
  9923. // new value, we need to evaluate the new state first.
  9924. // By setting skip_to_state_evaluation to false, we
  9925. // are effectively jumping to the beginning of this if.
  9926. JSON_ASSERT(!states.empty());
  9927. states.pop_back();
  9928. skip_to_state_evaluation = true;
  9929. continue;
  9930. }
  9931. return sax->parse_error(m_lexer.get_position(),
  9932. m_lexer.get_token_string(),
  9933. parse_error::create(101, m_lexer.get_position(), exception_message(token_type::end_object, "object"), BasicJsonType()));
  9934. }
  9935. }
  9936. /// get next token from lexer
  9937. token_type get_token()
  9938. {
  9939. return last_token = m_lexer.scan();
  9940. }
  9941. std::string exception_message(const token_type expected, const std::string& context)
  9942. {
  9943. std::string error_msg = "syntax error ";
  9944. if (!context.empty())
  9945. {
  9946. error_msg += "while parsing " + context + " ";
  9947. }
  9948. error_msg += "- ";
  9949. if (last_token == token_type::parse_error)
  9950. {
  9951. error_msg += std::string(m_lexer.get_error_message()) + "; last read: '" +
  9952. m_lexer.get_token_string() + "'";
  9953. }
  9954. else
  9955. {
  9956. error_msg += "unexpected " + std::string(lexer_t::token_type_name(last_token));
  9957. }
  9958. if (expected != token_type::uninitialized)
  9959. {
  9960. error_msg += "; expected " + std::string(lexer_t::token_type_name(expected));
  9961. }
  9962. return error_msg;
  9963. }
  9964. private:
  9965. /// callback function
  9966. const parser_callback_t<BasicJsonType> callback = nullptr;
  9967. /// the type of the last read token
  9968. token_type last_token = token_type::uninitialized;
  9969. /// the lexer
  9970. lexer_t m_lexer;
  9971. /// whether to throw exceptions in case of errors
  9972. const bool allow_exceptions = true;
  9973. };
  9974. } // namespace detail
  9975. } // namespace nlohmann
  9976. // #include <nlohmann/detail/iterators/internal_iterator.hpp>
  9977. // #include <nlohmann/detail/iterators/primitive_iterator.hpp>
  9978. #include <cstddef> // ptrdiff_t
  9979. #include <limits> // numeric_limits
  9980. // #include <nlohmann/detail/macro_scope.hpp>
  9981. namespace nlohmann
  9982. {
  9983. namespace detail
  9984. {
  9985. /*
  9986. @brief an iterator for primitive JSON types
  9987. This class models an iterator for primitive JSON types (boolean, number,
  9988. string). It's only purpose is to allow the iterator/const_iterator classes
  9989. to "iterate" over primitive values. Internally, the iterator is modeled by
  9990. a `difference_type` variable. Value begin_value (`0`) models the begin,
  9991. end_value (`1`) models past the end.
  9992. */
  9993. class primitive_iterator_t
  9994. {
  9995. private:
  9996. using difference_type = std::ptrdiff_t;
  9997. static constexpr difference_type begin_value = 0;
  9998. static constexpr difference_type end_value = begin_value + 1;
  9999. JSON_PRIVATE_UNLESS_TESTED:
  10000. /// iterator as signed integer type
  10001. difference_type m_it = (std::numeric_limits<std::ptrdiff_t>::min)();
  10002. public:
  10003. constexpr difference_type get_value() const noexcept
  10004. {
  10005. return m_it;
  10006. }
  10007. /// set iterator to a defined beginning
  10008. void set_begin() noexcept
  10009. {
  10010. m_it = begin_value;
  10011. }
  10012. /// set iterator to a defined past the end
  10013. void set_end() noexcept
  10014. {
  10015. m_it = end_value;
  10016. }
  10017. /// return whether the iterator can be dereferenced
  10018. constexpr bool is_begin() const noexcept
  10019. {
  10020. return m_it == begin_value;
  10021. }
  10022. /// return whether the iterator is at end
  10023. constexpr bool is_end() const noexcept
  10024. {
  10025. return m_it == end_value;
  10026. }
  10027. friend constexpr bool operator==(primitive_iterator_t lhs, primitive_iterator_t rhs) noexcept
  10028. {
  10029. return lhs.m_it == rhs.m_it;
  10030. }
  10031. friend constexpr bool operator<(primitive_iterator_t lhs, primitive_iterator_t rhs) noexcept
  10032. {
  10033. return lhs.m_it < rhs.m_it;
  10034. }
  10035. primitive_iterator_t operator+(difference_type n) noexcept
  10036. {
  10037. auto result = *this;
  10038. result += n;
  10039. return result;
  10040. }
  10041. friend constexpr difference_type operator-(primitive_iterator_t lhs, primitive_iterator_t rhs) noexcept
  10042. {
  10043. return lhs.m_it - rhs.m_it;
  10044. }
  10045. primitive_iterator_t& operator++() noexcept
  10046. {
  10047. ++m_it;
  10048. return *this;
  10049. }
  10050. primitive_iterator_t const operator++(int) noexcept // NOLINT(readability-const-return-type)
  10051. {
  10052. auto result = *this;
  10053. ++m_it;
  10054. return result;
  10055. }
  10056. primitive_iterator_t& operator--() noexcept
  10057. {
  10058. --m_it;
  10059. return *this;
  10060. }
  10061. primitive_iterator_t const operator--(int) noexcept // NOLINT(readability-const-return-type)
  10062. {
  10063. auto result = *this;
  10064. --m_it;
  10065. return result;
  10066. }
  10067. primitive_iterator_t& operator+=(difference_type n) noexcept
  10068. {
  10069. m_it += n;
  10070. return *this;
  10071. }
  10072. primitive_iterator_t& operator-=(difference_type n) noexcept
  10073. {
  10074. m_it -= n;
  10075. return *this;
  10076. }
  10077. };
  10078. } // namespace detail
  10079. } // namespace nlohmann
  10080. namespace nlohmann
  10081. {
  10082. namespace detail
  10083. {
  10084. /*!
  10085. @brief an iterator value
  10086. @note This structure could easily be a union, but MSVC currently does not allow
  10087. unions members with complex constructors, see https://github.com/nlohmann/json/pull/105.
  10088. */
  10089. template<typename BasicJsonType> struct internal_iterator
  10090. {
  10091. /// iterator for JSON objects
  10092. typename BasicJsonType::object_t::iterator object_iterator {};
  10093. /// iterator for JSON arrays
  10094. typename BasicJsonType::array_t::iterator array_iterator {};
  10095. /// generic iterator for all other types
  10096. primitive_iterator_t primitive_iterator {};
  10097. };
  10098. } // namespace detail
  10099. } // namespace nlohmann
  10100. // #include <nlohmann/detail/iterators/iter_impl.hpp>
  10101. #include <iterator> // iterator, random_access_iterator_tag, bidirectional_iterator_tag, advance, next
  10102. #include <type_traits> // conditional, is_const, remove_const
  10103. // #include <nlohmann/detail/exceptions.hpp>
  10104. // #include <nlohmann/detail/iterators/internal_iterator.hpp>
  10105. // #include <nlohmann/detail/iterators/primitive_iterator.hpp>
  10106. // #include <nlohmann/detail/macro_scope.hpp>
  10107. // #include <nlohmann/detail/meta/cpp_future.hpp>
  10108. // #include <nlohmann/detail/meta/type_traits.hpp>
  10109. // #include <nlohmann/detail/value_t.hpp>
  10110. namespace nlohmann
  10111. {
  10112. namespace detail
  10113. {
  10114. // forward declare, to be able to friend it later on
  10115. template<typename IteratorType> class iteration_proxy;
  10116. template<typename IteratorType> class iteration_proxy_value;
  10117. /*!
  10118. @brief a template for a bidirectional iterator for the @ref basic_json class
  10119. This class implements a both iterators (iterator and const_iterator) for the
  10120. @ref basic_json class.
  10121. @note An iterator is called *initialized* when a pointer to a JSON value has
  10122. been set (e.g., by a constructor or a copy assignment). If the iterator is
  10123. default-constructed, it is *uninitialized* and most methods are undefined.
  10124. **The library uses assertions to detect calls on uninitialized iterators.**
  10125. @requirement The class satisfies the following concept requirements:
  10126. -
  10127. [BidirectionalIterator](https://en.cppreference.com/w/cpp/named_req/BidirectionalIterator):
  10128. The iterator that can be moved can be moved in both directions (i.e.
  10129. incremented and decremented).
  10130. @since version 1.0.0, simplified in version 2.0.9, change to bidirectional
  10131. iterators in version 3.0.0 (see https://github.com/nlohmann/json/issues/593)
  10132. */
  10133. template<typename BasicJsonType>
  10134. class iter_impl
  10135. {
  10136. /// the iterator with BasicJsonType of different const-ness
  10137. using other_iter_impl = iter_impl<typename std::conditional<std::is_const<BasicJsonType>::value, typename std::remove_const<BasicJsonType>::type, const BasicJsonType>::type>;
  10138. /// allow basic_json to access private members
  10139. friend other_iter_impl;
  10140. friend BasicJsonType;
  10141. friend iteration_proxy<iter_impl>;
  10142. friend iteration_proxy_value<iter_impl>;
  10143. using object_t = typename BasicJsonType::object_t;
  10144. using array_t = typename BasicJsonType::array_t;
  10145. // make sure BasicJsonType is basic_json or const basic_json
  10146. static_assert(is_basic_json<typename std::remove_const<BasicJsonType>::type>::value,
  10147. "iter_impl only accepts (const) basic_json");
  10148. public:
  10149. /// The std::iterator class template (used as a base class to provide typedefs) is deprecated in C++17.
  10150. /// The C++ Standard has never required user-defined iterators to derive from std::iterator.
  10151. /// A user-defined iterator should provide publicly accessible typedefs named
  10152. /// iterator_category, value_type, difference_type, pointer, and reference.
  10153. /// Note that value_type is required to be non-const, even for constant iterators.
  10154. using iterator_category = std::bidirectional_iterator_tag;
  10155. /// the type of the values when the iterator is dereferenced
  10156. using value_type = typename BasicJsonType::value_type;
  10157. /// a type to represent differences between iterators
  10158. using difference_type = typename BasicJsonType::difference_type;
  10159. /// defines a pointer to the type iterated over (value_type)
  10160. using pointer = typename std::conditional<std::is_const<BasicJsonType>::value,
  10161. typename BasicJsonType::const_pointer,
  10162. typename BasicJsonType::pointer>::type;
  10163. /// defines a reference to the type iterated over (value_type)
  10164. using reference =
  10165. typename std::conditional<std::is_const<BasicJsonType>::value,
  10166. typename BasicJsonType::const_reference,
  10167. typename BasicJsonType::reference>::type;
  10168. iter_impl() = default;
  10169. ~iter_impl() = default;
  10170. iter_impl(iter_impl&&) noexcept = default;
  10171. iter_impl& operator=(iter_impl&&) noexcept = default;
  10172. /*!
  10173. @brief constructor for a given JSON instance
  10174. @param[in] object pointer to a JSON object for this iterator
  10175. @pre object != nullptr
  10176. @post The iterator is initialized; i.e. `m_object != nullptr`.
  10177. */
  10178. explicit iter_impl(pointer object) noexcept : m_object(object)
  10179. {
  10180. JSON_ASSERT(m_object != nullptr);
  10181. switch (m_object->m_type)
  10182. {
  10183. case value_t::object:
  10184. {
  10185. m_it.object_iterator = typename object_t::iterator();
  10186. break;
  10187. }
  10188. case value_t::array:
  10189. {
  10190. m_it.array_iterator = typename array_t::iterator();
  10191. break;
  10192. }
  10193. case value_t::null:
  10194. case value_t::string:
  10195. case value_t::boolean:
  10196. case value_t::number_integer:
  10197. case value_t::number_unsigned:
  10198. case value_t::number_float:
  10199. case value_t::binary:
  10200. case value_t::discarded:
  10201. default:
  10202. {
  10203. m_it.primitive_iterator = primitive_iterator_t();
  10204. break;
  10205. }
  10206. }
  10207. }
  10208. /*!
  10209. @note The conventional copy constructor and copy assignment are implicitly
  10210. defined. Combined with the following converting constructor and
  10211. assignment, they support: (1) copy from iterator to iterator, (2)
  10212. copy from const iterator to const iterator, and (3) conversion from
  10213. iterator to const iterator. However conversion from const iterator
  10214. to iterator is not defined.
  10215. */
  10216. /*!
  10217. @brief const copy constructor
  10218. @param[in] other const iterator to copy from
  10219. @note This copy constructor had to be defined explicitly to circumvent a bug
  10220. occurring on msvc v19.0 compiler (VS 2015) debug build. For more
  10221. information refer to: https://github.com/nlohmann/json/issues/1608
  10222. */
  10223. iter_impl(const iter_impl<const BasicJsonType>& other) noexcept
  10224. : m_object(other.m_object), m_it(other.m_it)
  10225. {}
  10226. /*!
  10227. @brief converting assignment
  10228. @param[in] other const iterator to copy from
  10229. @return const/non-const iterator
  10230. @note It is not checked whether @a other is initialized.
  10231. */
  10232. iter_impl& operator=(const iter_impl<const BasicJsonType>& other) noexcept
  10233. {
  10234. if (&other != this)
  10235. {
  10236. m_object = other.m_object;
  10237. m_it = other.m_it;
  10238. }
  10239. return *this;
  10240. }
  10241. /*!
  10242. @brief converting constructor
  10243. @param[in] other non-const iterator to copy from
  10244. @note It is not checked whether @a other is initialized.
  10245. */
  10246. iter_impl(const iter_impl<typename std::remove_const<BasicJsonType>::type>& other) noexcept
  10247. : m_object(other.m_object), m_it(other.m_it)
  10248. {}
  10249. /*!
  10250. @brief converting assignment
  10251. @param[in] other non-const iterator to copy from
  10252. @return const/non-const iterator
  10253. @note It is not checked whether @a other is initialized.
  10254. */
  10255. iter_impl& operator=(const iter_impl<typename std::remove_const<BasicJsonType>::type>& other) noexcept // NOLINT(cert-oop54-cpp)
  10256. {
  10257. m_object = other.m_object;
  10258. m_it = other.m_it;
  10259. return *this;
  10260. }
  10261. JSON_PRIVATE_UNLESS_TESTED:
  10262. /*!
  10263. @brief set the iterator to the first value
  10264. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  10265. */
  10266. void set_begin() noexcept
  10267. {
  10268. JSON_ASSERT(m_object != nullptr);
  10269. switch (m_object->m_type)
  10270. {
  10271. case value_t::object:
  10272. {
  10273. m_it.object_iterator = m_object->m_value.object->begin();
  10274. break;
  10275. }
  10276. case value_t::array:
  10277. {
  10278. m_it.array_iterator = m_object->m_value.array->begin();
  10279. break;
  10280. }
  10281. case value_t::null:
  10282. {
  10283. // set to end so begin()==end() is true: null is empty
  10284. m_it.primitive_iterator.set_end();
  10285. break;
  10286. }
  10287. case value_t::string:
  10288. case value_t::boolean:
  10289. case value_t::number_integer:
  10290. case value_t::number_unsigned:
  10291. case value_t::number_float:
  10292. case value_t::binary:
  10293. case value_t::discarded:
  10294. default:
  10295. {
  10296. m_it.primitive_iterator.set_begin();
  10297. break;
  10298. }
  10299. }
  10300. }
  10301. /*!
  10302. @brief set the iterator past the last value
  10303. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  10304. */
  10305. void set_end() noexcept
  10306. {
  10307. JSON_ASSERT(m_object != nullptr);
  10308. switch (m_object->m_type)
  10309. {
  10310. case value_t::object:
  10311. {
  10312. m_it.object_iterator = m_object->m_value.object->end();
  10313. break;
  10314. }
  10315. case value_t::array:
  10316. {
  10317. m_it.array_iterator = m_object->m_value.array->end();
  10318. break;
  10319. }
  10320. case value_t::null:
  10321. case value_t::string:
  10322. case value_t::boolean:
  10323. case value_t::number_integer:
  10324. case value_t::number_unsigned:
  10325. case value_t::number_float:
  10326. case value_t::binary:
  10327. case value_t::discarded:
  10328. default:
  10329. {
  10330. m_it.primitive_iterator.set_end();
  10331. break;
  10332. }
  10333. }
  10334. }
  10335. public:
  10336. /*!
  10337. @brief return a reference to the value pointed to by the iterator
  10338. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  10339. */
  10340. reference operator*() const
  10341. {
  10342. JSON_ASSERT(m_object != nullptr);
  10343. switch (m_object->m_type)
  10344. {
  10345. case value_t::object:
  10346. {
  10347. JSON_ASSERT(m_it.object_iterator != m_object->m_value.object->end());
  10348. return m_it.object_iterator->second;
  10349. }
  10350. case value_t::array:
  10351. {
  10352. JSON_ASSERT(m_it.array_iterator != m_object->m_value.array->end());
  10353. return *m_it.array_iterator;
  10354. }
  10355. case value_t::null:
  10356. JSON_THROW(invalid_iterator::create(214, "cannot get value", *m_object));
  10357. case value_t::string:
  10358. case value_t::boolean:
  10359. case value_t::number_integer:
  10360. case value_t::number_unsigned:
  10361. case value_t::number_float:
  10362. case value_t::binary:
  10363. case value_t::discarded:
  10364. default:
  10365. {
  10366. if (JSON_HEDLEY_LIKELY(m_it.primitive_iterator.is_begin()))
  10367. {
  10368. return *m_object;
  10369. }
  10370. JSON_THROW(invalid_iterator::create(214, "cannot get value", *m_object));
  10371. }
  10372. }
  10373. }
  10374. /*!
  10375. @brief dereference the iterator
  10376. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  10377. */
  10378. pointer operator->() const
  10379. {
  10380. JSON_ASSERT(m_object != nullptr);
  10381. switch (m_object->m_type)
  10382. {
  10383. case value_t::object:
  10384. {
  10385. JSON_ASSERT(m_it.object_iterator != m_object->m_value.object->end());
  10386. return &(m_it.object_iterator->second);
  10387. }
  10388. case value_t::array:
  10389. {
  10390. JSON_ASSERT(m_it.array_iterator != m_object->m_value.array->end());
  10391. return &*m_it.array_iterator;
  10392. }
  10393. case value_t::null:
  10394. case value_t::string:
  10395. case value_t::boolean:
  10396. case value_t::number_integer:
  10397. case value_t::number_unsigned:
  10398. case value_t::number_float:
  10399. case value_t::binary:
  10400. case value_t::discarded:
  10401. default:
  10402. {
  10403. if (JSON_HEDLEY_LIKELY(m_it.primitive_iterator.is_begin()))
  10404. {
  10405. return m_object;
  10406. }
  10407. JSON_THROW(invalid_iterator::create(214, "cannot get value", *m_object));
  10408. }
  10409. }
  10410. }
  10411. /*!
  10412. @brief post-increment (it++)
  10413. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  10414. */
  10415. iter_impl const operator++(int) // NOLINT(readability-const-return-type)
  10416. {
  10417. auto result = *this;
  10418. ++(*this);
  10419. return result;
  10420. }
  10421. /*!
  10422. @brief pre-increment (++it)
  10423. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  10424. */
  10425. iter_impl& operator++()
  10426. {
  10427. JSON_ASSERT(m_object != nullptr);
  10428. switch (m_object->m_type)
  10429. {
  10430. case value_t::object:
  10431. {
  10432. std::advance(m_it.object_iterator, 1);
  10433. break;
  10434. }
  10435. case value_t::array:
  10436. {
  10437. std::advance(m_it.array_iterator, 1);
  10438. break;
  10439. }
  10440. case value_t::null:
  10441. case value_t::string:
  10442. case value_t::boolean:
  10443. case value_t::number_integer:
  10444. case value_t::number_unsigned:
  10445. case value_t::number_float:
  10446. case value_t::binary:
  10447. case value_t::discarded:
  10448. default:
  10449. {
  10450. ++m_it.primitive_iterator;
  10451. break;
  10452. }
  10453. }
  10454. return *this;
  10455. }
  10456. /*!
  10457. @brief post-decrement (it--)
  10458. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  10459. */
  10460. iter_impl const operator--(int) // NOLINT(readability-const-return-type)
  10461. {
  10462. auto result = *this;
  10463. --(*this);
  10464. return result;
  10465. }
  10466. /*!
  10467. @brief pre-decrement (--it)
  10468. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  10469. */
  10470. iter_impl& operator--()
  10471. {
  10472. JSON_ASSERT(m_object != nullptr);
  10473. switch (m_object->m_type)
  10474. {
  10475. case value_t::object:
  10476. {
  10477. std::advance(m_it.object_iterator, -1);
  10478. break;
  10479. }
  10480. case value_t::array:
  10481. {
  10482. std::advance(m_it.array_iterator, -1);
  10483. break;
  10484. }
  10485. case value_t::null:
  10486. case value_t::string:
  10487. case value_t::boolean:
  10488. case value_t::number_integer:
  10489. case value_t::number_unsigned:
  10490. case value_t::number_float:
  10491. case value_t::binary:
  10492. case value_t::discarded:
  10493. default:
  10494. {
  10495. --m_it.primitive_iterator;
  10496. break;
  10497. }
  10498. }
  10499. return *this;
  10500. }
  10501. /*!
  10502. @brief comparison: equal
  10503. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  10504. */
  10505. template < typename IterImpl, detail::enable_if_t < (std::is_same<IterImpl, iter_impl>::value || std::is_same<IterImpl, other_iter_impl>::value), std::nullptr_t > = nullptr >
  10506. bool operator==(const IterImpl& other) const
  10507. {
  10508. // if objects are not the same, the comparison is undefined
  10509. if (JSON_HEDLEY_UNLIKELY(m_object != other.m_object))
  10510. {
  10511. JSON_THROW(invalid_iterator::create(212, "cannot compare iterators of different containers", *m_object));
  10512. }
  10513. JSON_ASSERT(m_object != nullptr);
  10514. switch (m_object->m_type)
  10515. {
  10516. case value_t::object:
  10517. return (m_it.object_iterator == other.m_it.object_iterator);
  10518. case value_t::array:
  10519. return (m_it.array_iterator == other.m_it.array_iterator);
  10520. case value_t::null:
  10521. case value_t::string:
  10522. case value_t::boolean:
  10523. case value_t::number_integer:
  10524. case value_t::number_unsigned:
  10525. case value_t::number_float:
  10526. case value_t::binary:
  10527. case value_t::discarded:
  10528. default:
  10529. return (m_it.primitive_iterator == other.m_it.primitive_iterator);
  10530. }
  10531. }
  10532. /*!
  10533. @brief comparison: not equal
  10534. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  10535. */
  10536. template < typename IterImpl, detail::enable_if_t < (std::is_same<IterImpl, iter_impl>::value || std::is_same<IterImpl, other_iter_impl>::value), std::nullptr_t > = nullptr >
  10537. bool operator!=(const IterImpl& other) const
  10538. {
  10539. return !operator==(other);
  10540. }
  10541. /*!
  10542. @brief comparison: smaller
  10543. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  10544. */
  10545. bool operator<(const iter_impl& other) const
  10546. {
  10547. // if objects are not the same, the comparison is undefined
  10548. if (JSON_HEDLEY_UNLIKELY(m_object != other.m_object))
  10549. {
  10550. JSON_THROW(invalid_iterator::create(212, "cannot compare iterators of different containers", *m_object));
  10551. }
  10552. JSON_ASSERT(m_object != nullptr);
  10553. switch (m_object->m_type)
  10554. {
  10555. case value_t::object:
  10556. JSON_THROW(invalid_iterator::create(213, "cannot compare order of object iterators", *m_object));
  10557. case value_t::array:
  10558. return (m_it.array_iterator < other.m_it.array_iterator);
  10559. case value_t::null:
  10560. case value_t::string:
  10561. case value_t::boolean:
  10562. case value_t::number_integer:
  10563. case value_t::number_unsigned:
  10564. case value_t::number_float:
  10565. case value_t::binary:
  10566. case value_t::discarded:
  10567. default:
  10568. return (m_it.primitive_iterator < other.m_it.primitive_iterator);
  10569. }
  10570. }
  10571. /*!
  10572. @brief comparison: less than or equal
  10573. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  10574. */
  10575. bool operator<=(const iter_impl& other) const
  10576. {
  10577. return !other.operator < (*this);
  10578. }
  10579. /*!
  10580. @brief comparison: greater than
  10581. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  10582. */
  10583. bool operator>(const iter_impl& other) const
  10584. {
  10585. return !operator<=(other);
  10586. }
  10587. /*!
  10588. @brief comparison: greater than or equal
  10589. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  10590. */
  10591. bool operator>=(const iter_impl& other) const
  10592. {
  10593. return !operator<(other);
  10594. }
  10595. /*!
  10596. @brief add to iterator
  10597. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  10598. */
  10599. iter_impl& operator+=(difference_type i)
  10600. {
  10601. JSON_ASSERT(m_object != nullptr);
  10602. switch (m_object->m_type)
  10603. {
  10604. case value_t::object:
  10605. JSON_THROW(invalid_iterator::create(209, "cannot use offsets with object iterators", *m_object));
  10606. case value_t::array:
  10607. {
  10608. std::advance(m_it.array_iterator, i);
  10609. break;
  10610. }
  10611. case value_t::null:
  10612. case value_t::string:
  10613. case value_t::boolean:
  10614. case value_t::number_integer:
  10615. case value_t::number_unsigned:
  10616. case value_t::number_float:
  10617. case value_t::binary:
  10618. case value_t::discarded:
  10619. default:
  10620. {
  10621. m_it.primitive_iterator += i;
  10622. break;
  10623. }
  10624. }
  10625. return *this;
  10626. }
  10627. /*!
  10628. @brief subtract from iterator
  10629. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  10630. */
  10631. iter_impl& operator-=(difference_type i)
  10632. {
  10633. return operator+=(-i);
  10634. }
  10635. /*!
  10636. @brief add to iterator
  10637. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  10638. */
  10639. iter_impl operator+(difference_type i) const
  10640. {
  10641. auto result = *this;
  10642. result += i;
  10643. return result;
  10644. }
  10645. /*!
  10646. @brief addition of distance and iterator
  10647. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  10648. */
  10649. friend iter_impl operator+(difference_type i, const iter_impl& it)
  10650. {
  10651. auto result = it;
  10652. result += i;
  10653. return result;
  10654. }
  10655. /*!
  10656. @brief subtract from iterator
  10657. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  10658. */
  10659. iter_impl operator-(difference_type i) const
  10660. {
  10661. auto result = *this;
  10662. result -= i;
  10663. return result;
  10664. }
  10665. /*!
  10666. @brief return difference
  10667. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  10668. */
  10669. difference_type operator-(const iter_impl& other) const
  10670. {
  10671. JSON_ASSERT(m_object != nullptr);
  10672. switch (m_object->m_type)
  10673. {
  10674. case value_t::object:
  10675. JSON_THROW(invalid_iterator::create(209, "cannot use offsets with object iterators", *m_object));
  10676. case value_t::array:
  10677. return m_it.array_iterator - other.m_it.array_iterator;
  10678. case value_t::null:
  10679. case value_t::string:
  10680. case value_t::boolean:
  10681. case value_t::number_integer:
  10682. case value_t::number_unsigned:
  10683. case value_t::number_float:
  10684. case value_t::binary:
  10685. case value_t::discarded:
  10686. default:
  10687. return m_it.primitive_iterator - other.m_it.primitive_iterator;
  10688. }
  10689. }
  10690. /*!
  10691. @brief access to successor
  10692. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  10693. */
  10694. reference operator[](difference_type n) const
  10695. {
  10696. JSON_ASSERT(m_object != nullptr);
  10697. switch (m_object->m_type)
  10698. {
  10699. case value_t::object:
  10700. JSON_THROW(invalid_iterator::create(208, "cannot use operator[] for object iterators", *m_object));
  10701. case value_t::array:
  10702. return *std::next(m_it.array_iterator, n);
  10703. case value_t::null:
  10704. JSON_THROW(invalid_iterator::create(214, "cannot get value", *m_object));
  10705. case value_t::string:
  10706. case value_t::boolean:
  10707. case value_t::number_integer:
  10708. case value_t::number_unsigned:
  10709. case value_t::number_float:
  10710. case value_t::binary:
  10711. case value_t::discarded:
  10712. default:
  10713. {
  10714. if (JSON_HEDLEY_LIKELY(m_it.primitive_iterator.get_value() == -n))
  10715. {
  10716. return *m_object;
  10717. }
  10718. JSON_THROW(invalid_iterator::create(214, "cannot get value", *m_object));
  10719. }
  10720. }
  10721. }
  10722. /*!
  10723. @brief return the key of an object iterator
  10724. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  10725. */
  10726. const typename object_t::key_type& key() const
  10727. {
  10728. JSON_ASSERT(m_object != nullptr);
  10729. if (JSON_HEDLEY_LIKELY(m_object->is_object()))
  10730. {
  10731. return m_it.object_iterator->first;
  10732. }
  10733. JSON_THROW(invalid_iterator::create(207, "cannot use key() for non-object iterators", *m_object));
  10734. }
  10735. /*!
  10736. @brief return the value of an iterator
  10737. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  10738. */
  10739. reference value() const
  10740. {
  10741. return operator*();
  10742. }
  10743. JSON_PRIVATE_UNLESS_TESTED:
  10744. /// associated JSON instance
  10745. pointer m_object = nullptr;
  10746. /// the actual iterator of the associated instance
  10747. internal_iterator<typename std::remove_const<BasicJsonType>::type> m_it {};
  10748. };
  10749. } // namespace detail
  10750. } // namespace nlohmann
  10751. // #include <nlohmann/detail/iterators/iteration_proxy.hpp>
  10752. // #include <nlohmann/detail/iterators/json_reverse_iterator.hpp>
  10753. #include <cstddef> // ptrdiff_t
  10754. #include <iterator> // reverse_iterator
  10755. #include <utility> // declval
  10756. namespace nlohmann
  10757. {
  10758. namespace detail
  10759. {
  10760. //////////////////////
  10761. // reverse_iterator //
  10762. //////////////////////
  10763. /*!
  10764. @brief a template for a reverse iterator class
  10765. @tparam Base the base iterator type to reverse. Valid types are @ref
  10766. iterator (to create @ref reverse_iterator) and @ref const_iterator (to
  10767. create @ref const_reverse_iterator).
  10768. @requirement The class satisfies the following concept requirements:
  10769. -
  10770. [BidirectionalIterator](https://en.cppreference.com/w/cpp/named_req/BidirectionalIterator):
  10771. The iterator that can be moved can be moved in both directions (i.e.
  10772. incremented and decremented).
  10773. - [OutputIterator](https://en.cppreference.com/w/cpp/named_req/OutputIterator):
  10774. It is possible to write to the pointed-to element (only if @a Base is
  10775. @ref iterator).
  10776. @since version 1.0.0
  10777. */
  10778. template<typename Base>
  10779. class json_reverse_iterator : public std::reverse_iterator<Base>
  10780. {
  10781. public:
  10782. using difference_type = std::ptrdiff_t;
  10783. /// shortcut to the reverse iterator adapter
  10784. using base_iterator = std::reverse_iterator<Base>;
  10785. /// the reference type for the pointed-to element
  10786. using reference = typename Base::reference;
  10787. /// create reverse iterator from iterator
  10788. explicit json_reverse_iterator(const typename base_iterator::iterator_type& it) noexcept
  10789. : base_iterator(it) {}
  10790. /// create reverse iterator from base class
  10791. explicit json_reverse_iterator(const base_iterator& it) noexcept : base_iterator(it) {}
  10792. /// post-increment (it++)
  10793. json_reverse_iterator const operator++(int) // NOLINT(readability-const-return-type)
  10794. {
  10795. return static_cast<json_reverse_iterator>(base_iterator::operator++(1));
  10796. }
  10797. /// pre-increment (++it)
  10798. json_reverse_iterator& operator++()
  10799. {
  10800. return static_cast<json_reverse_iterator&>(base_iterator::operator++());
  10801. }
  10802. /// post-decrement (it--)
  10803. json_reverse_iterator const operator--(int) // NOLINT(readability-const-return-type)
  10804. {
  10805. return static_cast<json_reverse_iterator>(base_iterator::operator--(1));
  10806. }
  10807. /// pre-decrement (--it)
  10808. json_reverse_iterator& operator--()
  10809. {
  10810. return static_cast<json_reverse_iterator&>(base_iterator::operator--());
  10811. }
  10812. /// add to iterator
  10813. json_reverse_iterator& operator+=(difference_type i)
  10814. {
  10815. return static_cast<json_reverse_iterator&>(base_iterator::operator+=(i));
  10816. }
  10817. /// add to iterator
  10818. json_reverse_iterator operator+(difference_type i) const
  10819. {
  10820. return static_cast<json_reverse_iterator>(base_iterator::operator+(i));
  10821. }
  10822. /// subtract from iterator
  10823. json_reverse_iterator operator-(difference_type i) const
  10824. {
  10825. return static_cast<json_reverse_iterator>(base_iterator::operator-(i));
  10826. }
  10827. /// return difference
  10828. difference_type operator-(const json_reverse_iterator& other) const
  10829. {
  10830. return base_iterator(*this) - base_iterator(other);
  10831. }
  10832. /// access to successor
  10833. reference operator[](difference_type n) const
  10834. {
  10835. return *(this->operator+(n));
  10836. }
  10837. /// return the key of an object iterator
  10838. auto key() const -> decltype(std::declval<Base>().key())
  10839. {
  10840. auto it = --this->base();
  10841. return it.key();
  10842. }
  10843. /// return the value of an iterator
  10844. reference value() const
  10845. {
  10846. auto it = --this->base();
  10847. return it.operator * ();
  10848. }
  10849. };
  10850. } // namespace detail
  10851. } // namespace nlohmann
  10852. // #include <nlohmann/detail/iterators/primitive_iterator.hpp>
  10853. // #include <nlohmann/detail/json_pointer.hpp>
  10854. #include <algorithm> // all_of
  10855. #include <cctype> // isdigit
  10856. #include <limits> // max
  10857. #include <numeric> // accumulate
  10858. #include <string> // string
  10859. #include <utility> // move
  10860. #include <vector> // vector
  10861. // #include <nlohmann/detail/exceptions.hpp>
  10862. // #include <nlohmann/detail/macro_scope.hpp>
  10863. // #include <nlohmann/detail/string_escape.hpp>
  10864. // #include <nlohmann/detail/value_t.hpp>
  10865. namespace nlohmann
  10866. {
  10867. template<typename BasicJsonType>
  10868. class json_pointer
  10869. {
  10870. // allow basic_json to access private members
  10871. NLOHMANN_BASIC_JSON_TPL_DECLARATION
  10872. friend class basic_json;
  10873. public:
  10874. /*!
  10875. @brief create JSON pointer
  10876. Create a JSON pointer according to the syntax described in
  10877. [Section 3 of RFC6901](https://tools.ietf.org/html/rfc6901#section-3).
  10878. @param[in] s string representing the JSON pointer; if omitted, the empty
  10879. string is assumed which references the whole JSON value
  10880. @throw parse_error.107 if the given JSON pointer @a s is nonempty and does
  10881. not begin with a slash (`/`); see example below
  10882. @throw parse_error.108 if a tilde (`~`) in the given JSON pointer @a s is
  10883. not followed by `0` (representing `~`) or `1` (representing `/`); see
  10884. example below
  10885. @liveexample{The example shows the construction several valid JSON pointers
  10886. as well as the exceptional behavior.,json_pointer}
  10887. @since version 2.0.0
  10888. */
  10889. explicit json_pointer(const std::string& s = "")
  10890. : reference_tokens(split(s))
  10891. {}
  10892. /*!
  10893. @brief return a string representation of the JSON pointer
  10894. @invariant For each JSON pointer `ptr`, it holds:
  10895. @code {.cpp}
  10896. ptr == json_pointer(ptr.to_string());
  10897. @endcode
  10898. @return a string representation of the JSON pointer
  10899. @liveexample{The example shows the result of `to_string`.,json_pointer__to_string}
  10900. @since version 2.0.0
  10901. */
  10902. std::string to_string() const
  10903. {
  10904. return std::accumulate(reference_tokens.begin(), reference_tokens.end(),
  10905. std::string{},
  10906. [](const std::string & a, const std::string & b)
  10907. {
  10908. return a + "/" + detail::escape(b);
  10909. });
  10910. }
  10911. /// @copydoc to_string()
  10912. operator std::string() const
  10913. {
  10914. return to_string();
  10915. }
  10916. /*!
  10917. @brief append another JSON pointer at the end of this JSON pointer
  10918. @param[in] ptr JSON pointer to append
  10919. @return JSON pointer with @a ptr appended
  10920. @liveexample{The example shows the usage of `operator/=`.,json_pointer__operator_add}
  10921. @complexity Linear in the length of @a ptr.
  10922. @sa see @ref operator/=(std::string) to append a reference token
  10923. @sa see @ref operator/=(std::size_t) to append an array index
  10924. @sa see @ref operator/(const json_pointer&, const json_pointer&) for a binary operator
  10925. @since version 3.6.0
  10926. */
  10927. json_pointer& operator/=(const json_pointer& ptr)
  10928. {
  10929. reference_tokens.insert(reference_tokens.end(),
  10930. ptr.reference_tokens.begin(),
  10931. ptr.reference_tokens.end());
  10932. return *this;
  10933. }
  10934. /*!
  10935. @brief append an unescaped reference token at the end of this JSON pointer
  10936. @param[in] token reference token to append
  10937. @return JSON pointer with @a token appended without escaping @a token
  10938. @liveexample{The example shows the usage of `operator/=`.,json_pointer__operator_add}
  10939. @complexity Amortized constant.
  10940. @sa see @ref operator/=(const json_pointer&) to append a JSON pointer
  10941. @sa see @ref operator/=(std::size_t) to append an array index
  10942. @sa see @ref operator/(const json_pointer&, std::size_t) for a binary operator
  10943. @since version 3.6.0
  10944. */
  10945. json_pointer& operator/=(std::string token)
  10946. {
  10947. push_back(std::move(token));
  10948. return *this;
  10949. }
  10950. /*!
  10951. @brief append an array index at the end of this JSON pointer
  10952. @param[in] array_idx array index to append
  10953. @return JSON pointer with @a array_idx appended
  10954. @liveexample{The example shows the usage of `operator/=`.,json_pointer__operator_add}
  10955. @complexity Amortized constant.
  10956. @sa see @ref operator/=(const json_pointer&) to append a JSON pointer
  10957. @sa see @ref operator/=(std::string) to append a reference token
  10958. @sa see @ref operator/(const json_pointer&, std::string) for a binary operator
  10959. @since version 3.6.0
  10960. */
  10961. json_pointer& operator/=(std::size_t array_idx)
  10962. {
  10963. return *this /= std::to_string(array_idx);
  10964. }
  10965. /*!
  10966. @brief create a new JSON pointer by appending the right JSON pointer at the end of the left JSON pointer
  10967. @param[in] lhs JSON pointer
  10968. @param[in] rhs JSON pointer
  10969. @return a new JSON pointer with @a rhs appended to @a lhs
  10970. @liveexample{The example shows the usage of `operator/`.,json_pointer__operator_add_binary}
  10971. @complexity Linear in the length of @a lhs and @a rhs.
  10972. @sa see @ref operator/=(const json_pointer&) to append a JSON pointer
  10973. @since version 3.6.0
  10974. */
  10975. friend json_pointer operator/(const json_pointer& lhs,
  10976. const json_pointer& rhs)
  10977. {
  10978. return json_pointer(lhs) /= rhs;
  10979. }
  10980. /*!
  10981. @brief create a new JSON pointer by appending the unescaped token at the end of the JSON pointer
  10982. @param[in] ptr JSON pointer
  10983. @param[in] token reference token
  10984. @return a new JSON pointer with unescaped @a token appended to @a ptr
  10985. @liveexample{The example shows the usage of `operator/`.,json_pointer__operator_add_binary}
  10986. @complexity Linear in the length of @a ptr.
  10987. @sa see @ref operator/=(std::string) to append a reference token
  10988. @since version 3.6.0
  10989. */
  10990. friend json_pointer operator/(const json_pointer& ptr, std::string token) // NOLINT(performance-unnecessary-value-param)
  10991. {
  10992. return json_pointer(ptr) /= std::move(token);
  10993. }
  10994. /*!
  10995. @brief create a new JSON pointer by appending the array-index-token at the end of the JSON pointer
  10996. @param[in] ptr JSON pointer
  10997. @param[in] array_idx array index
  10998. @return a new JSON pointer with @a array_idx appended to @a ptr
  10999. @liveexample{The example shows the usage of `operator/`.,json_pointer__operator_add_binary}
  11000. @complexity Linear in the length of @a ptr.
  11001. @sa see @ref operator/=(std::size_t) to append an array index
  11002. @since version 3.6.0
  11003. */
  11004. friend json_pointer operator/(const json_pointer& ptr, std::size_t array_idx)
  11005. {
  11006. return json_pointer(ptr) /= array_idx;
  11007. }
  11008. /*!
  11009. @brief returns the parent of this JSON pointer
  11010. @return parent of this JSON pointer; in case this JSON pointer is the root,
  11011. the root itself is returned
  11012. @complexity Linear in the length of the JSON pointer.
  11013. @liveexample{The example shows the result of `parent_pointer` for different
  11014. JSON Pointers.,json_pointer__parent_pointer}
  11015. @since version 3.6.0
  11016. */
  11017. json_pointer parent_pointer() const
  11018. {
  11019. if (empty())
  11020. {
  11021. return *this;
  11022. }
  11023. json_pointer res = *this;
  11024. res.pop_back();
  11025. return res;
  11026. }
  11027. /*!
  11028. @brief remove last reference token
  11029. @pre not `empty()`
  11030. @liveexample{The example shows the usage of `pop_back`.,json_pointer__pop_back}
  11031. @complexity Constant.
  11032. @throw out_of_range.405 if JSON pointer has no parent
  11033. @since version 3.6.0
  11034. */
  11035. void pop_back()
  11036. {
  11037. if (JSON_HEDLEY_UNLIKELY(empty()))
  11038. {
  11039. JSON_THROW(detail::out_of_range::create(405, "JSON pointer has no parent", BasicJsonType()));
  11040. }
  11041. reference_tokens.pop_back();
  11042. }
  11043. /*!
  11044. @brief return last reference token
  11045. @pre not `empty()`
  11046. @return last reference token
  11047. @liveexample{The example shows the usage of `back`.,json_pointer__back}
  11048. @complexity Constant.
  11049. @throw out_of_range.405 if JSON pointer has no parent
  11050. @since version 3.6.0
  11051. */
  11052. const std::string& back() const
  11053. {
  11054. if (JSON_HEDLEY_UNLIKELY(empty()))
  11055. {
  11056. JSON_THROW(detail::out_of_range::create(405, "JSON pointer has no parent", BasicJsonType()));
  11057. }
  11058. return reference_tokens.back();
  11059. }
  11060. /*!
  11061. @brief append an unescaped token at the end of the reference pointer
  11062. @param[in] token token to add
  11063. @complexity Amortized constant.
  11064. @liveexample{The example shows the result of `push_back` for different
  11065. JSON Pointers.,json_pointer__push_back}
  11066. @since version 3.6.0
  11067. */
  11068. void push_back(const std::string& token)
  11069. {
  11070. reference_tokens.push_back(token);
  11071. }
  11072. /// @copydoc push_back(const std::string&)
  11073. void push_back(std::string&& token)
  11074. {
  11075. reference_tokens.push_back(std::move(token));
  11076. }
  11077. /*!
  11078. @brief return whether pointer points to the root document
  11079. @return true iff the JSON pointer points to the root document
  11080. @complexity Constant.
  11081. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  11082. @liveexample{The example shows the result of `empty` for different JSON
  11083. Pointers.,json_pointer__empty}
  11084. @since version 3.6.0
  11085. */
  11086. bool empty() const noexcept
  11087. {
  11088. return reference_tokens.empty();
  11089. }
  11090. private:
  11091. /*!
  11092. @param[in] s reference token to be converted into an array index
  11093. @return integer representation of @a s
  11094. @throw parse_error.106 if an array index begins with '0'
  11095. @throw parse_error.109 if an array index begins not with a digit
  11096. @throw out_of_range.404 if string @a s could not be converted to an integer
  11097. @throw out_of_range.410 if an array index exceeds size_type
  11098. */
  11099. static typename BasicJsonType::size_type array_index(const std::string& s)
  11100. {
  11101. using size_type = typename BasicJsonType::size_type;
  11102. // error condition (cf. RFC 6901, Sect. 4)
  11103. if (JSON_HEDLEY_UNLIKELY(s.size() > 1 && s[0] == '0'))
  11104. {
  11105. JSON_THROW(detail::parse_error::create(106, 0, "array index '" + s + "' must not begin with '0'", BasicJsonType()));
  11106. }
  11107. // error condition (cf. RFC 6901, Sect. 4)
  11108. if (JSON_HEDLEY_UNLIKELY(s.size() > 1 && !(s[0] >= '1' && s[0] <= '9')))
  11109. {
  11110. JSON_THROW(detail::parse_error::create(109, 0, "array index '" + s + "' is not a number", BasicJsonType()));
  11111. }
  11112. std::size_t processed_chars = 0;
  11113. unsigned long long res = 0; // NOLINT(runtime/int)
  11114. JSON_TRY
  11115. {
  11116. res = std::stoull(s, &processed_chars);
  11117. }
  11118. JSON_CATCH(std::out_of_range&)
  11119. {
  11120. JSON_THROW(detail::out_of_range::create(404, "unresolved reference token '" + s + "'", BasicJsonType()));
  11121. }
  11122. // check if the string was completely read
  11123. if (JSON_HEDLEY_UNLIKELY(processed_chars != s.size()))
  11124. {
  11125. JSON_THROW(detail::out_of_range::create(404, "unresolved reference token '" + s + "'", BasicJsonType()));
  11126. }
  11127. // only triggered on special platforms (like 32bit), see also
  11128. // https://github.com/nlohmann/json/pull/2203
  11129. if (res >= static_cast<unsigned long long>((std::numeric_limits<size_type>::max)())) // NOLINT(runtime/int)
  11130. {
  11131. JSON_THROW(detail::out_of_range::create(410, "array index " + s + " exceeds size_type", BasicJsonType())); // LCOV_EXCL_LINE
  11132. }
  11133. return static_cast<size_type>(res);
  11134. }
  11135. JSON_PRIVATE_UNLESS_TESTED:
  11136. json_pointer top() const
  11137. {
  11138. if (JSON_HEDLEY_UNLIKELY(empty()))
  11139. {
  11140. JSON_THROW(detail::out_of_range::create(405, "JSON pointer has no parent", BasicJsonType()));
  11141. }
  11142. json_pointer result = *this;
  11143. result.reference_tokens = {reference_tokens[0]};
  11144. return result;
  11145. }
  11146. private:
  11147. /*!
  11148. @brief create and return a reference to the pointed to value
  11149. @complexity Linear in the number of reference tokens.
  11150. @throw parse_error.109 if array index is not a number
  11151. @throw type_error.313 if value cannot be unflattened
  11152. */
  11153. BasicJsonType& get_and_create(BasicJsonType& j) const
  11154. {
  11155. auto* result = &j;
  11156. // in case no reference tokens exist, return a reference to the JSON value
  11157. // j which will be overwritten by a primitive value
  11158. for (const auto& reference_token : reference_tokens)
  11159. {
  11160. switch (result->type())
  11161. {
  11162. case detail::value_t::null:
  11163. {
  11164. if (reference_token == "0")
  11165. {
  11166. // start a new array if reference token is 0
  11167. result = &result->operator[](0);
  11168. }
  11169. else
  11170. {
  11171. // start a new object otherwise
  11172. result = &result->operator[](reference_token);
  11173. }
  11174. break;
  11175. }
  11176. case detail::value_t::object:
  11177. {
  11178. // create an entry in the object
  11179. result = &result->operator[](reference_token);
  11180. break;
  11181. }
  11182. case detail::value_t::array:
  11183. {
  11184. // create an entry in the array
  11185. result = &result->operator[](array_index(reference_token));
  11186. break;
  11187. }
  11188. /*
  11189. The following code is only reached if there exists a reference
  11190. token _and_ the current value is primitive. In this case, we have
  11191. an error situation, because primitive values may only occur as
  11192. single value; that is, with an empty list of reference tokens.
  11193. */
  11194. case detail::value_t::string:
  11195. case detail::value_t::boolean:
  11196. case detail::value_t::number_integer:
  11197. case detail::value_t::number_unsigned:
  11198. case detail::value_t::number_float:
  11199. case detail::value_t::binary:
  11200. case detail::value_t::discarded:
  11201. default:
  11202. JSON_THROW(detail::type_error::create(313, "invalid value to unflatten", j));
  11203. }
  11204. }
  11205. return *result;
  11206. }
  11207. /*!
  11208. @brief return a reference to the pointed to value
  11209. @note This version does not throw if a value is not present, but tries to
  11210. create nested values instead. For instance, calling this function
  11211. with pointer `"/this/that"` on a null value is equivalent to calling
  11212. `operator[]("this").operator[]("that")` on that value, effectively
  11213. changing the null value to an object.
  11214. @param[in] ptr a JSON value
  11215. @return reference to the JSON value pointed to by the JSON pointer
  11216. @complexity Linear in the length of the JSON pointer.
  11217. @throw parse_error.106 if an array index begins with '0'
  11218. @throw parse_error.109 if an array index was not a number
  11219. @throw out_of_range.404 if the JSON pointer can not be resolved
  11220. */
  11221. BasicJsonType& get_unchecked(BasicJsonType* ptr) const
  11222. {
  11223. for (const auto& reference_token : reference_tokens)
  11224. {
  11225. // convert null values to arrays or objects before continuing
  11226. if (ptr->is_null())
  11227. {
  11228. // check if reference token is a number
  11229. const bool nums =
  11230. std::all_of(reference_token.begin(), reference_token.end(),
  11231. [](const unsigned char x)
  11232. {
  11233. return std::isdigit(x);
  11234. });
  11235. // change value to array for numbers or "-" or to object otherwise
  11236. *ptr = (nums || reference_token == "-")
  11237. ? detail::value_t::array
  11238. : detail::value_t::object;
  11239. }
  11240. switch (ptr->type())
  11241. {
  11242. case detail::value_t::object:
  11243. {
  11244. // use unchecked object access
  11245. ptr = &ptr->operator[](reference_token);
  11246. break;
  11247. }
  11248. case detail::value_t::array:
  11249. {
  11250. if (reference_token == "-")
  11251. {
  11252. // explicitly treat "-" as index beyond the end
  11253. ptr = &ptr->operator[](ptr->m_value.array->size());
  11254. }
  11255. else
  11256. {
  11257. // convert array index to number; unchecked access
  11258. ptr = &ptr->operator[](array_index(reference_token));
  11259. }
  11260. break;
  11261. }
  11262. case detail::value_t::null:
  11263. case detail::value_t::string:
  11264. case detail::value_t::boolean:
  11265. case detail::value_t::number_integer:
  11266. case detail::value_t::number_unsigned:
  11267. case detail::value_t::number_float:
  11268. case detail::value_t::binary:
  11269. case detail::value_t::discarded:
  11270. default:
  11271. JSON_THROW(detail::out_of_range::create(404, "unresolved reference token '" + reference_token + "'", *ptr));
  11272. }
  11273. }
  11274. return *ptr;
  11275. }
  11276. /*!
  11277. @throw parse_error.106 if an array index begins with '0'
  11278. @throw parse_error.109 if an array index was not a number
  11279. @throw out_of_range.402 if the array index '-' is used
  11280. @throw out_of_range.404 if the JSON pointer can not be resolved
  11281. */
  11282. BasicJsonType& get_checked(BasicJsonType* ptr) const
  11283. {
  11284. for (const auto& reference_token : reference_tokens)
  11285. {
  11286. switch (ptr->type())
  11287. {
  11288. case detail::value_t::object:
  11289. {
  11290. // note: at performs range check
  11291. ptr = &ptr->at(reference_token);
  11292. break;
  11293. }
  11294. case detail::value_t::array:
  11295. {
  11296. if (JSON_HEDLEY_UNLIKELY(reference_token == "-"))
  11297. {
  11298. // "-" always fails the range check
  11299. JSON_THROW(detail::out_of_range::create(402,
  11300. "array index '-' (" + std::to_string(ptr->m_value.array->size()) +
  11301. ") is out of range", *ptr));
  11302. }
  11303. // note: at performs range check
  11304. ptr = &ptr->at(array_index(reference_token));
  11305. break;
  11306. }
  11307. case detail::value_t::null:
  11308. case detail::value_t::string:
  11309. case detail::value_t::boolean:
  11310. case detail::value_t::number_integer:
  11311. case detail::value_t::number_unsigned:
  11312. case detail::value_t::number_float:
  11313. case detail::value_t::binary:
  11314. case detail::value_t::discarded:
  11315. default:
  11316. JSON_THROW(detail::out_of_range::create(404, "unresolved reference token '" + reference_token + "'", *ptr));
  11317. }
  11318. }
  11319. return *ptr;
  11320. }
  11321. /*!
  11322. @brief return a const reference to the pointed to value
  11323. @param[in] ptr a JSON value
  11324. @return const reference to the JSON value pointed to by the JSON
  11325. pointer
  11326. @throw parse_error.106 if an array index begins with '0'
  11327. @throw parse_error.109 if an array index was not a number
  11328. @throw out_of_range.402 if the array index '-' is used
  11329. @throw out_of_range.404 if the JSON pointer can not be resolved
  11330. */
  11331. const BasicJsonType& get_unchecked(const BasicJsonType* ptr) const
  11332. {
  11333. for (const auto& reference_token : reference_tokens)
  11334. {
  11335. switch (ptr->type())
  11336. {
  11337. case detail::value_t::object:
  11338. {
  11339. // use unchecked object access
  11340. ptr = &ptr->operator[](reference_token);
  11341. break;
  11342. }
  11343. case detail::value_t::array:
  11344. {
  11345. if (JSON_HEDLEY_UNLIKELY(reference_token == "-"))
  11346. {
  11347. // "-" cannot be used for const access
  11348. JSON_THROW(detail::out_of_range::create(402, "array index '-' (" + std::to_string(ptr->m_value.array->size()) + ") is out of range", *ptr));
  11349. }
  11350. // use unchecked array access
  11351. ptr = &ptr->operator[](array_index(reference_token));
  11352. break;
  11353. }
  11354. case detail::value_t::null:
  11355. case detail::value_t::string:
  11356. case detail::value_t::boolean:
  11357. case detail::value_t::number_integer:
  11358. case detail::value_t::number_unsigned:
  11359. case detail::value_t::number_float:
  11360. case detail::value_t::binary:
  11361. case detail::value_t::discarded:
  11362. default:
  11363. JSON_THROW(detail::out_of_range::create(404, "unresolved reference token '" + reference_token + "'", *ptr));
  11364. }
  11365. }
  11366. return *ptr;
  11367. }
  11368. /*!
  11369. @throw parse_error.106 if an array index begins with '0'
  11370. @throw parse_error.109 if an array index was not a number
  11371. @throw out_of_range.402 if the array index '-' is used
  11372. @throw out_of_range.404 if the JSON pointer can not be resolved
  11373. */
  11374. const BasicJsonType& get_checked(const BasicJsonType* ptr) const
  11375. {
  11376. for (const auto& reference_token : reference_tokens)
  11377. {
  11378. switch (ptr->type())
  11379. {
  11380. case detail::value_t::object:
  11381. {
  11382. // note: at performs range check
  11383. ptr = &ptr->at(reference_token);
  11384. break;
  11385. }
  11386. case detail::value_t::array:
  11387. {
  11388. if (JSON_HEDLEY_UNLIKELY(reference_token == "-"))
  11389. {
  11390. // "-" always fails the range check
  11391. JSON_THROW(detail::out_of_range::create(402,
  11392. "array index '-' (" + std::to_string(ptr->m_value.array->size()) +
  11393. ") is out of range", *ptr));
  11394. }
  11395. // note: at performs range check
  11396. ptr = &ptr->at(array_index(reference_token));
  11397. break;
  11398. }
  11399. case detail::value_t::null:
  11400. case detail::value_t::string:
  11401. case detail::value_t::boolean:
  11402. case detail::value_t::number_integer:
  11403. case detail::value_t::number_unsigned:
  11404. case detail::value_t::number_float:
  11405. case detail::value_t::binary:
  11406. case detail::value_t::discarded:
  11407. default:
  11408. JSON_THROW(detail::out_of_range::create(404, "unresolved reference token '" + reference_token + "'", *ptr));
  11409. }
  11410. }
  11411. return *ptr;
  11412. }
  11413. /*!
  11414. @throw parse_error.106 if an array index begins with '0'
  11415. @throw parse_error.109 if an array index was not a number
  11416. */
  11417. bool contains(const BasicJsonType* ptr) const
  11418. {
  11419. for (const auto& reference_token : reference_tokens)
  11420. {
  11421. switch (ptr->type())
  11422. {
  11423. case detail::value_t::object:
  11424. {
  11425. if (!ptr->contains(reference_token))
  11426. {
  11427. // we did not find the key in the object
  11428. return false;
  11429. }
  11430. ptr = &ptr->operator[](reference_token);
  11431. break;
  11432. }
  11433. case detail::value_t::array:
  11434. {
  11435. if (JSON_HEDLEY_UNLIKELY(reference_token == "-"))
  11436. {
  11437. // "-" always fails the range check
  11438. return false;
  11439. }
  11440. if (JSON_HEDLEY_UNLIKELY(reference_token.size() == 1 && !("0" <= reference_token && reference_token <= "9")))
  11441. {
  11442. // invalid char
  11443. return false;
  11444. }
  11445. if (JSON_HEDLEY_UNLIKELY(reference_token.size() > 1))
  11446. {
  11447. if (JSON_HEDLEY_UNLIKELY(!('1' <= reference_token[0] && reference_token[0] <= '9')))
  11448. {
  11449. // first char should be between '1' and '9'
  11450. return false;
  11451. }
  11452. for (std::size_t i = 1; i < reference_token.size(); i++)
  11453. {
  11454. if (JSON_HEDLEY_UNLIKELY(!('0' <= reference_token[i] && reference_token[i] <= '9')))
  11455. {
  11456. // other char should be between '0' and '9'
  11457. return false;
  11458. }
  11459. }
  11460. }
  11461. const auto idx = array_index(reference_token);
  11462. if (idx >= ptr->size())
  11463. {
  11464. // index out of range
  11465. return false;
  11466. }
  11467. ptr = &ptr->operator[](idx);
  11468. break;
  11469. }
  11470. case detail::value_t::null:
  11471. case detail::value_t::string:
  11472. case detail::value_t::boolean:
  11473. case detail::value_t::number_integer:
  11474. case detail::value_t::number_unsigned:
  11475. case detail::value_t::number_float:
  11476. case detail::value_t::binary:
  11477. case detail::value_t::discarded:
  11478. default:
  11479. {
  11480. // we do not expect primitive values if there is still a
  11481. // reference token to process
  11482. return false;
  11483. }
  11484. }
  11485. }
  11486. // no reference token left means we found a primitive value
  11487. return true;
  11488. }
  11489. /*!
  11490. @brief split the string input to reference tokens
  11491. @note This function is only called by the json_pointer constructor.
  11492. All exceptions below are documented there.
  11493. @throw parse_error.107 if the pointer is not empty or begins with '/'
  11494. @throw parse_error.108 if character '~' is not followed by '0' or '1'
  11495. */
  11496. static std::vector<std::string> split(const std::string& reference_string)
  11497. {
  11498. std::vector<std::string> result;
  11499. // special case: empty reference string -> no reference tokens
  11500. if (reference_string.empty())
  11501. {
  11502. return result;
  11503. }
  11504. // check if nonempty reference string begins with slash
  11505. if (JSON_HEDLEY_UNLIKELY(reference_string[0] != '/'))
  11506. {
  11507. JSON_THROW(detail::parse_error::create(107, 1, "JSON pointer must be empty or begin with '/' - was: '" + reference_string + "'", BasicJsonType()));
  11508. }
  11509. // extract the reference tokens:
  11510. // - slash: position of the last read slash (or end of string)
  11511. // - start: position after the previous slash
  11512. for (
  11513. // search for the first slash after the first character
  11514. std::size_t slash = reference_string.find_first_of('/', 1),
  11515. // set the beginning of the first reference token
  11516. start = 1;
  11517. // we can stop if start == 0 (if slash == std::string::npos)
  11518. start != 0;
  11519. // set the beginning of the next reference token
  11520. // (will eventually be 0 if slash == std::string::npos)
  11521. start = (slash == std::string::npos) ? 0 : slash + 1,
  11522. // find next slash
  11523. slash = reference_string.find_first_of('/', start))
  11524. {
  11525. // use the text between the beginning of the reference token
  11526. // (start) and the last slash (slash).
  11527. auto reference_token = reference_string.substr(start, slash - start);
  11528. // check reference tokens are properly escaped
  11529. for (std::size_t pos = reference_token.find_first_of('~');
  11530. pos != std::string::npos;
  11531. pos = reference_token.find_first_of('~', pos + 1))
  11532. {
  11533. JSON_ASSERT(reference_token[pos] == '~');
  11534. // ~ must be followed by 0 or 1
  11535. if (JSON_HEDLEY_UNLIKELY(pos == reference_token.size() - 1 ||
  11536. (reference_token[pos + 1] != '0' &&
  11537. reference_token[pos + 1] != '1')))
  11538. {
  11539. JSON_THROW(detail::parse_error::create(108, 0, "escape character '~' must be followed with '0' or '1'", BasicJsonType()));
  11540. }
  11541. }
  11542. // finally, store the reference token
  11543. detail::unescape(reference_token);
  11544. result.push_back(reference_token);
  11545. }
  11546. return result;
  11547. }
  11548. private:
  11549. /*!
  11550. @param[in] reference_string the reference string to the current value
  11551. @param[in] value the value to consider
  11552. @param[in,out] result the result object to insert values to
  11553. @note Empty objects or arrays are flattened to `null`.
  11554. */
  11555. static void flatten(const std::string& reference_string,
  11556. const BasicJsonType& value,
  11557. BasicJsonType& result)
  11558. {
  11559. switch (value.type())
  11560. {
  11561. case detail::value_t::array:
  11562. {
  11563. if (value.m_value.array->empty())
  11564. {
  11565. // flatten empty array as null
  11566. result[reference_string] = nullptr;
  11567. }
  11568. else
  11569. {
  11570. // iterate array and use index as reference string
  11571. for (std::size_t i = 0; i < value.m_value.array->size(); ++i)
  11572. {
  11573. flatten(reference_string + "/" + std::to_string(i),
  11574. value.m_value.array->operator[](i), result);
  11575. }
  11576. }
  11577. break;
  11578. }
  11579. case detail::value_t::object:
  11580. {
  11581. if (value.m_value.object->empty())
  11582. {
  11583. // flatten empty object as null
  11584. result[reference_string] = nullptr;
  11585. }
  11586. else
  11587. {
  11588. // iterate object and use keys as reference string
  11589. for (const auto& element : *value.m_value.object)
  11590. {
  11591. flatten(reference_string + "/" + detail::escape(element.first), element.second, result);
  11592. }
  11593. }
  11594. break;
  11595. }
  11596. case detail::value_t::null:
  11597. case detail::value_t::string:
  11598. case detail::value_t::boolean:
  11599. case detail::value_t::number_integer:
  11600. case detail::value_t::number_unsigned:
  11601. case detail::value_t::number_float:
  11602. case detail::value_t::binary:
  11603. case detail::value_t::discarded:
  11604. default:
  11605. {
  11606. // add primitive value with its reference string
  11607. result[reference_string] = value;
  11608. break;
  11609. }
  11610. }
  11611. }
  11612. /*!
  11613. @param[in] value flattened JSON
  11614. @return unflattened JSON
  11615. @throw parse_error.109 if array index is not a number
  11616. @throw type_error.314 if value is not an object
  11617. @throw type_error.315 if object values are not primitive
  11618. @throw type_error.313 if value cannot be unflattened
  11619. */
  11620. static BasicJsonType
  11621. unflatten(const BasicJsonType& value)
  11622. {
  11623. if (JSON_HEDLEY_UNLIKELY(!value.is_object()))
  11624. {
  11625. JSON_THROW(detail::type_error::create(314, "only objects can be unflattened", value));
  11626. }
  11627. BasicJsonType result;
  11628. // iterate the JSON object values
  11629. for (const auto& element : *value.m_value.object)
  11630. {
  11631. if (JSON_HEDLEY_UNLIKELY(!element.second.is_primitive()))
  11632. {
  11633. JSON_THROW(detail::type_error::create(315, "values in object must be primitive", element.second));
  11634. }
  11635. // assign value to reference pointed to by JSON pointer; Note that if
  11636. // the JSON pointer is "" (i.e., points to the whole value), function
  11637. // get_and_create returns a reference to result itself. An assignment
  11638. // will then create a primitive value.
  11639. json_pointer(element.first).get_and_create(result) = element.second;
  11640. }
  11641. return result;
  11642. }
  11643. /*!
  11644. @brief compares two JSON pointers for equality
  11645. @param[in] lhs JSON pointer to compare
  11646. @param[in] rhs JSON pointer to compare
  11647. @return whether @a lhs is equal to @a rhs
  11648. @complexity Linear in the length of the JSON pointer
  11649. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  11650. */
  11651. friend bool operator==(json_pointer const& lhs,
  11652. json_pointer const& rhs) noexcept
  11653. {
  11654. return lhs.reference_tokens == rhs.reference_tokens;
  11655. }
  11656. /*!
  11657. @brief compares two JSON pointers for inequality
  11658. @param[in] lhs JSON pointer to compare
  11659. @param[in] rhs JSON pointer to compare
  11660. @return whether @a lhs is not equal @a rhs
  11661. @complexity Linear in the length of the JSON pointer
  11662. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  11663. */
  11664. friend bool operator!=(json_pointer const& lhs,
  11665. json_pointer const& rhs) noexcept
  11666. {
  11667. return !(lhs == rhs);
  11668. }
  11669. /// the reference tokens
  11670. std::vector<std::string> reference_tokens;
  11671. };
  11672. } // namespace nlohmann
  11673. // #include <nlohmann/detail/json_ref.hpp>
  11674. #include <initializer_list>
  11675. #include <utility>
  11676. // #include <nlohmann/detail/meta/type_traits.hpp>
  11677. namespace nlohmann
  11678. {
  11679. namespace detail
  11680. {
  11681. template<typename BasicJsonType>
  11682. class json_ref
  11683. {
  11684. public:
  11685. using value_type = BasicJsonType;
  11686. json_ref(value_type&& value)
  11687. : owned_value(std::move(value))
  11688. {}
  11689. json_ref(const value_type& value)
  11690. : value_ref(&value)
  11691. {}
  11692. json_ref(std::initializer_list<json_ref> init)
  11693. : owned_value(init)
  11694. {}
  11695. template <
  11696. class... Args,
  11697. enable_if_t<std::is_constructible<value_type, Args...>::value, int> = 0 >
  11698. json_ref(Args && ... args)
  11699. : owned_value(std::forward<Args>(args)...)
  11700. {}
  11701. // class should be movable only
  11702. json_ref(json_ref&&) noexcept = default;
  11703. json_ref(const json_ref&) = delete;
  11704. json_ref& operator=(const json_ref&) = delete;
  11705. json_ref& operator=(json_ref&&) = delete;
  11706. ~json_ref() = default;
  11707. value_type moved_or_copied() const
  11708. {
  11709. if (value_ref == nullptr)
  11710. {
  11711. return std::move(owned_value);
  11712. }
  11713. return *value_ref;
  11714. }
  11715. value_type const& operator*() const
  11716. {
  11717. return value_ref ? *value_ref : owned_value;
  11718. }
  11719. value_type const* operator->() const
  11720. {
  11721. return &** this;
  11722. }
  11723. private:
  11724. mutable value_type owned_value = nullptr;
  11725. value_type const* value_ref = nullptr;
  11726. };
  11727. } // namespace detail
  11728. } // namespace nlohmann
  11729. // #include <nlohmann/detail/macro_scope.hpp>
  11730. // #include <nlohmann/detail/string_escape.hpp>
  11731. // #include <nlohmann/detail/meta/cpp_future.hpp>
  11732. // #include <nlohmann/detail/meta/type_traits.hpp>
  11733. // #include <nlohmann/detail/output/binary_writer.hpp>
  11734. #include <algorithm> // reverse
  11735. #include <array> // array
  11736. #include <cmath> // isnan, isinf
  11737. #include <cstdint> // uint8_t, uint16_t, uint32_t, uint64_t
  11738. #include <cstring> // memcpy
  11739. #include <limits> // numeric_limits
  11740. #include <string> // string
  11741. #include <utility> // move
  11742. // #include <nlohmann/detail/input/binary_reader.hpp>
  11743. // #include <nlohmann/detail/macro_scope.hpp>
  11744. // #include <nlohmann/detail/output/output_adapters.hpp>
  11745. #include <algorithm> // copy
  11746. #include <cstddef> // size_t
  11747. #include <iterator> // back_inserter
  11748. #include <memory> // shared_ptr, make_shared
  11749. #include <string> // basic_string
  11750. #include <vector> // vector
  11751. #ifndef JSON_NO_IO
  11752. #include <ios> // streamsize
  11753. #include <ostream> // basic_ostream
  11754. #endif // JSON_NO_IO
  11755. // #include <nlohmann/detail/macro_scope.hpp>
  11756. namespace nlohmann
  11757. {
  11758. namespace detail
  11759. {
  11760. /// abstract output adapter interface
  11761. template<typename CharType> struct output_adapter_protocol
  11762. {
  11763. virtual void write_character(CharType c) = 0;
  11764. virtual void write_characters(const CharType* s, std::size_t length) = 0;
  11765. virtual ~output_adapter_protocol() = default;
  11766. output_adapter_protocol() = default;
  11767. output_adapter_protocol(const output_adapter_protocol&) = default;
  11768. output_adapter_protocol(output_adapter_protocol&&) noexcept = default;
  11769. output_adapter_protocol& operator=(const output_adapter_protocol&) = default;
  11770. output_adapter_protocol& operator=(output_adapter_protocol&&) noexcept = default;
  11771. };
  11772. /// a type to simplify interfaces
  11773. template<typename CharType>
  11774. using output_adapter_t = std::shared_ptr<output_adapter_protocol<CharType>>;
  11775. /// output adapter for byte vectors
  11776. template<typename CharType, typename AllocatorType = std::allocator<CharType>>
  11777. class output_vector_adapter : public output_adapter_protocol<CharType>
  11778. {
  11779. public:
  11780. explicit output_vector_adapter(std::vector<CharType, AllocatorType>& vec) noexcept
  11781. : v(vec)
  11782. {}
  11783. void write_character(CharType c) override
  11784. {
  11785. v.push_back(c);
  11786. }
  11787. JSON_HEDLEY_NON_NULL(2)
  11788. void write_characters(const CharType* s, std::size_t length) override
  11789. {
  11790. std::copy(s, s + length, std::back_inserter(v));
  11791. }
  11792. private:
  11793. std::vector<CharType, AllocatorType>& v;
  11794. };
  11795. #ifndef JSON_NO_IO
  11796. /// output adapter for output streams
  11797. template<typename CharType>
  11798. class output_stream_adapter : public output_adapter_protocol<CharType>
  11799. {
  11800. public:
  11801. explicit output_stream_adapter(std::basic_ostream<CharType>& s) noexcept
  11802. : stream(s)
  11803. {}
  11804. void write_character(CharType c) override
  11805. {
  11806. stream.put(c);
  11807. }
  11808. JSON_HEDLEY_NON_NULL(2)
  11809. void write_characters(const CharType* s, std::size_t length) override
  11810. {
  11811. stream.write(s, static_cast<std::streamsize>(length));
  11812. }
  11813. private:
  11814. std::basic_ostream<CharType>& stream;
  11815. };
  11816. #endif // JSON_NO_IO
  11817. /// output adapter for basic_string
  11818. template<typename CharType, typename StringType = std::basic_string<CharType>>
  11819. class output_string_adapter : public output_adapter_protocol<CharType>
  11820. {
  11821. public:
  11822. explicit output_string_adapter(StringType& s) noexcept
  11823. : str(s)
  11824. {}
  11825. void write_character(CharType c) override
  11826. {
  11827. str.push_back(c);
  11828. }
  11829. JSON_HEDLEY_NON_NULL(2)
  11830. void write_characters(const CharType* s, std::size_t length) override
  11831. {
  11832. str.append(s, length);
  11833. }
  11834. private:
  11835. StringType& str;
  11836. };
  11837. template<typename CharType, typename StringType = std::basic_string<CharType>>
  11838. class output_adapter
  11839. {
  11840. public:
  11841. template<typename AllocatorType = std::allocator<CharType>>
  11842. output_adapter(std::vector<CharType, AllocatorType>& vec)
  11843. : oa(std::make_shared<output_vector_adapter<CharType, AllocatorType>>(vec)) {}
  11844. #ifndef JSON_NO_IO
  11845. output_adapter(std::basic_ostream<CharType>& s)
  11846. : oa(std::make_shared<output_stream_adapter<CharType>>(s)) {}
  11847. #endif // JSON_NO_IO
  11848. output_adapter(StringType& s)
  11849. : oa(std::make_shared<output_string_adapter<CharType, StringType>>(s)) {}
  11850. operator output_adapter_t<CharType>()
  11851. {
  11852. return oa;
  11853. }
  11854. private:
  11855. output_adapter_t<CharType> oa = nullptr;
  11856. };
  11857. } // namespace detail
  11858. } // namespace nlohmann
  11859. namespace nlohmann
  11860. {
  11861. namespace detail
  11862. {
  11863. ///////////////////
  11864. // binary writer //
  11865. ///////////////////
  11866. /*!
  11867. @brief serialization to CBOR and MessagePack values
  11868. */
  11869. template<typename BasicJsonType, typename CharType>
  11870. class binary_writer
  11871. {
  11872. using string_t = typename BasicJsonType::string_t;
  11873. using binary_t = typename BasicJsonType::binary_t;
  11874. using number_float_t = typename BasicJsonType::number_float_t;
  11875. public:
  11876. /*!
  11877. @brief create a binary writer
  11878. @param[in] adapter output adapter to write to
  11879. */
  11880. explicit binary_writer(output_adapter_t<CharType> adapter) : oa(std::move(adapter))
  11881. {
  11882. JSON_ASSERT(oa);
  11883. }
  11884. /*!
  11885. @param[in] j JSON value to serialize
  11886. @pre j.type() == value_t::object
  11887. */
  11888. void write_bson(const BasicJsonType& j)
  11889. {
  11890. switch (j.type())
  11891. {
  11892. case value_t::object:
  11893. {
  11894. write_bson_object(*j.m_value.object);
  11895. break;
  11896. }
  11897. case value_t::null:
  11898. case value_t::array:
  11899. case value_t::string:
  11900. case value_t::boolean:
  11901. case value_t::number_integer:
  11902. case value_t::number_unsigned:
  11903. case value_t::number_float:
  11904. case value_t::binary:
  11905. case value_t::discarded:
  11906. default:
  11907. {
  11908. JSON_THROW(type_error::create(317, "to serialize to BSON, top-level type must be object, but is " + std::string(j.type_name()), j));
  11909. }
  11910. }
  11911. }
  11912. /*!
  11913. @param[in] j JSON value to serialize
  11914. */
  11915. void write_cbor(const BasicJsonType& j)
  11916. {
  11917. switch (j.type())
  11918. {
  11919. case value_t::null:
  11920. {
  11921. oa->write_character(to_char_type(0xF6));
  11922. break;
  11923. }
  11924. case value_t::boolean:
  11925. {
  11926. oa->write_character(j.m_value.boolean
  11927. ? to_char_type(0xF5)
  11928. : to_char_type(0xF4));
  11929. break;
  11930. }
  11931. case value_t::number_integer:
  11932. {
  11933. if (j.m_value.number_integer >= 0)
  11934. {
  11935. // CBOR does not differentiate between positive signed
  11936. // integers and unsigned integers. Therefore, we used the
  11937. // code from the value_t::number_unsigned case here.
  11938. if (j.m_value.number_integer <= 0x17)
  11939. {
  11940. write_number(static_cast<std::uint8_t>(j.m_value.number_integer));
  11941. }
  11942. else if (j.m_value.number_integer <= (std::numeric_limits<std::uint8_t>::max)())
  11943. {
  11944. oa->write_character(to_char_type(0x18));
  11945. write_number(static_cast<std::uint8_t>(j.m_value.number_integer));
  11946. }
  11947. else if (j.m_value.number_integer <= (std::numeric_limits<std::uint16_t>::max)())
  11948. {
  11949. oa->write_character(to_char_type(0x19));
  11950. write_number(static_cast<std::uint16_t>(j.m_value.number_integer));
  11951. }
  11952. else if (j.m_value.number_integer <= (std::numeric_limits<std::uint32_t>::max)())
  11953. {
  11954. oa->write_character(to_char_type(0x1A));
  11955. write_number(static_cast<std::uint32_t>(j.m_value.number_integer));
  11956. }
  11957. else
  11958. {
  11959. oa->write_character(to_char_type(0x1B));
  11960. write_number(static_cast<std::uint64_t>(j.m_value.number_integer));
  11961. }
  11962. }
  11963. else
  11964. {
  11965. // The conversions below encode the sign in the first
  11966. // byte, and the value is converted to a positive number.
  11967. const auto positive_number = -1 - j.m_value.number_integer;
  11968. if (j.m_value.number_integer >= -24)
  11969. {
  11970. write_number(static_cast<std::uint8_t>(0x20 + positive_number));
  11971. }
  11972. else if (positive_number <= (std::numeric_limits<std::uint8_t>::max)())
  11973. {
  11974. oa->write_character(to_char_type(0x38));
  11975. write_number(static_cast<std::uint8_t>(positive_number));
  11976. }
  11977. else if (positive_number <= (std::numeric_limits<std::uint16_t>::max)())
  11978. {
  11979. oa->write_character(to_char_type(0x39));
  11980. write_number(static_cast<std::uint16_t>(positive_number));
  11981. }
  11982. else if (positive_number <= (std::numeric_limits<std::uint32_t>::max)())
  11983. {
  11984. oa->write_character(to_char_type(0x3A));
  11985. write_number(static_cast<std::uint32_t>(positive_number));
  11986. }
  11987. else
  11988. {
  11989. oa->write_character(to_char_type(0x3B));
  11990. write_number(static_cast<std::uint64_t>(positive_number));
  11991. }
  11992. }
  11993. break;
  11994. }
  11995. case value_t::number_unsigned:
  11996. {
  11997. if (j.m_value.number_unsigned <= 0x17)
  11998. {
  11999. write_number(static_cast<std::uint8_t>(j.m_value.number_unsigned));
  12000. }
  12001. else if (j.m_value.number_unsigned <= (std::numeric_limits<std::uint8_t>::max)())
  12002. {
  12003. oa->write_character(to_char_type(0x18));
  12004. write_number(static_cast<std::uint8_t>(j.m_value.number_unsigned));
  12005. }
  12006. else if (j.m_value.number_unsigned <= (std::numeric_limits<std::uint16_t>::max)())
  12007. {
  12008. oa->write_character(to_char_type(0x19));
  12009. write_number(static_cast<std::uint16_t>(j.m_value.number_unsigned));
  12010. }
  12011. else if (j.m_value.number_unsigned <= (std::numeric_limits<std::uint32_t>::max)())
  12012. {
  12013. oa->write_character(to_char_type(0x1A));
  12014. write_number(static_cast<std::uint32_t>(j.m_value.number_unsigned));
  12015. }
  12016. else
  12017. {
  12018. oa->write_character(to_char_type(0x1B));
  12019. write_number(static_cast<std::uint64_t>(j.m_value.number_unsigned));
  12020. }
  12021. break;
  12022. }
  12023. case value_t::number_float:
  12024. {
  12025. if (std::isnan(j.m_value.number_float))
  12026. {
  12027. // NaN is 0xf97e00 in CBOR
  12028. oa->write_character(to_char_type(0xF9));
  12029. oa->write_character(to_char_type(0x7E));
  12030. oa->write_character(to_char_type(0x00));
  12031. }
  12032. else if (std::isinf(j.m_value.number_float))
  12033. {
  12034. // Infinity is 0xf97c00, -Infinity is 0xf9fc00
  12035. oa->write_character(to_char_type(0xf9));
  12036. oa->write_character(j.m_value.number_float > 0 ? to_char_type(0x7C) : to_char_type(0xFC));
  12037. oa->write_character(to_char_type(0x00));
  12038. }
  12039. else
  12040. {
  12041. write_compact_float(j.m_value.number_float, detail::input_format_t::cbor);
  12042. }
  12043. break;
  12044. }
  12045. case value_t::string:
  12046. {
  12047. // step 1: write control byte and the string length
  12048. const auto N = j.m_value.string->size();
  12049. if (N <= 0x17)
  12050. {
  12051. write_number(static_cast<std::uint8_t>(0x60 + N));
  12052. }
  12053. else if (N <= (std::numeric_limits<std::uint8_t>::max)())
  12054. {
  12055. oa->write_character(to_char_type(0x78));
  12056. write_number(static_cast<std::uint8_t>(N));
  12057. }
  12058. else if (N <= (std::numeric_limits<std::uint16_t>::max)())
  12059. {
  12060. oa->write_character(to_char_type(0x79));
  12061. write_number(static_cast<std::uint16_t>(N));
  12062. }
  12063. else if (N <= (std::numeric_limits<std::uint32_t>::max)())
  12064. {
  12065. oa->write_character(to_char_type(0x7A));
  12066. write_number(static_cast<std::uint32_t>(N));
  12067. }
  12068. // LCOV_EXCL_START
  12069. else if (N <= (std::numeric_limits<std::uint64_t>::max)())
  12070. {
  12071. oa->write_character(to_char_type(0x7B));
  12072. write_number(static_cast<std::uint64_t>(N));
  12073. }
  12074. // LCOV_EXCL_STOP
  12075. // step 2: write the string
  12076. oa->write_characters(
  12077. reinterpret_cast<const CharType*>(j.m_value.string->c_str()),
  12078. j.m_value.string->size());
  12079. break;
  12080. }
  12081. case value_t::array:
  12082. {
  12083. // step 1: write control byte and the array size
  12084. const auto N = j.m_value.array->size();
  12085. if (N <= 0x17)
  12086. {
  12087. write_number(static_cast<std::uint8_t>(0x80 + N));
  12088. }
  12089. else if (N <= (std::numeric_limits<std::uint8_t>::max)())
  12090. {
  12091. oa->write_character(to_char_type(0x98));
  12092. write_number(static_cast<std::uint8_t>(N));
  12093. }
  12094. else if (N <= (std::numeric_limits<std::uint16_t>::max)())
  12095. {
  12096. oa->write_character(to_char_type(0x99));
  12097. write_number(static_cast<std::uint16_t>(N));
  12098. }
  12099. else if (N <= (std::numeric_limits<std::uint32_t>::max)())
  12100. {
  12101. oa->write_character(to_char_type(0x9A));
  12102. write_number(static_cast<std::uint32_t>(N));
  12103. }
  12104. // LCOV_EXCL_START
  12105. else if (N <= (std::numeric_limits<std::uint64_t>::max)())
  12106. {
  12107. oa->write_character(to_char_type(0x9B));
  12108. write_number(static_cast<std::uint64_t>(N));
  12109. }
  12110. // LCOV_EXCL_STOP
  12111. // step 2: write each element
  12112. for (const auto& el : *j.m_value.array)
  12113. {
  12114. write_cbor(el);
  12115. }
  12116. break;
  12117. }
  12118. case value_t::binary:
  12119. {
  12120. if (j.m_value.binary->has_subtype())
  12121. {
  12122. if (j.m_value.binary->subtype() <= (std::numeric_limits<std::uint8_t>::max)())
  12123. {
  12124. write_number(static_cast<std::uint8_t>(0xd8));
  12125. write_number(static_cast<std::uint8_t>(j.m_value.binary->subtype()));
  12126. }
  12127. else if (j.m_value.binary->subtype() <= (std::numeric_limits<std::uint16_t>::max)())
  12128. {
  12129. write_number(static_cast<std::uint8_t>(0xd9));
  12130. write_number(static_cast<std::uint16_t>(j.m_value.binary->subtype()));
  12131. }
  12132. else if (j.m_value.binary->subtype() <= (std::numeric_limits<std::uint32_t>::max)())
  12133. {
  12134. write_number(static_cast<std::uint8_t>(0xda));
  12135. write_number(static_cast<std::uint32_t>(j.m_value.binary->subtype()));
  12136. }
  12137. else if (j.m_value.binary->subtype() <= (std::numeric_limits<std::uint64_t>::max)())
  12138. {
  12139. write_number(static_cast<std::uint8_t>(0xdb));
  12140. write_number(static_cast<std::uint64_t>(j.m_value.binary->subtype()));
  12141. }
  12142. }
  12143. // step 1: write control byte and the binary array size
  12144. const auto N = j.m_value.binary->size();
  12145. if (N <= 0x17)
  12146. {
  12147. write_number(static_cast<std::uint8_t>(0x40 + N));
  12148. }
  12149. else if (N <= (std::numeric_limits<std::uint8_t>::max)())
  12150. {
  12151. oa->write_character(to_char_type(0x58));
  12152. write_number(static_cast<std::uint8_t>(N));
  12153. }
  12154. else if (N <= (std::numeric_limits<std::uint16_t>::max)())
  12155. {
  12156. oa->write_character(to_char_type(0x59));
  12157. write_number(static_cast<std::uint16_t>(N));
  12158. }
  12159. else if (N <= (std::numeric_limits<std::uint32_t>::max)())
  12160. {
  12161. oa->write_character(to_char_type(0x5A));
  12162. write_number(static_cast<std::uint32_t>(N));
  12163. }
  12164. // LCOV_EXCL_START
  12165. else if (N <= (std::numeric_limits<std::uint64_t>::max)())
  12166. {
  12167. oa->write_character(to_char_type(0x5B));
  12168. write_number(static_cast<std::uint64_t>(N));
  12169. }
  12170. // LCOV_EXCL_STOP
  12171. // step 2: write each element
  12172. oa->write_characters(
  12173. reinterpret_cast<const CharType*>(j.m_value.binary->data()),
  12174. N);
  12175. break;
  12176. }
  12177. case value_t::object:
  12178. {
  12179. // step 1: write control byte and the object size
  12180. const auto N = j.m_value.object->size();
  12181. if (N <= 0x17)
  12182. {
  12183. write_number(static_cast<std::uint8_t>(0xA0 + N));
  12184. }
  12185. else if (N <= (std::numeric_limits<std::uint8_t>::max)())
  12186. {
  12187. oa->write_character(to_char_type(0xB8));
  12188. write_number(static_cast<std::uint8_t>(N));
  12189. }
  12190. else if (N <= (std::numeric_limits<std::uint16_t>::max)())
  12191. {
  12192. oa->write_character(to_char_type(0xB9));
  12193. write_number(static_cast<std::uint16_t>(N));
  12194. }
  12195. else if (N <= (std::numeric_limits<std::uint32_t>::max)())
  12196. {
  12197. oa->write_character(to_char_type(0xBA));
  12198. write_number(static_cast<std::uint32_t>(N));
  12199. }
  12200. // LCOV_EXCL_START
  12201. else if (N <= (std::numeric_limits<std::uint64_t>::max)())
  12202. {
  12203. oa->write_character(to_char_type(0xBB));
  12204. write_number(static_cast<std::uint64_t>(N));
  12205. }
  12206. // LCOV_EXCL_STOP
  12207. // step 2: write each element
  12208. for (const auto& el : *j.m_value.object)
  12209. {
  12210. write_cbor(el.first);
  12211. write_cbor(el.second);
  12212. }
  12213. break;
  12214. }
  12215. case value_t::discarded:
  12216. default:
  12217. break;
  12218. }
  12219. }
  12220. /*!
  12221. @param[in] j JSON value to serialize
  12222. */
  12223. void write_msgpack(const BasicJsonType& j)
  12224. {
  12225. switch (j.type())
  12226. {
  12227. case value_t::null: // nil
  12228. {
  12229. oa->write_character(to_char_type(0xC0));
  12230. break;
  12231. }
  12232. case value_t::boolean: // true and false
  12233. {
  12234. oa->write_character(j.m_value.boolean
  12235. ? to_char_type(0xC3)
  12236. : to_char_type(0xC2));
  12237. break;
  12238. }
  12239. case value_t::number_integer:
  12240. {
  12241. if (j.m_value.number_integer >= 0)
  12242. {
  12243. // MessagePack does not differentiate between positive
  12244. // signed integers and unsigned integers. Therefore, we used
  12245. // the code from the value_t::number_unsigned case here.
  12246. if (j.m_value.number_unsigned < 128)
  12247. {
  12248. // positive fixnum
  12249. write_number(static_cast<std::uint8_t>(j.m_value.number_integer));
  12250. }
  12251. else if (j.m_value.number_unsigned <= (std::numeric_limits<std::uint8_t>::max)())
  12252. {
  12253. // uint 8
  12254. oa->write_character(to_char_type(0xCC));
  12255. write_number(static_cast<std::uint8_t>(j.m_value.number_integer));
  12256. }
  12257. else if (j.m_value.number_unsigned <= (std::numeric_limits<std::uint16_t>::max)())
  12258. {
  12259. // uint 16
  12260. oa->write_character(to_char_type(0xCD));
  12261. write_number(static_cast<std::uint16_t>(j.m_value.number_integer));
  12262. }
  12263. else if (j.m_value.number_unsigned <= (std::numeric_limits<std::uint32_t>::max)())
  12264. {
  12265. // uint 32
  12266. oa->write_character(to_char_type(0xCE));
  12267. write_number(static_cast<std::uint32_t>(j.m_value.number_integer));
  12268. }
  12269. else if (j.m_value.number_unsigned <= (std::numeric_limits<std::uint64_t>::max)())
  12270. {
  12271. // uint 64
  12272. oa->write_character(to_char_type(0xCF));
  12273. write_number(static_cast<std::uint64_t>(j.m_value.number_integer));
  12274. }
  12275. }
  12276. else
  12277. {
  12278. if (j.m_value.number_integer >= -32)
  12279. {
  12280. // negative fixnum
  12281. write_number(static_cast<std::int8_t>(j.m_value.number_integer));
  12282. }
  12283. else if (j.m_value.number_integer >= (std::numeric_limits<std::int8_t>::min)() &&
  12284. j.m_value.number_integer <= (std::numeric_limits<std::int8_t>::max)())
  12285. {
  12286. // int 8
  12287. oa->write_character(to_char_type(0xD0));
  12288. write_number(static_cast<std::int8_t>(j.m_value.number_integer));
  12289. }
  12290. else if (j.m_value.number_integer >= (std::numeric_limits<std::int16_t>::min)() &&
  12291. j.m_value.number_integer <= (std::numeric_limits<std::int16_t>::max)())
  12292. {
  12293. // int 16
  12294. oa->write_character(to_char_type(0xD1));
  12295. write_number(static_cast<std::int16_t>(j.m_value.number_integer));
  12296. }
  12297. else if (j.m_value.number_integer >= (std::numeric_limits<std::int32_t>::min)() &&
  12298. j.m_value.number_integer <= (std::numeric_limits<std::int32_t>::max)())
  12299. {
  12300. // int 32
  12301. oa->write_character(to_char_type(0xD2));
  12302. write_number(static_cast<std::int32_t>(j.m_value.number_integer));
  12303. }
  12304. else if (j.m_value.number_integer >= (std::numeric_limits<std::int64_t>::min)() &&
  12305. j.m_value.number_integer <= (std::numeric_limits<std::int64_t>::max)())
  12306. {
  12307. // int 64
  12308. oa->write_character(to_char_type(0xD3));
  12309. write_number(static_cast<std::int64_t>(j.m_value.number_integer));
  12310. }
  12311. }
  12312. break;
  12313. }
  12314. case value_t::number_unsigned:
  12315. {
  12316. if (j.m_value.number_unsigned < 128)
  12317. {
  12318. // positive fixnum
  12319. write_number(static_cast<std::uint8_t>(j.m_value.number_integer));
  12320. }
  12321. else if (j.m_value.number_unsigned <= (std::numeric_limits<std::uint8_t>::max)())
  12322. {
  12323. // uint 8
  12324. oa->write_character(to_char_type(0xCC));
  12325. write_number(static_cast<std::uint8_t>(j.m_value.number_integer));
  12326. }
  12327. else if (j.m_value.number_unsigned <= (std::numeric_limits<std::uint16_t>::max)())
  12328. {
  12329. // uint 16
  12330. oa->write_character(to_char_type(0xCD));
  12331. write_number(static_cast<std::uint16_t>(j.m_value.number_integer));
  12332. }
  12333. else if (j.m_value.number_unsigned <= (std::numeric_limits<std::uint32_t>::max)())
  12334. {
  12335. // uint 32
  12336. oa->write_character(to_char_type(0xCE));
  12337. write_number(static_cast<std::uint32_t>(j.m_value.number_integer));
  12338. }
  12339. else if (j.m_value.number_unsigned <= (std::numeric_limits<std::uint64_t>::max)())
  12340. {
  12341. // uint 64
  12342. oa->write_character(to_char_type(0xCF));
  12343. write_number(static_cast<std::uint64_t>(j.m_value.number_integer));
  12344. }
  12345. break;
  12346. }
  12347. case value_t::number_float:
  12348. {
  12349. write_compact_float(j.m_value.number_float, detail::input_format_t::msgpack);
  12350. break;
  12351. }
  12352. case value_t::string:
  12353. {
  12354. // step 1: write control byte and the string length
  12355. const auto N = j.m_value.string->size();
  12356. if (N <= 31)
  12357. {
  12358. // fixstr
  12359. write_number(static_cast<std::uint8_t>(0xA0 | N));
  12360. }
  12361. else if (N <= (std::numeric_limits<std::uint8_t>::max)())
  12362. {
  12363. // str 8
  12364. oa->write_character(to_char_type(0xD9));
  12365. write_number(static_cast<std::uint8_t>(N));
  12366. }
  12367. else if (N <= (std::numeric_limits<std::uint16_t>::max)())
  12368. {
  12369. // str 16
  12370. oa->write_character(to_char_type(0xDA));
  12371. write_number(static_cast<std::uint16_t>(N));
  12372. }
  12373. else if (N <= (std::numeric_limits<std::uint32_t>::max)())
  12374. {
  12375. // str 32
  12376. oa->write_character(to_char_type(0xDB));
  12377. write_number(static_cast<std::uint32_t>(N));
  12378. }
  12379. // step 2: write the string
  12380. oa->write_characters(
  12381. reinterpret_cast<const CharType*>(j.m_value.string->c_str()),
  12382. j.m_value.string->size());
  12383. break;
  12384. }
  12385. case value_t::array:
  12386. {
  12387. // step 1: write control byte and the array size
  12388. const auto N = j.m_value.array->size();
  12389. if (N <= 15)
  12390. {
  12391. // fixarray
  12392. write_number(static_cast<std::uint8_t>(0x90 | N));
  12393. }
  12394. else if (N <= (std::numeric_limits<std::uint16_t>::max)())
  12395. {
  12396. // array 16
  12397. oa->write_character(to_char_type(0xDC));
  12398. write_number(static_cast<std::uint16_t>(N));
  12399. }
  12400. else if (N <= (std::numeric_limits<std::uint32_t>::max)())
  12401. {
  12402. // array 32
  12403. oa->write_character(to_char_type(0xDD));
  12404. write_number(static_cast<std::uint32_t>(N));
  12405. }
  12406. // step 2: write each element
  12407. for (const auto& el : *j.m_value.array)
  12408. {
  12409. write_msgpack(el);
  12410. }
  12411. break;
  12412. }
  12413. case value_t::binary:
  12414. {
  12415. // step 0: determine if the binary type has a set subtype to
  12416. // determine whether or not to use the ext or fixext types
  12417. const bool use_ext = j.m_value.binary->has_subtype();
  12418. // step 1: write control byte and the byte string length
  12419. const auto N = j.m_value.binary->size();
  12420. if (N <= (std::numeric_limits<std::uint8_t>::max)())
  12421. {
  12422. std::uint8_t output_type{};
  12423. bool fixed = true;
  12424. if (use_ext)
  12425. {
  12426. switch (N)
  12427. {
  12428. case 1:
  12429. output_type = 0xD4; // fixext 1
  12430. break;
  12431. case 2:
  12432. output_type = 0xD5; // fixext 2
  12433. break;
  12434. case 4:
  12435. output_type = 0xD6; // fixext 4
  12436. break;
  12437. case 8:
  12438. output_type = 0xD7; // fixext 8
  12439. break;
  12440. case 16:
  12441. output_type = 0xD8; // fixext 16
  12442. break;
  12443. default:
  12444. output_type = 0xC7; // ext 8
  12445. fixed = false;
  12446. break;
  12447. }
  12448. }
  12449. else
  12450. {
  12451. output_type = 0xC4; // bin 8
  12452. fixed = false;
  12453. }
  12454. oa->write_character(to_char_type(output_type));
  12455. if (!fixed)
  12456. {
  12457. write_number(static_cast<std::uint8_t>(N));
  12458. }
  12459. }
  12460. else if (N <= (std::numeric_limits<std::uint16_t>::max)())
  12461. {
  12462. std::uint8_t output_type = use_ext
  12463. ? 0xC8 // ext 16
  12464. : 0xC5; // bin 16
  12465. oa->write_character(to_char_type(output_type));
  12466. write_number(static_cast<std::uint16_t>(N));
  12467. }
  12468. else if (N <= (std::numeric_limits<std::uint32_t>::max)())
  12469. {
  12470. std::uint8_t output_type = use_ext
  12471. ? 0xC9 // ext 32
  12472. : 0xC6; // bin 32
  12473. oa->write_character(to_char_type(output_type));
  12474. write_number(static_cast<std::uint32_t>(N));
  12475. }
  12476. // step 1.5: if this is an ext type, write the subtype
  12477. if (use_ext)
  12478. {
  12479. write_number(static_cast<std::int8_t>(j.m_value.binary->subtype()));
  12480. }
  12481. // step 2: write the byte string
  12482. oa->write_characters(
  12483. reinterpret_cast<const CharType*>(j.m_value.binary->data()),
  12484. N);
  12485. break;
  12486. }
  12487. case value_t::object:
  12488. {
  12489. // step 1: write control byte and the object size
  12490. const auto N = j.m_value.object->size();
  12491. if (N <= 15)
  12492. {
  12493. // fixmap
  12494. write_number(static_cast<std::uint8_t>(0x80 | (N & 0xF)));
  12495. }
  12496. else if (N <= (std::numeric_limits<std::uint16_t>::max)())
  12497. {
  12498. // map 16
  12499. oa->write_character(to_char_type(0xDE));
  12500. write_number(static_cast<std::uint16_t>(N));
  12501. }
  12502. else if (N <= (std::numeric_limits<std::uint32_t>::max)())
  12503. {
  12504. // map 32
  12505. oa->write_character(to_char_type(0xDF));
  12506. write_number(static_cast<std::uint32_t>(N));
  12507. }
  12508. // step 2: write each element
  12509. for (const auto& el : *j.m_value.object)
  12510. {
  12511. write_msgpack(el.first);
  12512. write_msgpack(el.second);
  12513. }
  12514. break;
  12515. }
  12516. case value_t::discarded:
  12517. default:
  12518. break;
  12519. }
  12520. }
  12521. /*!
  12522. @param[in] j JSON value to serialize
  12523. @param[in] use_count whether to use '#' prefixes (optimized format)
  12524. @param[in] use_type whether to use '$' prefixes (optimized format)
  12525. @param[in] add_prefix whether prefixes need to be used for this value
  12526. */
  12527. void write_ubjson(const BasicJsonType& j, const bool use_count,
  12528. const bool use_type, const bool add_prefix = true)
  12529. {
  12530. switch (j.type())
  12531. {
  12532. case value_t::null:
  12533. {
  12534. if (add_prefix)
  12535. {
  12536. oa->write_character(to_char_type('Z'));
  12537. }
  12538. break;
  12539. }
  12540. case value_t::boolean:
  12541. {
  12542. if (add_prefix)
  12543. {
  12544. oa->write_character(j.m_value.boolean
  12545. ? to_char_type('T')
  12546. : to_char_type('F'));
  12547. }
  12548. break;
  12549. }
  12550. case value_t::number_integer:
  12551. {
  12552. write_number_with_ubjson_prefix(j.m_value.number_integer, add_prefix);
  12553. break;
  12554. }
  12555. case value_t::number_unsigned:
  12556. {
  12557. write_number_with_ubjson_prefix(j.m_value.number_unsigned, add_prefix);
  12558. break;
  12559. }
  12560. case value_t::number_float:
  12561. {
  12562. write_number_with_ubjson_prefix(j.m_value.number_float, add_prefix);
  12563. break;
  12564. }
  12565. case value_t::string:
  12566. {
  12567. if (add_prefix)
  12568. {
  12569. oa->write_character(to_char_type('S'));
  12570. }
  12571. write_number_with_ubjson_prefix(j.m_value.string->size(), true);
  12572. oa->write_characters(
  12573. reinterpret_cast<const CharType*>(j.m_value.string->c_str()),
  12574. j.m_value.string->size());
  12575. break;
  12576. }
  12577. case value_t::array:
  12578. {
  12579. if (add_prefix)
  12580. {
  12581. oa->write_character(to_char_type('['));
  12582. }
  12583. bool prefix_required = true;
  12584. if (use_type && !j.m_value.array->empty())
  12585. {
  12586. JSON_ASSERT(use_count);
  12587. const CharType first_prefix = ubjson_prefix(j.front());
  12588. const bool same_prefix = std::all_of(j.begin() + 1, j.end(),
  12589. [this, first_prefix](const BasicJsonType & v)
  12590. {
  12591. return ubjson_prefix(v) == first_prefix;
  12592. });
  12593. if (same_prefix)
  12594. {
  12595. prefix_required = false;
  12596. oa->write_character(to_char_type('$'));
  12597. oa->write_character(first_prefix);
  12598. }
  12599. }
  12600. if (use_count)
  12601. {
  12602. oa->write_character(to_char_type('#'));
  12603. write_number_with_ubjson_prefix(j.m_value.array->size(), true);
  12604. }
  12605. for (const auto& el : *j.m_value.array)
  12606. {
  12607. write_ubjson(el, use_count, use_type, prefix_required);
  12608. }
  12609. if (!use_count)
  12610. {
  12611. oa->write_character(to_char_type(']'));
  12612. }
  12613. break;
  12614. }
  12615. case value_t::binary:
  12616. {
  12617. if (add_prefix)
  12618. {
  12619. oa->write_character(to_char_type('['));
  12620. }
  12621. if (use_type && !j.m_value.binary->empty())
  12622. {
  12623. JSON_ASSERT(use_count);
  12624. oa->write_character(to_char_type('$'));
  12625. oa->write_character('U');
  12626. }
  12627. if (use_count)
  12628. {
  12629. oa->write_character(to_char_type('#'));
  12630. write_number_with_ubjson_prefix(j.m_value.binary->size(), true);
  12631. }
  12632. if (use_type)
  12633. {
  12634. oa->write_characters(
  12635. reinterpret_cast<const CharType*>(j.m_value.binary->data()),
  12636. j.m_value.binary->size());
  12637. }
  12638. else
  12639. {
  12640. for (size_t i = 0; i < j.m_value.binary->size(); ++i)
  12641. {
  12642. oa->write_character(to_char_type('U'));
  12643. oa->write_character(j.m_value.binary->data()[i]);
  12644. }
  12645. }
  12646. if (!use_count)
  12647. {
  12648. oa->write_character(to_char_type(']'));
  12649. }
  12650. break;
  12651. }
  12652. case value_t::object:
  12653. {
  12654. if (add_prefix)
  12655. {
  12656. oa->write_character(to_char_type('{'));
  12657. }
  12658. bool prefix_required = true;
  12659. if (use_type && !j.m_value.object->empty())
  12660. {
  12661. JSON_ASSERT(use_count);
  12662. const CharType first_prefix = ubjson_prefix(j.front());
  12663. const bool same_prefix = std::all_of(j.begin(), j.end(),
  12664. [this, first_prefix](const BasicJsonType & v)
  12665. {
  12666. return ubjson_prefix(v) == first_prefix;
  12667. });
  12668. if (same_prefix)
  12669. {
  12670. prefix_required = false;
  12671. oa->write_character(to_char_type('$'));
  12672. oa->write_character(first_prefix);
  12673. }
  12674. }
  12675. if (use_count)
  12676. {
  12677. oa->write_character(to_char_type('#'));
  12678. write_number_with_ubjson_prefix(j.m_value.object->size(), true);
  12679. }
  12680. for (const auto& el : *j.m_value.object)
  12681. {
  12682. write_number_with_ubjson_prefix(el.first.size(), true);
  12683. oa->write_characters(
  12684. reinterpret_cast<const CharType*>(el.first.c_str()),
  12685. el.first.size());
  12686. write_ubjson(el.second, use_count, use_type, prefix_required);
  12687. }
  12688. if (!use_count)
  12689. {
  12690. oa->write_character(to_char_type('}'));
  12691. }
  12692. break;
  12693. }
  12694. case value_t::discarded:
  12695. default:
  12696. break;
  12697. }
  12698. }
  12699. private:
  12700. //////////
  12701. // BSON //
  12702. //////////
  12703. /*!
  12704. @return The size of a BSON document entry header, including the id marker
  12705. and the entry name size (and its null-terminator).
  12706. */
  12707. static std::size_t calc_bson_entry_header_size(const string_t& name, const BasicJsonType& j)
  12708. {
  12709. const auto it = name.find(static_cast<typename string_t::value_type>(0));
  12710. if (JSON_HEDLEY_UNLIKELY(it != BasicJsonType::string_t::npos))
  12711. {
  12712. JSON_THROW(out_of_range::create(409, "BSON key cannot contain code point U+0000 (at byte " + std::to_string(it) + ")", j));
  12713. static_cast<void>(j);
  12714. }
  12715. return /*id*/ 1ul + name.size() + /*zero-terminator*/1u;
  12716. }
  12717. /*!
  12718. @brief Writes the given @a element_type and @a name to the output adapter
  12719. */
  12720. void write_bson_entry_header(const string_t& name,
  12721. const std::uint8_t element_type)
  12722. {
  12723. oa->write_character(to_char_type(element_type)); // boolean
  12724. oa->write_characters(
  12725. reinterpret_cast<const CharType*>(name.c_str()),
  12726. name.size() + 1u);
  12727. }
  12728. /*!
  12729. @brief Writes a BSON element with key @a name and boolean value @a value
  12730. */
  12731. void write_bson_boolean(const string_t& name,
  12732. const bool value)
  12733. {
  12734. write_bson_entry_header(name, 0x08);
  12735. oa->write_character(value ? to_char_type(0x01) : to_char_type(0x00));
  12736. }
  12737. /*!
  12738. @brief Writes a BSON element with key @a name and double value @a value
  12739. */
  12740. void write_bson_double(const string_t& name,
  12741. const double value)
  12742. {
  12743. write_bson_entry_header(name, 0x01);
  12744. write_number<double, true>(value);
  12745. }
  12746. /*!
  12747. @return The size of the BSON-encoded string in @a value
  12748. */
  12749. static std::size_t calc_bson_string_size(const string_t& value)
  12750. {
  12751. return sizeof(std::int32_t) + value.size() + 1ul;
  12752. }
  12753. /*!
  12754. @brief Writes a BSON element with key @a name and string value @a value
  12755. */
  12756. void write_bson_string(const string_t& name,
  12757. const string_t& value)
  12758. {
  12759. write_bson_entry_header(name, 0x02);
  12760. write_number<std::int32_t, true>(static_cast<std::int32_t>(value.size() + 1ul));
  12761. oa->write_characters(
  12762. reinterpret_cast<const CharType*>(value.c_str()),
  12763. value.size() + 1);
  12764. }
  12765. /*!
  12766. @brief Writes a BSON element with key @a name and null value
  12767. */
  12768. void write_bson_null(const string_t& name)
  12769. {
  12770. write_bson_entry_header(name, 0x0A);
  12771. }
  12772. /*!
  12773. @return The size of the BSON-encoded integer @a value
  12774. */
  12775. static std::size_t calc_bson_integer_size(const std::int64_t value)
  12776. {
  12777. return (std::numeric_limits<std::int32_t>::min)() <= value && value <= (std::numeric_limits<std::int32_t>::max)()
  12778. ? sizeof(std::int32_t)
  12779. : sizeof(std::int64_t);
  12780. }
  12781. /*!
  12782. @brief Writes a BSON element with key @a name and integer @a value
  12783. */
  12784. void write_bson_integer(const string_t& name,
  12785. const std::int64_t value)
  12786. {
  12787. if ((std::numeric_limits<std::int32_t>::min)() <= value && value <= (std::numeric_limits<std::int32_t>::max)())
  12788. {
  12789. write_bson_entry_header(name, 0x10); // int32
  12790. write_number<std::int32_t, true>(static_cast<std::int32_t>(value));
  12791. }
  12792. else
  12793. {
  12794. write_bson_entry_header(name, 0x12); // int64
  12795. write_number<std::int64_t, true>(static_cast<std::int64_t>(value));
  12796. }
  12797. }
  12798. /*!
  12799. @return The size of the BSON-encoded unsigned integer in @a j
  12800. */
  12801. static constexpr std::size_t calc_bson_unsigned_size(const std::uint64_t value) noexcept
  12802. {
  12803. return (value <= static_cast<std::uint64_t>((std::numeric_limits<std::int32_t>::max)()))
  12804. ? sizeof(std::int32_t)
  12805. : sizeof(std::int64_t);
  12806. }
  12807. /*!
  12808. @brief Writes a BSON element with key @a name and unsigned @a value
  12809. */
  12810. void write_bson_unsigned(const string_t& name,
  12811. const BasicJsonType& j)
  12812. {
  12813. if (j.m_value.number_unsigned <= static_cast<std::uint64_t>((std::numeric_limits<std::int32_t>::max)()))
  12814. {
  12815. write_bson_entry_header(name, 0x10 /* int32 */);
  12816. write_number<std::int32_t, true>(static_cast<std::int32_t>(j.m_value.number_unsigned));
  12817. }
  12818. else if (j.m_value.number_unsigned <= static_cast<std::uint64_t>((std::numeric_limits<std::int64_t>::max)()))
  12819. {
  12820. write_bson_entry_header(name, 0x12 /* int64 */);
  12821. write_number<std::int64_t, true>(static_cast<std::int64_t>(j.m_value.number_unsigned));
  12822. }
  12823. else
  12824. {
  12825. JSON_THROW(out_of_range::create(407, "integer number " + std::to_string(j.m_value.number_unsigned) + " cannot be represented by BSON as it does not fit int64", j));
  12826. }
  12827. }
  12828. /*!
  12829. @brief Writes a BSON element with key @a name and object @a value
  12830. */
  12831. void write_bson_object_entry(const string_t& name,
  12832. const typename BasicJsonType::object_t& value)
  12833. {
  12834. write_bson_entry_header(name, 0x03); // object
  12835. write_bson_object(value);
  12836. }
  12837. /*!
  12838. @return The size of the BSON-encoded array @a value
  12839. */
  12840. static std::size_t calc_bson_array_size(const typename BasicJsonType::array_t& value)
  12841. {
  12842. std::size_t array_index = 0ul;
  12843. const std::size_t embedded_document_size = std::accumulate(std::begin(value), std::end(value), std::size_t(0), [&array_index](std::size_t result, const typename BasicJsonType::array_t::value_type & el)
  12844. {
  12845. return result + calc_bson_element_size(std::to_string(array_index++), el);
  12846. });
  12847. return sizeof(std::int32_t) + embedded_document_size + 1ul;
  12848. }
  12849. /*!
  12850. @return The size of the BSON-encoded binary array @a value
  12851. */
  12852. static std::size_t calc_bson_binary_size(const typename BasicJsonType::binary_t& value)
  12853. {
  12854. return sizeof(std::int32_t) + value.size() + 1ul;
  12855. }
  12856. /*!
  12857. @brief Writes a BSON element with key @a name and array @a value
  12858. */
  12859. void write_bson_array(const string_t& name,
  12860. const typename BasicJsonType::array_t& value)
  12861. {
  12862. write_bson_entry_header(name, 0x04); // array
  12863. write_number<std::int32_t, true>(static_cast<std::int32_t>(calc_bson_array_size(value)));
  12864. std::size_t array_index = 0ul;
  12865. for (const auto& el : value)
  12866. {
  12867. write_bson_element(std::to_string(array_index++), el);
  12868. }
  12869. oa->write_character(to_char_type(0x00));
  12870. }
  12871. /*!
  12872. @brief Writes a BSON element with key @a name and binary value @a value
  12873. */
  12874. void write_bson_binary(const string_t& name,
  12875. const binary_t& value)
  12876. {
  12877. write_bson_entry_header(name, 0x05);
  12878. write_number<std::int32_t, true>(static_cast<std::int32_t>(value.size()));
  12879. write_number(value.has_subtype() ? static_cast<std::uint8_t>(value.subtype()) : std::uint8_t(0x00));
  12880. oa->write_characters(reinterpret_cast<const CharType*>(value.data()), value.size());
  12881. }
  12882. /*!
  12883. @brief Calculates the size necessary to serialize the JSON value @a j with its @a name
  12884. @return The calculated size for the BSON document entry for @a j with the given @a name.
  12885. */
  12886. static std::size_t calc_bson_element_size(const string_t& name,
  12887. const BasicJsonType& j)
  12888. {
  12889. const auto header_size = calc_bson_entry_header_size(name, j);
  12890. switch (j.type())
  12891. {
  12892. case value_t::object:
  12893. return header_size + calc_bson_object_size(*j.m_value.object);
  12894. case value_t::array:
  12895. return header_size + calc_bson_array_size(*j.m_value.array);
  12896. case value_t::binary:
  12897. return header_size + calc_bson_binary_size(*j.m_value.binary);
  12898. case value_t::boolean:
  12899. return header_size + 1ul;
  12900. case value_t::number_float:
  12901. return header_size + 8ul;
  12902. case value_t::number_integer:
  12903. return header_size + calc_bson_integer_size(j.m_value.number_integer);
  12904. case value_t::number_unsigned:
  12905. return header_size + calc_bson_unsigned_size(j.m_value.number_unsigned);
  12906. case value_t::string:
  12907. return header_size + calc_bson_string_size(*j.m_value.string);
  12908. case value_t::null:
  12909. return header_size + 0ul;
  12910. // LCOV_EXCL_START
  12911. case value_t::discarded:
  12912. default:
  12913. JSON_ASSERT(false); // NOLINT(cert-dcl03-c,hicpp-static-assert,misc-static-assert)
  12914. return 0ul;
  12915. // LCOV_EXCL_STOP
  12916. }
  12917. }
  12918. /*!
  12919. @brief Serializes the JSON value @a j to BSON and associates it with the
  12920. key @a name.
  12921. @param name The name to associate with the JSON entity @a j within the
  12922. current BSON document
  12923. */
  12924. void write_bson_element(const string_t& name,
  12925. const BasicJsonType& j)
  12926. {
  12927. switch (j.type())
  12928. {
  12929. case value_t::object:
  12930. return write_bson_object_entry(name, *j.m_value.object);
  12931. case value_t::array:
  12932. return write_bson_array(name, *j.m_value.array);
  12933. case value_t::binary:
  12934. return write_bson_binary(name, *j.m_value.binary);
  12935. case value_t::boolean:
  12936. return write_bson_boolean(name, j.m_value.boolean);
  12937. case value_t::number_float:
  12938. return write_bson_double(name, j.m_value.number_float);
  12939. case value_t::number_integer:
  12940. return write_bson_integer(name, j.m_value.number_integer);
  12941. case value_t::number_unsigned:
  12942. return write_bson_unsigned(name, j);
  12943. case value_t::string:
  12944. return write_bson_string(name, *j.m_value.string);
  12945. case value_t::null:
  12946. return write_bson_null(name);
  12947. // LCOV_EXCL_START
  12948. case value_t::discarded:
  12949. default:
  12950. JSON_ASSERT(false); // NOLINT(cert-dcl03-c,hicpp-static-assert,misc-static-assert)
  12951. return;
  12952. // LCOV_EXCL_STOP
  12953. }
  12954. }
  12955. /*!
  12956. @brief Calculates the size of the BSON serialization of the given
  12957. JSON-object @a j.
  12958. @param[in] value JSON value to serialize
  12959. @pre value.type() == value_t::object
  12960. */
  12961. static std::size_t calc_bson_object_size(const typename BasicJsonType::object_t& value)
  12962. {
  12963. std::size_t document_size = std::accumulate(value.begin(), value.end(), std::size_t(0),
  12964. [](size_t result, const typename BasicJsonType::object_t::value_type & el)
  12965. {
  12966. return result += calc_bson_element_size(el.first, el.second);
  12967. });
  12968. return sizeof(std::int32_t) + document_size + 1ul;
  12969. }
  12970. /*!
  12971. @param[in] value JSON value to serialize
  12972. @pre value.type() == value_t::object
  12973. */
  12974. void write_bson_object(const typename BasicJsonType::object_t& value)
  12975. {
  12976. write_number<std::int32_t, true>(static_cast<std::int32_t>(calc_bson_object_size(value)));
  12977. for (const auto& el : value)
  12978. {
  12979. write_bson_element(el.first, el.second);
  12980. }
  12981. oa->write_character(to_char_type(0x00));
  12982. }
  12983. //////////
  12984. // CBOR //
  12985. //////////
  12986. static constexpr CharType get_cbor_float_prefix(float /*unused*/)
  12987. {
  12988. return to_char_type(0xFA); // Single-Precision Float
  12989. }
  12990. static constexpr CharType get_cbor_float_prefix(double /*unused*/)
  12991. {
  12992. return to_char_type(0xFB); // Double-Precision Float
  12993. }
  12994. /////////////
  12995. // MsgPack //
  12996. /////////////
  12997. static constexpr CharType get_msgpack_float_prefix(float /*unused*/)
  12998. {
  12999. return to_char_type(0xCA); // float 32
  13000. }
  13001. static constexpr CharType get_msgpack_float_prefix(double /*unused*/)
  13002. {
  13003. return to_char_type(0xCB); // float 64
  13004. }
  13005. ////////////
  13006. // UBJSON //
  13007. ////////////
  13008. // UBJSON: write number (floating point)
  13009. template<typename NumberType, typename std::enable_if<
  13010. std::is_floating_point<NumberType>::value, int>::type = 0>
  13011. void write_number_with_ubjson_prefix(const NumberType n,
  13012. const bool add_prefix)
  13013. {
  13014. if (add_prefix)
  13015. {
  13016. oa->write_character(get_ubjson_float_prefix(n));
  13017. }
  13018. write_number(n);
  13019. }
  13020. // UBJSON: write number (unsigned integer)
  13021. template<typename NumberType, typename std::enable_if<
  13022. std::is_unsigned<NumberType>::value, int>::type = 0>
  13023. void write_number_with_ubjson_prefix(const NumberType n,
  13024. const bool add_prefix)
  13025. {
  13026. if (n <= static_cast<std::uint64_t>((std::numeric_limits<std::int8_t>::max)()))
  13027. {
  13028. if (add_prefix)
  13029. {
  13030. oa->write_character(to_char_type('i')); // int8
  13031. }
  13032. write_number(static_cast<std::uint8_t>(n));
  13033. }
  13034. else if (n <= (std::numeric_limits<std::uint8_t>::max)())
  13035. {
  13036. if (add_prefix)
  13037. {
  13038. oa->write_character(to_char_type('U')); // uint8
  13039. }
  13040. write_number(static_cast<std::uint8_t>(n));
  13041. }
  13042. else if (n <= static_cast<std::uint64_t>((std::numeric_limits<std::int16_t>::max)()))
  13043. {
  13044. if (add_prefix)
  13045. {
  13046. oa->write_character(to_char_type('I')); // int16
  13047. }
  13048. write_number(static_cast<std::int16_t>(n));
  13049. }
  13050. else if (n <= static_cast<std::uint64_t>((std::numeric_limits<std::int32_t>::max)()))
  13051. {
  13052. if (add_prefix)
  13053. {
  13054. oa->write_character(to_char_type('l')); // int32
  13055. }
  13056. write_number(static_cast<std::int32_t>(n));
  13057. }
  13058. else if (n <= static_cast<std::uint64_t>((std::numeric_limits<std::int64_t>::max)()))
  13059. {
  13060. if (add_prefix)
  13061. {
  13062. oa->write_character(to_char_type('L')); // int64
  13063. }
  13064. write_number(static_cast<std::int64_t>(n));
  13065. }
  13066. else
  13067. {
  13068. if (add_prefix)
  13069. {
  13070. oa->write_character(to_char_type('H')); // high-precision number
  13071. }
  13072. const auto number = BasicJsonType(n).dump();
  13073. write_number_with_ubjson_prefix(number.size(), true);
  13074. for (std::size_t i = 0; i < number.size(); ++i)
  13075. {
  13076. oa->write_character(to_char_type(static_cast<std::uint8_t>(number[i])));
  13077. }
  13078. }
  13079. }
  13080. // UBJSON: write number (signed integer)
  13081. template < typename NumberType, typename std::enable_if <
  13082. std::is_signed<NumberType>::value&&
  13083. !std::is_floating_point<NumberType>::value, int >::type = 0 >
  13084. void write_number_with_ubjson_prefix(const NumberType n,
  13085. const bool add_prefix)
  13086. {
  13087. if ((std::numeric_limits<std::int8_t>::min)() <= n && n <= (std::numeric_limits<std::int8_t>::max)())
  13088. {
  13089. if (add_prefix)
  13090. {
  13091. oa->write_character(to_char_type('i')); // int8
  13092. }
  13093. write_number(static_cast<std::int8_t>(n));
  13094. }
  13095. else if (static_cast<std::int64_t>((std::numeric_limits<std::uint8_t>::min)()) <= n && n <= static_cast<std::int64_t>((std::numeric_limits<std::uint8_t>::max)()))
  13096. {
  13097. if (add_prefix)
  13098. {
  13099. oa->write_character(to_char_type('U')); // uint8
  13100. }
  13101. write_number(static_cast<std::uint8_t>(n));
  13102. }
  13103. else if ((std::numeric_limits<std::int16_t>::min)() <= n && n <= (std::numeric_limits<std::int16_t>::max)())
  13104. {
  13105. if (add_prefix)
  13106. {
  13107. oa->write_character(to_char_type('I')); // int16
  13108. }
  13109. write_number(static_cast<std::int16_t>(n));
  13110. }
  13111. else if ((std::numeric_limits<std::int32_t>::min)() <= n && n <= (std::numeric_limits<std::int32_t>::max)())
  13112. {
  13113. if (add_prefix)
  13114. {
  13115. oa->write_character(to_char_type('l')); // int32
  13116. }
  13117. write_number(static_cast<std::int32_t>(n));
  13118. }
  13119. else if ((std::numeric_limits<std::int64_t>::min)() <= n && n <= (std::numeric_limits<std::int64_t>::max)())
  13120. {
  13121. if (add_prefix)
  13122. {
  13123. oa->write_character(to_char_type('L')); // int64
  13124. }
  13125. write_number(static_cast<std::int64_t>(n));
  13126. }
  13127. // LCOV_EXCL_START
  13128. else
  13129. {
  13130. if (add_prefix)
  13131. {
  13132. oa->write_character(to_char_type('H')); // high-precision number
  13133. }
  13134. const auto number = BasicJsonType(n).dump();
  13135. write_number_with_ubjson_prefix(number.size(), true);
  13136. for (std::size_t i = 0; i < number.size(); ++i)
  13137. {
  13138. oa->write_character(to_char_type(static_cast<std::uint8_t>(number[i])));
  13139. }
  13140. }
  13141. // LCOV_EXCL_STOP
  13142. }
  13143. /*!
  13144. @brief determine the type prefix of container values
  13145. */
  13146. CharType ubjson_prefix(const BasicJsonType& j) const noexcept
  13147. {
  13148. switch (j.type())
  13149. {
  13150. case value_t::null:
  13151. return 'Z';
  13152. case value_t::boolean:
  13153. return j.m_value.boolean ? 'T' : 'F';
  13154. case value_t::number_integer:
  13155. {
  13156. if ((std::numeric_limits<std::int8_t>::min)() <= j.m_value.number_integer && j.m_value.number_integer <= (std::numeric_limits<std::int8_t>::max)())
  13157. {
  13158. return 'i';
  13159. }
  13160. if ((std::numeric_limits<std::uint8_t>::min)() <= j.m_value.number_integer && j.m_value.number_integer <= (std::numeric_limits<std::uint8_t>::max)())
  13161. {
  13162. return 'U';
  13163. }
  13164. if ((std::numeric_limits<std::int16_t>::min)() <= j.m_value.number_integer && j.m_value.number_integer <= (std::numeric_limits<std::int16_t>::max)())
  13165. {
  13166. return 'I';
  13167. }
  13168. if ((std::numeric_limits<std::int32_t>::min)() <= j.m_value.number_integer && j.m_value.number_integer <= (std::numeric_limits<std::int32_t>::max)())
  13169. {
  13170. return 'l';
  13171. }
  13172. if ((std::numeric_limits<std::int64_t>::min)() <= j.m_value.number_integer && j.m_value.number_integer <= (std::numeric_limits<std::int64_t>::max)())
  13173. {
  13174. return 'L';
  13175. }
  13176. // anything else is treated as high-precision number
  13177. return 'H'; // LCOV_EXCL_LINE
  13178. }
  13179. case value_t::number_unsigned:
  13180. {
  13181. if (j.m_value.number_unsigned <= static_cast<std::uint64_t>((std::numeric_limits<std::int8_t>::max)()))
  13182. {
  13183. return 'i';
  13184. }
  13185. if (j.m_value.number_unsigned <= static_cast<std::uint64_t>((std::numeric_limits<std::uint8_t>::max)()))
  13186. {
  13187. return 'U';
  13188. }
  13189. if (j.m_value.number_unsigned <= static_cast<std::uint64_t>((std::numeric_limits<std::int16_t>::max)()))
  13190. {
  13191. return 'I';
  13192. }
  13193. if (j.m_value.number_unsigned <= static_cast<std::uint64_t>((std::numeric_limits<std::int32_t>::max)()))
  13194. {
  13195. return 'l';
  13196. }
  13197. if (j.m_value.number_unsigned <= static_cast<std::uint64_t>((std::numeric_limits<std::int64_t>::max)()))
  13198. {
  13199. return 'L';
  13200. }
  13201. // anything else is treated as high-precision number
  13202. return 'H'; // LCOV_EXCL_LINE
  13203. }
  13204. case value_t::number_float:
  13205. return get_ubjson_float_prefix(j.m_value.number_float);
  13206. case value_t::string:
  13207. return 'S';
  13208. case value_t::array: // fallthrough
  13209. case value_t::binary:
  13210. return '[';
  13211. case value_t::object:
  13212. return '{';
  13213. case value_t::discarded:
  13214. default: // discarded values
  13215. return 'N';
  13216. }
  13217. }
  13218. static constexpr CharType get_ubjson_float_prefix(float /*unused*/)
  13219. {
  13220. return 'd'; // float 32
  13221. }
  13222. static constexpr CharType get_ubjson_float_prefix(double /*unused*/)
  13223. {
  13224. return 'D'; // float 64
  13225. }
  13226. ///////////////////////
  13227. // Utility functions //
  13228. ///////////////////////
  13229. /*
  13230. @brief write a number to output input
  13231. @param[in] n number of type @a NumberType
  13232. @tparam NumberType the type of the number
  13233. @tparam OutputIsLittleEndian Set to true if output data is
  13234. required to be little endian
  13235. @note This function needs to respect the system's endianess, because bytes
  13236. in CBOR, MessagePack, and UBJSON are stored in network order (big
  13237. endian) and therefore need reordering on little endian systems.
  13238. */
  13239. template<typename NumberType, bool OutputIsLittleEndian = false>
  13240. void write_number(const NumberType n)
  13241. {
  13242. // step 1: write number to array of length NumberType
  13243. std::array<CharType, sizeof(NumberType)> vec{};
  13244. std::memcpy(vec.data(), &n, sizeof(NumberType));
  13245. // step 2: write array to output (with possible reordering)
  13246. if (is_little_endian != OutputIsLittleEndian)
  13247. {
  13248. // reverse byte order prior to conversion if necessary
  13249. std::reverse(vec.begin(), vec.end());
  13250. }
  13251. oa->write_characters(vec.data(), sizeof(NumberType));
  13252. }
  13253. void write_compact_float(const number_float_t n, detail::input_format_t format)
  13254. {
  13255. #ifdef __GNUC__
  13256. #pragma GCC diagnostic push
  13257. #pragma GCC diagnostic ignored "-Wfloat-equal"
  13258. #endif
  13259. if (static_cast<double>(n) >= static_cast<double>(std::numeric_limits<float>::lowest()) &&
  13260. static_cast<double>(n) <= static_cast<double>((std::numeric_limits<float>::max)()) &&
  13261. static_cast<double>(static_cast<float>(n)) == static_cast<double>(n))
  13262. {
  13263. oa->write_character(format == detail::input_format_t::cbor
  13264. ? get_cbor_float_prefix(static_cast<float>(n))
  13265. : get_msgpack_float_prefix(static_cast<float>(n)));
  13266. write_number(static_cast<float>(n));
  13267. }
  13268. else
  13269. {
  13270. oa->write_character(format == detail::input_format_t::cbor
  13271. ? get_cbor_float_prefix(n)
  13272. : get_msgpack_float_prefix(n));
  13273. write_number(n);
  13274. }
  13275. #ifdef __GNUC__
  13276. #pragma GCC diagnostic pop
  13277. #endif
  13278. }
  13279. public:
  13280. // The following to_char_type functions are implement the conversion
  13281. // between uint8_t and CharType. In case CharType is not unsigned,
  13282. // such a conversion is required to allow values greater than 128.
  13283. // See <https://github.com/nlohmann/json/issues/1286> for a discussion.
  13284. template < typename C = CharType,
  13285. enable_if_t < std::is_signed<C>::value && std::is_signed<char>::value > * = nullptr >
  13286. static constexpr CharType to_char_type(std::uint8_t x) noexcept
  13287. {
  13288. return *reinterpret_cast<char*>(&x);
  13289. }
  13290. template < typename C = CharType,
  13291. enable_if_t < std::is_signed<C>::value && std::is_unsigned<char>::value > * = nullptr >
  13292. static CharType to_char_type(std::uint8_t x) noexcept
  13293. {
  13294. static_assert(sizeof(std::uint8_t) == sizeof(CharType), "size of CharType must be equal to std::uint8_t");
  13295. static_assert(std::is_trivial<CharType>::value, "CharType must be trivial");
  13296. CharType result;
  13297. std::memcpy(&result, &x, sizeof(x));
  13298. return result;
  13299. }
  13300. template<typename C = CharType,
  13301. enable_if_t<std::is_unsigned<C>::value>* = nullptr>
  13302. static constexpr CharType to_char_type(std::uint8_t x) noexcept
  13303. {
  13304. return x;
  13305. }
  13306. template < typename InputCharType, typename C = CharType,
  13307. enable_if_t <
  13308. std::is_signed<C>::value &&
  13309. std::is_signed<char>::value &&
  13310. std::is_same<char, typename std::remove_cv<InputCharType>::type>::value
  13311. > * = nullptr >
  13312. static constexpr CharType to_char_type(InputCharType x) noexcept
  13313. {
  13314. return x;
  13315. }
  13316. private:
  13317. /// whether we can assume little endianess
  13318. const bool is_little_endian = little_endianess();
  13319. /// the output
  13320. output_adapter_t<CharType> oa = nullptr;
  13321. };
  13322. } // namespace detail
  13323. } // namespace nlohmann
  13324. // #include <nlohmann/detail/output/output_adapters.hpp>
  13325. // #include <nlohmann/detail/output/serializer.hpp>
  13326. #include <algorithm> // reverse, remove, fill, find, none_of
  13327. #include <array> // array
  13328. #include <clocale> // localeconv, lconv
  13329. #include <cmath> // labs, isfinite, isnan, signbit
  13330. #include <cstddef> // size_t, ptrdiff_t
  13331. #include <cstdint> // uint8_t
  13332. #include <cstdio> // snprintf
  13333. #include <limits> // numeric_limits
  13334. #include <string> // string, char_traits
  13335. #include <type_traits> // is_same
  13336. #include <utility> // move
  13337. // #include <nlohmann/detail/conversions/to_chars.hpp>
  13338. #include <array> // array
  13339. #include <cmath> // signbit, isfinite
  13340. #include <cstdint> // intN_t, uintN_t
  13341. #include <cstring> // memcpy, memmove
  13342. #include <limits> // numeric_limits
  13343. #include <type_traits> // conditional
  13344. // #include <nlohmann/detail/macro_scope.hpp>
  13345. namespace nlohmann
  13346. {
  13347. namespace detail
  13348. {
  13349. /*!
  13350. @brief implements the Grisu2 algorithm for binary to decimal floating-point
  13351. conversion.
  13352. This implementation is a slightly modified version of the reference
  13353. implementation which may be obtained from
  13354. http://florian.loitsch.com/publications (bench.tar.gz).
  13355. The code is distributed under the MIT license, Copyright (c) 2009 Florian Loitsch.
  13356. For a detailed description of the algorithm see:
  13357. [1] Loitsch, "Printing Floating-Point Numbers Quickly and Accurately with
  13358. Integers", Proceedings of the ACM SIGPLAN 2010 Conference on Programming
  13359. Language Design and Implementation, PLDI 2010
  13360. [2] Burger, Dybvig, "Printing Floating-Point Numbers Quickly and Accurately",
  13361. Proceedings of the ACM SIGPLAN 1996 Conference on Programming Language
  13362. Design and Implementation, PLDI 1996
  13363. */
  13364. namespace dtoa_impl
  13365. {
  13366. template<typename Target, typename Source>
  13367. Target reinterpret_bits(const Source source)
  13368. {
  13369. static_assert(sizeof(Target) == sizeof(Source), "size mismatch");
  13370. Target target;
  13371. std::memcpy(&target, &source, sizeof(Source));
  13372. return target;
  13373. }
  13374. struct diyfp // f * 2^e
  13375. {
  13376. static constexpr int kPrecision = 64; // = q
  13377. std::uint64_t f = 0;
  13378. int e = 0;
  13379. constexpr diyfp(std::uint64_t f_, int e_) noexcept : f(f_), e(e_) {}
  13380. /*!
  13381. @brief returns x - y
  13382. @pre x.e == y.e and x.f >= y.f
  13383. */
  13384. static diyfp sub(const diyfp& x, const diyfp& y) noexcept
  13385. {
  13386. JSON_ASSERT(x.e == y.e);
  13387. JSON_ASSERT(x.f >= y.f);
  13388. return {x.f - y.f, x.e};
  13389. }
  13390. /*!
  13391. @brief returns x * y
  13392. @note The result is rounded. (Only the upper q bits are returned.)
  13393. */
  13394. static diyfp mul(const diyfp& x, const diyfp& y) noexcept
  13395. {
  13396. static_assert(kPrecision == 64, "internal error");
  13397. // Computes:
  13398. // f = round((x.f * y.f) / 2^q)
  13399. // e = x.e + y.e + q
  13400. // Emulate the 64-bit * 64-bit multiplication:
  13401. //
  13402. // p = u * v
  13403. // = (u_lo + 2^32 u_hi) (v_lo + 2^32 v_hi)
  13404. // = (u_lo v_lo ) + 2^32 ((u_lo v_hi ) + (u_hi v_lo )) + 2^64 (u_hi v_hi )
  13405. // = (p0 ) + 2^32 ((p1 ) + (p2 )) + 2^64 (p3 )
  13406. // = (p0_lo + 2^32 p0_hi) + 2^32 ((p1_lo + 2^32 p1_hi) + (p2_lo + 2^32 p2_hi)) + 2^64 (p3 )
  13407. // = (p0_lo ) + 2^32 (p0_hi + p1_lo + p2_lo ) + 2^64 (p1_hi + p2_hi + p3)
  13408. // = (p0_lo ) + 2^32 (Q ) + 2^64 (H )
  13409. // = (p0_lo ) + 2^32 (Q_lo + 2^32 Q_hi ) + 2^64 (H )
  13410. //
  13411. // (Since Q might be larger than 2^32 - 1)
  13412. //
  13413. // = (p0_lo + 2^32 Q_lo) + 2^64 (Q_hi + H)
  13414. //
  13415. // (Q_hi + H does not overflow a 64-bit int)
  13416. //
  13417. // = p_lo + 2^64 p_hi
  13418. const std::uint64_t u_lo = x.f & 0xFFFFFFFFu;
  13419. const std::uint64_t u_hi = x.f >> 32u;
  13420. const std::uint64_t v_lo = y.f & 0xFFFFFFFFu;
  13421. const std::uint64_t v_hi = y.f >> 32u;
  13422. const std::uint64_t p0 = u_lo * v_lo;
  13423. const std::uint64_t p1 = u_lo * v_hi;
  13424. const std::uint64_t p2 = u_hi * v_lo;
  13425. const std::uint64_t p3 = u_hi * v_hi;
  13426. const std::uint64_t p0_hi = p0 >> 32u;
  13427. const std::uint64_t p1_lo = p1 & 0xFFFFFFFFu;
  13428. const std::uint64_t p1_hi = p1 >> 32u;
  13429. const std::uint64_t p2_lo = p2 & 0xFFFFFFFFu;
  13430. const std::uint64_t p2_hi = p2 >> 32u;
  13431. std::uint64_t Q = p0_hi + p1_lo + p2_lo;
  13432. // The full product might now be computed as
  13433. //
  13434. // p_hi = p3 + p2_hi + p1_hi + (Q >> 32)
  13435. // p_lo = p0_lo + (Q << 32)
  13436. //
  13437. // But in this particular case here, the full p_lo is not required.
  13438. // Effectively we only need to add the highest bit in p_lo to p_hi (and
  13439. // Q_hi + 1 does not overflow).
  13440. Q += std::uint64_t{1} << (64u - 32u - 1u); // round, ties up
  13441. const std::uint64_t h = p3 + p2_hi + p1_hi + (Q >> 32u);
  13442. return {h, x.e + y.e + 64};
  13443. }
  13444. /*!
  13445. @brief normalize x such that the significand is >= 2^(q-1)
  13446. @pre x.f != 0
  13447. */
  13448. static diyfp normalize(diyfp x) noexcept
  13449. {
  13450. JSON_ASSERT(x.f != 0);
  13451. while ((x.f >> 63u) == 0)
  13452. {
  13453. x.f <<= 1u;
  13454. x.e--;
  13455. }
  13456. return x;
  13457. }
  13458. /*!
  13459. @brief normalize x such that the result has the exponent E
  13460. @pre e >= x.e and the upper e - x.e bits of x.f must be zero.
  13461. */
  13462. static diyfp normalize_to(const diyfp& x, const int target_exponent) noexcept
  13463. {
  13464. const int delta = x.e - target_exponent;
  13465. JSON_ASSERT(delta >= 0);
  13466. JSON_ASSERT(((x.f << delta) >> delta) == x.f);
  13467. return {x.f << delta, target_exponent};
  13468. }
  13469. };
  13470. struct boundaries
  13471. {
  13472. diyfp w;
  13473. diyfp minus;
  13474. diyfp plus;
  13475. };
  13476. /*!
  13477. Compute the (normalized) diyfp representing the input number 'value' and its
  13478. boundaries.
  13479. @pre value must be finite and positive
  13480. */
  13481. template<typename FloatType>
  13482. boundaries compute_boundaries(FloatType value)
  13483. {
  13484. JSON_ASSERT(std::isfinite(value));
  13485. JSON_ASSERT(value > 0);
  13486. // Convert the IEEE representation into a diyfp.
  13487. //
  13488. // If v is denormal:
  13489. // value = 0.F * 2^(1 - bias) = ( F) * 2^(1 - bias - (p-1))
  13490. // If v is normalized:
  13491. // value = 1.F * 2^(E - bias) = (2^(p-1) + F) * 2^(E - bias - (p-1))
  13492. static_assert(std::numeric_limits<FloatType>::is_iec559,
  13493. "internal error: dtoa_short requires an IEEE-754 floating-point implementation");
  13494. constexpr int kPrecision = std::numeric_limits<FloatType>::digits; // = p (includes the hidden bit)
  13495. constexpr int kBias = std::numeric_limits<FloatType>::max_exponent - 1 + (kPrecision - 1);
  13496. constexpr int kMinExp = 1 - kBias;
  13497. constexpr std::uint64_t kHiddenBit = std::uint64_t{1} << (kPrecision - 1); // = 2^(p-1)
  13498. using bits_type = typename std::conditional<kPrecision == 24, std::uint32_t, std::uint64_t >::type;
  13499. const auto bits = static_cast<std::uint64_t>(reinterpret_bits<bits_type>(value));
  13500. const std::uint64_t E = bits >> (kPrecision - 1);
  13501. const std::uint64_t F = bits & (kHiddenBit - 1);
  13502. const bool is_denormal = E == 0;
  13503. const diyfp v = is_denormal
  13504. ? diyfp(F, kMinExp)
  13505. : diyfp(F + kHiddenBit, static_cast<int>(E) - kBias);
  13506. // Compute the boundaries m- and m+ of the floating-point value
  13507. // v = f * 2^e.
  13508. //
  13509. // Determine v- and v+, the floating-point predecessor and successor if v,
  13510. // respectively.
  13511. //
  13512. // v- = v - 2^e if f != 2^(p-1) or e == e_min (A)
  13513. // = v - 2^(e-1) if f == 2^(p-1) and e > e_min (B)
  13514. //
  13515. // v+ = v + 2^e
  13516. //
  13517. // Let m- = (v- + v) / 2 and m+ = (v + v+) / 2. All real numbers _strictly_
  13518. // between m- and m+ round to v, regardless of how the input rounding
  13519. // algorithm breaks ties.
  13520. //
  13521. // ---+-------------+-------------+-------------+-------------+--- (A)
  13522. // v- m- v m+ v+
  13523. //
  13524. // -----------------+------+------+-------------+-------------+--- (B)
  13525. // v- m- v m+ v+
  13526. const bool lower_boundary_is_closer = F == 0 && E > 1;
  13527. const diyfp m_plus = diyfp(2 * v.f + 1, v.e - 1);
  13528. const diyfp m_minus = lower_boundary_is_closer
  13529. ? diyfp(4 * v.f - 1, v.e - 2) // (B)
  13530. : diyfp(2 * v.f - 1, v.e - 1); // (A)
  13531. // Determine the normalized w+ = m+.
  13532. const diyfp w_plus = diyfp::normalize(m_plus);
  13533. // Determine w- = m- such that e_(w-) = e_(w+).
  13534. const diyfp w_minus = diyfp::normalize_to(m_minus, w_plus.e);
  13535. return {diyfp::normalize(v), w_minus, w_plus};
  13536. }
  13537. // Given normalized diyfp w, Grisu needs to find a (normalized) cached
  13538. // power-of-ten c, such that the exponent of the product c * w = f * 2^e lies
  13539. // within a certain range [alpha, gamma] (Definition 3.2 from [1])
  13540. //
  13541. // alpha <= e = e_c + e_w + q <= gamma
  13542. //
  13543. // or
  13544. //
  13545. // f_c * f_w * 2^alpha <= f_c 2^(e_c) * f_w 2^(e_w) * 2^q
  13546. // <= f_c * f_w * 2^gamma
  13547. //
  13548. // Since c and w are normalized, i.e. 2^(q-1) <= f < 2^q, this implies
  13549. //
  13550. // 2^(q-1) * 2^(q-1) * 2^alpha <= c * w * 2^q < 2^q * 2^q * 2^gamma
  13551. //
  13552. // or
  13553. //
  13554. // 2^(q - 2 + alpha) <= c * w < 2^(q + gamma)
  13555. //
  13556. // The choice of (alpha,gamma) determines the size of the table and the form of
  13557. // the digit generation procedure. Using (alpha,gamma)=(-60,-32) works out well
  13558. // in practice:
  13559. //
  13560. // The idea is to cut the number c * w = f * 2^e into two parts, which can be
  13561. // processed independently: An integral part p1, and a fractional part p2:
  13562. //
  13563. // f * 2^e = ( (f div 2^-e) * 2^-e + (f mod 2^-e) ) * 2^e
  13564. // = (f div 2^-e) + (f mod 2^-e) * 2^e
  13565. // = p1 + p2 * 2^e
  13566. //
  13567. // The conversion of p1 into decimal form requires a series of divisions and
  13568. // modulos by (a power of) 10. These operations are faster for 32-bit than for
  13569. // 64-bit integers, so p1 should ideally fit into a 32-bit integer. This can be
  13570. // achieved by choosing
  13571. //
  13572. // -e >= 32 or e <= -32 := gamma
  13573. //
  13574. // In order to convert the fractional part
  13575. //
  13576. // p2 * 2^e = p2 / 2^-e = d[-1] / 10^1 + d[-2] / 10^2 + ...
  13577. //
  13578. // into decimal form, the fraction is repeatedly multiplied by 10 and the digits
  13579. // d[-i] are extracted in order:
  13580. //
  13581. // (10 * p2) div 2^-e = d[-1]
  13582. // (10 * p2) mod 2^-e = d[-2] / 10^1 + ...
  13583. //
  13584. // The multiplication by 10 must not overflow. It is sufficient to choose
  13585. //
  13586. // 10 * p2 < 16 * p2 = 2^4 * p2 <= 2^64.
  13587. //
  13588. // Since p2 = f mod 2^-e < 2^-e,
  13589. //
  13590. // -e <= 60 or e >= -60 := alpha
  13591. constexpr int kAlpha = -60;
  13592. constexpr int kGamma = -32;
  13593. struct cached_power // c = f * 2^e ~= 10^k
  13594. {
  13595. std::uint64_t f;
  13596. int e;
  13597. int k;
  13598. };
  13599. /*!
  13600. For a normalized diyfp w = f * 2^e, this function returns a (normalized) cached
  13601. power-of-ten c = f_c * 2^e_c, such that the exponent of the product w * c
  13602. satisfies (Definition 3.2 from [1])
  13603. alpha <= e_c + e + q <= gamma.
  13604. */
  13605. inline cached_power get_cached_power_for_binary_exponent(int e)
  13606. {
  13607. // Now
  13608. //
  13609. // alpha <= e_c + e + q <= gamma (1)
  13610. // ==> f_c * 2^alpha <= c * 2^e * 2^q
  13611. //
  13612. // and since the c's are normalized, 2^(q-1) <= f_c,
  13613. //
  13614. // ==> 2^(q - 1 + alpha) <= c * 2^(e + q)
  13615. // ==> 2^(alpha - e - 1) <= c
  13616. //
  13617. // If c were an exact power of ten, i.e. c = 10^k, one may determine k as
  13618. //
  13619. // k = ceil( log_10( 2^(alpha - e - 1) ) )
  13620. // = ceil( (alpha - e - 1) * log_10(2) )
  13621. //
  13622. // From the paper:
  13623. // "In theory the result of the procedure could be wrong since c is rounded,
  13624. // and the computation itself is approximated [...]. In practice, however,
  13625. // this simple function is sufficient."
  13626. //
  13627. // For IEEE double precision floating-point numbers converted into
  13628. // normalized diyfp's w = f * 2^e, with q = 64,
  13629. //
  13630. // e >= -1022 (min IEEE exponent)
  13631. // -52 (p - 1)
  13632. // -52 (p - 1, possibly normalize denormal IEEE numbers)
  13633. // -11 (normalize the diyfp)
  13634. // = -1137
  13635. //
  13636. // and
  13637. //
  13638. // e <= +1023 (max IEEE exponent)
  13639. // -52 (p - 1)
  13640. // -11 (normalize the diyfp)
  13641. // = 960
  13642. //
  13643. // This binary exponent range [-1137,960] results in a decimal exponent
  13644. // range [-307,324]. One does not need to store a cached power for each
  13645. // k in this range. For each such k it suffices to find a cached power
  13646. // such that the exponent of the product lies in [alpha,gamma].
  13647. // This implies that the difference of the decimal exponents of adjacent
  13648. // table entries must be less than or equal to
  13649. //
  13650. // floor( (gamma - alpha) * log_10(2) ) = 8.
  13651. //
  13652. // (A smaller distance gamma-alpha would require a larger table.)
  13653. // NB:
  13654. // Actually this function returns c, such that -60 <= e_c + e + 64 <= -34.
  13655. constexpr int kCachedPowersMinDecExp = -300;
  13656. constexpr int kCachedPowersDecStep = 8;
  13657. static constexpr std::array<cached_power, 79> kCachedPowers =
  13658. {
  13659. {
  13660. { 0xAB70FE17C79AC6CA, -1060, -300 },
  13661. { 0xFF77B1FCBEBCDC4F, -1034, -292 },
  13662. { 0xBE5691EF416BD60C, -1007, -284 },
  13663. { 0x8DD01FAD907FFC3C, -980, -276 },
  13664. { 0xD3515C2831559A83, -954, -268 },
  13665. { 0x9D71AC8FADA6C9B5, -927, -260 },
  13666. { 0xEA9C227723EE8BCB, -901, -252 },
  13667. { 0xAECC49914078536D, -874, -244 },
  13668. { 0x823C12795DB6CE57, -847, -236 },
  13669. { 0xC21094364DFB5637, -821, -228 },
  13670. { 0x9096EA6F3848984F, -794, -220 },
  13671. { 0xD77485CB25823AC7, -768, -212 },
  13672. { 0xA086CFCD97BF97F4, -741, -204 },
  13673. { 0xEF340A98172AACE5, -715, -196 },
  13674. { 0xB23867FB2A35B28E, -688, -188 },
  13675. { 0x84C8D4DFD2C63F3B, -661, -180 },
  13676. { 0xC5DD44271AD3CDBA, -635, -172 },
  13677. { 0x936B9FCEBB25C996, -608, -164 },
  13678. { 0xDBAC6C247D62A584, -582, -156 },
  13679. { 0xA3AB66580D5FDAF6, -555, -148 },
  13680. { 0xF3E2F893DEC3F126, -529, -140 },
  13681. { 0xB5B5ADA8AAFF80B8, -502, -132 },
  13682. { 0x87625F056C7C4A8B, -475, -124 },
  13683. { 0xC9BCFF6034C13053, -449, -116 },
  13684. { 0x964E858C91BA2655, -422, -108 },
  13685. { 0xDFF9772470297EBD, -396, -100 },
  13686. { 0xA6DFBD9FB8E5B88F, -369, -92 },
  13687. { 0xF8A95FCF88747D94, -343, -84 },
  13688. { 0xB94470938FA89BCF, -316, -76 },
  13689. { 0x8A08F0F8BF0F156B, -289, -68 },
  13690. { 0xCDB02555653131B6, -263, -60 },
  13691. { 0x993FE2C6D07B7FAC, -236, -52 },
  13692. { 0xE45C10C42A2B3B06, -210, -44 },
  13693. { 0xAA242499697392D3, -183, -36 },
  13694. { 0xFD87B5F28300CA0E, -157, -28 },
  13695. { 0xBCE5086492111AEB, -130, -20 },
  13696. { 0x8CBCCC096F5088CC, -103, -12 },
  13697. { 0xD1B71758E219652C, -77, -4 },
  13698. { 0x9C40000000000000, -50, 4 },
  13699. { 0xE8D4A51000000000, -24, 12 },
  13700. { 0xAD78EBC5AC620000, 3, 20 },
  13701. { 0x813F3978F8940984, 30, 28 },
  13702. { 0xC097CE7BC90715B3, 56, 36 },
  13703. { 0x8F7E32CE7BEA5C70, 83, 44 },
  13704. { 0xD5D238A4ABE98068, 109, 52 },
  13705. { 0x9F4F2726179A2245, 136, 60 },
  13706. { 0xED63A231D4C4FB27, 162, 68 },
  13707. { 0xB0DE65388CC8ADA8, 189, 76 },
  13708. { 0x83C7088E1AAB65DB, 216, 84 },
  13709. { 0xC45D1DF942711D9A, 242, 92 },
  13710. { 0x924D692CA61BE758, 269, 100 },
  13711. { 0xDA01EE641A708DEA, 295, 108 },
  13712. { 0xA26DA3999AEF774A, 322, 116 },
  13713. { 0xF209787BB47D6B85, 348, 124 },
  13714. { 0xB454E4A179DD1877, 375, 132 },
  13715. { 0x865B86925B9BC5C2, 402, 140 },
  13716. { 0xC83553C5C8965D3D, 428, 148 },
  13717. { 0x952AB45CFA97A0B3, 455, 156 },
  13718. { 0xDE469FBD99A05FE3, 481, 164 },
  13719. { 0xA59BC234DB398C25, 508, 172 },
  13720. { 0xF6C69A72A3989F5C, 534, 180 },
  13721. { 0xB7DCBF5354E9BECE, 561, 188 },
  13722. { 0x88FCF317F22241E2, 588, 196 },
  13723. { 0xCC20CE9BD35C78A5, 614, 204 },
  13724. { 0x98165AF37B2153DF, 641, 212 },
  13725. { 0xE2A0B5DC971F303A, 667, 220 },
  13726. { 0xA8D9D1535CE3B396, 694, 228 },
  13727. { 0xFB9B7CD9A4A7443C, 720, 236 },
  13728. { 0xBB764C4CA7A44410, 747, 244 },
  13729. { 0x8BAB8EEFB6409C1A, 774, 252 },
  13730. { 0xD01FEF10A657842C, 800, 260 },
  13731. { 0x9B10A4E5E9913129, 827, 268 },
  13732. { 0xE7109BFBA19C0C9D, 853, 276 },
  13733. { 0xAC2820D9623BF429, 880, 284 },
  13734. { 0x80444B5E7AA7CF85, 907, 292 },
  13735. { 0xBF21E44003ACDD2D, 933, 300 },
  13736. { 0x8E679C2F5E44FF8F, 960, 308 },
  13737. { 0xD433179D9C8CB841, 986, 316 },
  13738. { 0x9E19DB92B4E31BA9, 1013, 324 },
  13739. }
  13740. };
  13741. // This computation gives exactly the same results for k as
  13742. // k = ceil((kAlpha - e - 1) * 0.30102999566398114)
  13743. // for |e| <= 1500, but doesn't require floating-point operations.
  13744. // NB: log_10(2) ~= 78913 / 2^18
  13745. JSON_ASSERT(e >= -1500);
  13746. JSON_ASSERT(e <= 1500);
  13747. const int f = kAlpha - e - 1;
  13748. const int k = (f * 78913) / (1 << 18) + static_cast<int>(f > 0);
  13749. const int index = (-kCachedPowersMinDecExp + k + (kCachedPowersDecStep - 1)) / kCachedPowersDecStep;
  13750. JSON_ASSERT(index >= 0);
  13751. JSON_ASSERT(static_cast<std::size_t>(index) < kCachedPowers.size());
  13752. const cached_power cached = kCachedPowers[static_cast<std::size_t>(index)];
  13753. JSON_ASSERT(kAlpha <= cached.e + e + 64);
  13754. JSON_ASSERT(kGamma >= cached.e + e + 64);
  13755. return cached;
  13756. }
  13757. /*!
  13758. For n != 0, returns k, such that pow10 := 10^(k-1) <= n < 10^k.
  13759. For n == 0, returns 1 and sets pow10 := 1.
  13760. */
  13761. inline int find_largest_pow10(const std::uint32_t n, std::uint32_t& pow10)
  13762. {
  13763. // LCOV_EXCL_START
  13764. if (n >= 1000000000)
  13765. {
  13766. pow10 = 1000000000;
  13767. return 10;
  13768. }
  13769. // LCOV_EXCL_STOP
  13770. if (n >= 100000000)
  13771. {
  13772. pow10 = 100000000;
  13773. return 9;
  13774. }
  13775. if (n >= 10000000)
  13776. {
  13777. pow10 = 10000000;
  13778. return 8;
  13779. }
  13780. if (n >= 1000000)
  13781. {
  13782. pow10 = 1000000;
  13783. return 7;
  13784. }
  13785. if (n >= 100000)
  13786. {
  13787. pow10 = 100000;
  13788. return 6;
  13789. }
  13790. if (n >= 10000)
  13791. {
  13792. pow10 = 10000;
  13793. return 5;
  13794. }
  13795. if (n >= 1000)
  13796. {
  13797. pow10 = 1000;
  13798. return 4;
  13799. }
  13800. if (n >= 100)
  13801. {
  13802. pow10 = 100;
  13803. return 3;
  13804. }
  13805. if (n >= 10)
  13806. {
  13807. pow10 = 10;
  13808. return 2;
  13809. }
  13810. pow10 = 1;
  13811. return 1;
  13812. }
  13813. inline void grisu2_round(char* buf, int len, std::uint64_t dist, std::uint64_t delta,
  13814. std::uint64_t rest, std::uint64_t ten_k)
  13815. {
  13816. JSON_ASSERT(len >= 1);
  13817. JSON_ASSERT(dist <= delta);
  13818. JSON_ASSERT(rest <= delta);
  13819. JSON_ASSERT(ten_k > 0);
  13820. // <--------------------------- delta ---->
  13821. // <---- dist --------->
  13822. // --------------[------------------+-------------------]--------------
  13823. // M- w M+
  13824. //
  13825. // ten_k
  13826. // <------>
  13827. // <---- rest ---->
  13828. // --------------[------------------+----+--------------]--------------
  13829. // w V
  13830. // = buf * 10^k
  13831. //
  13832. // ten_k represents a unit-in-the-last-place in the decimal representation
  13833. // stored in buf.
  13834. // Decrement buf by ten_k while this takes buf closer to w.
  13835. // The tests are written in this order to avoid overflow in unsigned
  13836. // integer arithmetic.
  13837. while (rest < dist
  13838. && delta - rest >= ten_k
  13839. && (rest + ten_k < dist || dist - rest > rest + ten_k - dist))
  13840. {
  13841. JSON_ASSERT(buf[len - 1] != '0');
  13842. buf[len - 1]--;
  13843. rest += ten_k;
  13844. }
  13845. }
  13846. /*!
  13847. Generates V = buffer * 10^decimal_exponent, such that M- <= V <= M+.
  13848. M- and M+ must be normalized and share the same exponent -60 <= e <= -32.
  13849. */
  13850. inline void grisu2_digit_gen(char* buffer, int& length, int& decimal_exponent,
  13851. diyfp M_minus, diyfp w, diyfp M_plus)
  13852. {
  13853. static_assert(kAlpha >= -60, "internal error");
  13854. static_assert(kGamma <= -32, "internal error");
  13855. // Generates the digits (and the exponent) of a decimal floating-point
  13856. // number V = buffer * 10^decimal_exponent in the range [M-, M+]. The diyfp's
  13857. // w, M- and M+ share the same exponent e, which satisfies alpha <= e <= gamma.
  13858. //
  13859. // <--------------------------- delta ---->
  13860. // <---- dist --------->
  13861. // --------------[------------------+-------------------]--------------
  13862. // M- w M+
  13863. //
  13864. // Grisu2 generates the digits of M+ from left to right and stops as soon as
  13865. // V is in [M-,M+].
  13866. JSON_ASSERT(M_plus.e >= kAlpha);
  13867. JSON_ASSERT(M_plus.e <= kGamma);
  13868. std::uint64_t delta = diyfp::sub(M_plus, M_minus).f; // (significand of (M+ - M-), implicit exponent is e)
  13869. std::uint64_t dist = diyfp::sub(M_plus, w ).f; // (significand of (M+ - w ), implicit exponent is e)
  13870. // Split M+ = f * 2^e into two parts p1 and p2 (note: e < 0):
  13871. //
  13872. // M+ = f * 2^e
  13873. // = ((f div 2^-e) * 2^-e + (f mod 2^-e)) * 2^e
  13874. // = ((p1 ) * 2^-e + (p2 )) * 2^e
  13875. // = p1 + p2 * 2^e
  13876. const diyfp one(std::uint64_t{1} << -M_plus.e, M_plus.e);
  13877. auto p1 = static_cast<std::uint32_t>(M_plus.f >> -one.e); // p1 = f div 2^-e (Since -e >= 32, p1 fits into a 32-bit int.)
  13878. std::uint64_t p2 = M_plus.f & (one.f - 1); // p2 = f mod 2^-e
  13879. // 1)
  13880. //
  13881. // Generate the digits of the integral part p1 = d[n-1]...d[1]d[0]
  13882. JSON_ASSERT(p1 > 0);
  13883. std::uint32_t pow10{};
  13884. const int k = find_largest_pow10(p1, pow10);
  13885. // 10^(k-1) <= p1 < 10^k, pow10 = 10^(k-1)
  13886. //
  13887. // p1 = (p1 div 10^(k-1)) * 10^(k-1) + (p1 mod 10^(k-1))
  13888. // = (d[k-1] ) * 10^(k-1) + (p1 mod 10^(k-1))
  13889. //
  13890. // M+ = p1 + p2 * 2^e
  13891. // = d[k-1] * 10^(k-1) + (p1 mod 10^(k-1)) + p2 * 2^e
  13892. // = d[k-1] * 10^(k-1) + ((p1 mod 10^(k-1)) * 2^-e + p2) * 2^e
  13893. // = d[k-1] * 10^(k-1) + ( rest) * 2^e
  13894. //
  13895. // Now generate the digits d[n] of p1 from left to right (n = k-1,...,0)
  13896. //
  13897. // p1 = d[k-1]...d[n] * 10^n + d[n-1]...d[0]
  13898. //
  13899. // but stop as soon as
  13900. //
  13901. // rest * 2^e = (d[n-1]...d[0] * 2^-e + p2) * 2^e <= delta * 2^e
  13902. int n = k;
  13903. while (n > 0)
  13904. {
  13905. // Invariants:
  13906. // M+ = buffer * 10^n + (p1 + p2 * 2^e) (buffer = 0 for n = k)
  13907. // pow10 = 10^(n-1) <= p1 < 10^n
  13908. //
  13909. const std::uint32_t d = p1 / pow10; // d = p1 div 10^(n-1)
  13910. const std::uint32_t r = p1 % pow10; // r = p1 mod 10^(n-1)
  13911. //
  13912. // M+ = buffer * 10^n + (d * 10^(n-1) + r) + p2 * 2^e
  13913. // = (buffer * 10 + d) * 10^(n-1) + (r + p2 * 2^e)
  13914. //
  13915. JSON_ASSERT(d <= 9);
  13916. buffer[length++] = static_cast<char>('0' + d); // buffer := buffer * 10 + d
  13917. //
  13918. // M+ = buffer * 10^(n-1) + (r + p2 * 2^e)
  13919. //
  13920. p1 = r;
  13921. n--;
  13922. //
  13923. // M+ = buffer * 10^n + (p1 + p2 * 2^e)
  13924. // pow10 = 10^n
  13925. //
  13926. // Now check if enough digits have been generated.
  13927. // Compute
  13928. //
  13929. // p1 + p2 * 2^e = (p1 * 2^-e + p2) * 2^e = rest * 2^e
  13930. //
  13931. // Note:
  13932. // Since rest and delta share the same exponent e, it suffices to
  13933. // compare the significands.
  13934. const std::uint64_t rest = (std::uint64_t{p1} << -one.e) + p2;
  13935. if (rest <= delta)
  13936. {
  13937. // V = buffer * 10^n, with M- <= V <= M+.
  13938. decimal_exponent += n;
  13939. // We may now just stop. But instead look if the buffer could be
  13940. // decremented to bring V closer to w.
  13941. //
  13942. // pow10 = 10^n is now 1 ulp in the decimal representation V.
  13943. // The rounding procedure works with diyfp's with an implicit
  13944. // exponent of e.
  13945. //
  13946. // 10^n = (10^n * 2^-e) * 2^e = ulp * 2^e
  13947. //
  13948. const std::uint64_t ten_n = std::uint64_t{pow10} << -one.e;
  13949. grisu2_round(buffer, length, dist, delta, rest, ten_n);
  13950. return;
  13951. }
  13952. pow10 /= 10;
  13953. //
  13954. // pow10 = 10^(n-1) <= p1 < 10^n
  13955. // Invariants restored.
  13956. }
  13957. // 2)
  13958. //
  13959. // The digits of the integral part have been generated:
  13960. //
  13961. // M+ = d[k-1]...d[1]d[0] + p2 * 2^e
  13962. // = buffer + p2 * 2^e
  13963. //
  13964. // Now generate the digits of the fractional part p2 * 2^e.
  13965. //
  13966. // Note:
  13967. // No decimal point is generated: the exponent is adjusted instead.
  13968. //
  13969. // p2 actually represents the fraction
  13970. //
  13971. // p2 * 2^e
  13972. // = p2 / 2^-e
  13973. // = d[-1] / 10^1 + d[-2] / 10^2 + ...
  13974. //
  13975. // Now generate the digits d[-m] of p1 from left to right (m = 1,2,...)
  13976. //
  13977. // p2 * 2^e = d[-1]d[-2]...d[-m] * 10^-m
  13978. // + 10^-m * (d[-m-1] / 10^1 + d[-m-2] / 10^2 + ...)
  13979. //
  13980. // using
  13981. //
  13982. // 10^m * p2 = ((10^m * p2) div 2^-e) * 2^-e + ((10^m * p2) mod 2^-e)
  13983. // = ( d) * 2^-e + ( r)
  13984. //
  13985. // or
  13986. // 10^m * p2 * 2^e = d + r * 2^e
  13987. //
  13988. // i.e.
  13989. //
  13990. // M+ = buffer + p2 * 2^e
  13991. // = buffer + 10^-m * (d + r * 2^e)
  13992. // = (buffer * 10^m + d) * 10^-m + 10^-m * r * 2^e
  13993. //
  13994. // and stop as soon as 10^-m * r * 2^e <= delta * 2^e
  13995. JSON_ASSERT(p2 > delta);
  13996. int m = 0;
  13997. for (;;)
  13998. {
  13999. // Invariant:
  14000. // M+ = buffer * 10^-m + 10^-m * (d[-m-1] / 10 + d[-m-2] / 10^2 + ...) * 2^e
  14001. // = buffer * 10^-m + 10^-m * (p2 ) * 2^e
  14002. // = buffer * 10^-m + 10^-m * (1/10 * (10 * p2) ) * 2^e
  14003. // = buffer * 10^-m + 10^-m * (1/10 * ((10*p2 div 2^-e) * 2^-e + (10*p2 mod 2^-e)) * 2^e
  14004. //
  14005. JSON_ASSERT(p2 <= (std::numeric_limits<std::uint64_t>::max)() / 10);
  14006. p2 *= 10;
  14007. const std::uint64_t d = p2 >> -one.e; // d = (10 * p2) div 2^-e
  14008. const std::uint64_t r = p2 & (one.f - 1); // r = (10 * p2) mod 2^-e
  14009. //
  14010. // M+ = buffer * 10^-m + 10^-m * (1/10 * (d * 2^-e + r) * 2^e
  14011. // = buffer * 10^-m + 10^-m * (1/10 * (d + r * 2^e))
  14012. // = (buffer * 10 + d) * 10^(-m-1) + 10^(-m-1) * r * 2^e
  14013. //
  14014. JSON_ASSERT(d <= 9);
  14015. buffer[length++] = static_cast<char>('0' + d); // buffer := buffer * 10 + d
  14016. //
  14017. // M+ = buffer * 10^(-m-1) + 10^(-m-1) * r * 2^e
  14018. //
  14019. p2 = r;
  14020. m++;
  14021. //
  14022. // M+ = buffer * 10^-m + 10^-m * p2 * 2^e
  14023. // Invariant restored.
  14024. // Check if enough digits have been generated.
  14025. //
  14026. // 10^-m * p2 * 2^e <= delta * 2^e
  14027. // p2 * 2^e <= 10^m * delta * 2^e
  14028. // p2 <= 10^m * delta
  14029. delta *= 10;
  14030. dist *= 10;
  14031. if (p2 <= delta)
  14032. {
  14033. break;
  14034. }
  14035. }
  14036. // V = buffer * 10^-m, with M- <= V <= M+.
  14037. decimal_exponent -= m;
  14038. // 1 ulp in the decimal representation is now 10^-m.
  14039. // Since delta and dist are now scaled by 10^m, we need to do the
  14040. // same with ulp in order to keep the units in sync.
  14041. //
  14042. // 10^m * 10^-m = 1 = 2^-e * 2^e = ten_m * 2^e
  14043. //
  14044. const std::uint64_t ten_m = one.f;
  14045. grisu2_round(buffer, length, dist, delta, p2, ten_m);
  14046. // By construction this algorithm generates the shortest possible decimal
  14047. // number (Loitsch, Theorem 6.2) which rounds back to w.
  14048. // For an input number of precision p, at least
  14049. //
  14050. // N = 1 + ceil(p * log_10(2))
  14051. //
  14052. // decimal digits are sufficient to identify all binary floating-point
  14053. // numbers (Matula, "In-and-Out conversions").
  14054. // This implies that the algorithm does not produce more than N decimal
  14055. // digits.
  14056. //
  14057. // N = 17 for p = 53 (IEEE double precision)
  14058. // N = 9 for p = 24 (IEEE single precision)
  14059. }
  14060. /*!
  14061. v = buf * 10^decimal_exponent
  14062. len is the length of the buffer (number of decimal digits)
  14063. The buffer must be large enough, i.e. >= max_digits10.
  14064. */
  14065. JSON_HEDLEY_NON_NULL(1)
  14066. inline void grisu2(char* buf, int& len, int& decimal_exponent,
  14067. diyfp m_minus, diyfp v, diyfp m_plus)
  14068. {
  14069. JSON_ASSERT(m_plus.e == m_minus.e);
  14070. JSON_ASSERT(m_plus.e == v.e);
  14071. // --------(-----------------------+-----------------------)-------- (A)
  14072. // m- v m+
  14073. //
  14074. // --------------------(-----------+-----------------------)-------- (B)
  14075. // m- v m+
  14076. //
  14077. // First scale v (and m- and m+) such that the exponent is in the range
  14078. // [alpha, gamma].
  14079. const cached_power cached = get_cached_power_for_binary_exponent(m_plus.e);
  14080. const diyfp c_minus_k(cached.f, cached.e); // = c ~= 10^-k
  14081. // The exponent of the products is = v.e + c_minus_k.e + q and is in the range [alpha,gamma]
  14082. const diyfp w = diyfp::mul(v, c_minus_k);
  14083. const diyfp w_minus = diyfp::mul(m_minus, c_minus_k);
  14084. const diyfp w_plus = diyfp::mul(m_plus, c_minus_k);
  14085. // ----(---+---)---------------(---+---)---------------(---+---)----
  14086. // w- w w+
  14087. // = c*m- = c*v = c*m+
  14088. //
  14089. // diyfp::mul rounds its result and c_minus_k is approximated too. w, w- and
  14090. // w+ are now off by a small amount.
  14091. // In fact:
  14092. //
  14093. // w - v * 10^k < 1 ulp
  14094. //
  14095. // To account for this inaccuracy, add resp. subtract 1 ulp.
  14096. //
  14097. // --------+---[---------------(---+---)---------------]---+--------
  14098. // w- M- w M+ w+
  14099. //
  14100. // Now any number in [M-, M+] (bounds included) will round to w when input,
  14101. // regardless of how the input rounding algorithm breaks ties.
  14102. //
  14103. // And digit_gen generates the shortest possible such number in [M-, M+].
  14104. // Note that this does not mean that Grisu2 always generates the shortest
  14105. // possible number in the interval (m-, m+).
  14106. const diyfp M_minus(w_minus.f + 1, w_minus.e);
  14107. const diyfp M_plus (w_plus.f - 1, w_plus.e );
  14108. decimal_exponent = -cached.k; // = -(-k) = k
  14109. grisu2_digit_gen(buf, len, decimal_exponent, M_minus, w, M_plus);
  14110. }
  14111. /*!
  14112. v = buf * 10^decimal_exponent
  14113. len is the length of the buffer (number of decimal digits)
  14114. The buffer must be large enough, i.e. >= max_digits10.
  14115. */
  14116. template<typename FloatType>
  14117. JSON_HEDLEY_NON_NULL(1)
  14118. void grisu2(char* buf, int& len, int& decimal_exponent, FloatType value)
  14119. {
  14120. static_assert(diyfp::kPrecision >= std::numeric_limits<FloatType>::digits + 3,
  14121. "internal error: not enough precision");
  14122. JSON_ASSERT(std::isfinite(value));
  14123. JSON_ASSERT(value > 0);
  14124. // If the neighbors (and boundaries) of 'value' are always computed for double-precision
  14125. // numbers, all float's can be recovered using strtod (and strtof). However, the resulting
  14126. // decimal representations are not exactly "short".
  14127. //
  14128. // The documentation for 'std::to_chars' (https://en.cppreference.com/w/cpp/utility/to_chars)
  14129. // says "value is converted to a string as if by std::sprintf in the default ("C") locale"
  14130. // and since sprintf promotes float's to double's, I think this is exactly what 'std::to_chars'
  14131. // does.
  14132. // On the other hand, the documentation for 'std::to_chars' requires that "parsing the
  14133. // representation using the corresponding std::from_chars function recovers value exactly". That
  14134. // indicates that single precision floating-point numbers should be recovered using
  14135. // 'std::strtof'.
  14136. //
  14137. // NB: If the neighbors are computed for single-precision numbers, there is a single float
  14138. // (7.0385307e-26f) which can't be recovered using strtod. The resulting double precision
  14139. // value is off by 1 ulp.
  14140. #if 0
  14141. const boundaries w = compute_boundaries(static_cast<double>(value));
  14142. #else
  14143. const boundaries w = compute_boundaries(value);
  14144. #endif
  14145. grisu2(buf, len, decimal_exponent, w.minus, w.w, w.plus);
  14146. }
  14147. /*!
  14148. @brief appends a decimal representation of e to buf
  14149. @return a pointer to the element following the exponent.
  14150. @pre -1000 < e < 1000
  14151. */
  14152. JSON_HEDLEY_NON_NULL(1)
  14153. JSON_HEDLEY_RETURNS_NON_NULL
  14154. inline char* append_exponent(char* buf, int e)
  14155. {
  14156. JSON_ASSERT(e > -1000);
  14157. JSON_ASSERT(e < 1000);
  14158. if (e < 0)
  14159. {
  14160. e = -e;
  14161. *buf++ = '-';
  14162. }
  14163. else
  14164. {
  14165. *buf++ = '+';
  14166. }
  14167. auto k = static_cast<std::uint32_t>(e);
  14168. if (k < 10)
  14169. {
  14170. // Always print at least two digits in the exponent.
  14171. // This is for compatibility with printf("%g").
  14172. *buf++ = '0';
  14173. *buf++ = static_cast<char>('0' + k);
  14174. }
  14175. else if (k < 100)
  14176. {
  14177. *buf++ = static_cast<char>('0' + k / 10);
  14178. k %= 10;
  14179. *buf++ = static_cast<char>('0' + k);
  14180. }
  14181. else
  14182. {
  14183. *buf++ = static_cast<char>('0' + k / 100);
  14184. k %= 100;
  14185. *buf++ = static_cast<char>('0' + k / 10);
  14186. k %= 10;
  14187. *buf++ = static_cast<char>('0' + k);
  14188. }
  14189. return buf;
  14190. }
  14191. /*!
  14192. @brief prettify v = buf * 10^decimal_exponent
  14193. If v is in the range [10^min_exp, 10^max_exp) it will be printed in fixed-point
  14194. notation. Otherwise it will be printed in exponential notation.
  14195. @pre min_exp < 0
  14196. @pre max_exp > 0
  14197. */
  14198. JSON_HEDLEY_NON_NULL(1)
  14199. JSON_HEDLEY_RETURNS_NON_NULL
  14200. inline char* format_buffer(char* buf, int len, int decimal_exponent,
  14201. int min_exp, int max_exp)
  14202. {
  14203. JSON_ASSERT(min_exp < 0);
  14204. JSON_ASSERT(max_exp > 0);
  14205. const int k = len;
  14206. const int n = len + decimal_exponent;
  14207. // v = buf * 10^(n-k)
  14208. // k is the length of the buffer (number of decimal digits)
  14209. // n is the position of the decimal point relative to the start of the buffer.
  14210. if (k <= n && n <= max_exp)
  14211. {
  14212. // digits[000]
  14213. // len <= max_exp + 2
  14214. std::memset(buf + k, '0', static_cast<size_t>(n) - static_cast<size_t>(k));
  14215. // Make it look like a floating-point number (#362, #378)
  14216. buf[n + 0] = '.';
  14217. buf[n + 1] = '0';
  14218. return buf + (static_cast<size_t>(n) + 2);
  14219. }
  14220. if (0 < n && n <= max_exp)
  14221. {
  14222. // dig.its
  14223. // len <= max_digits10 + 1
  14224. JSON_ASSERT(k > n);
  14225. std::memmove(buf + (static_cast<size_t>(n) + 1), buf + n, static_cast<size_t>(k) - static_cast<size_t>(n));
  14226. buf[n] = '.';
  14227. return buf + (static_cast<size_t>(k) + 1U);
  14228. }
  14229. if (min_exp < n && n <= 0)
  14230. {
  14231. // 0.[000]digits
  14232. // len <= 2 + (-min_exp - 1) + max_digits10
  14233. std::memmove(buf + (2 + static_cast<size_t>(-n)), buf, static_cast<size_t>(k));
  14234. buf[0] = '0';
  14235. buf[1] = '.';
  14236. std::memset(buf + 2, '0', static_cast<size_t>(-n));
  14237. return buf + (2U + static_cast<size_t>(-n) + static_cast<size_t>(k));
  14238. }
  14239. if (k == 1)
  14240. {
  14241. // dE+123
  14242. // len <= 1 + 5
  14243. buf += 1;
  14244. }
  14245. else
  14246. {
  14247. // d.igitsE+123
  14248. // len <= max_digits10 + 1 + 5
  14249. std::memmove(buf + 2, buf + 1, static_cast<size_t>(k) - 1);
  14250. buf[1] = '.';
  14251. buf += 1 + static_cast<size_t>(k);
  14252. }
  14253. *buf++ = 'e';
  14254. return append_exponent(buf, n - 1);
  14255. }
  14256. } // namespace dtoa_impl
  14257. /*!
  14258. @brief generates a decimal representation of the floating-point number value in [first, last).
  14259. The format of the resulting decimal representation is similar to printf's %g
  14260. format. Returns an iterator pointing past-the-end of the decimal representation.
  14261. @note The input number must be finite, i.e. NaN's and Inf's are not supported.
  14262. @note The buffer must be large enough.
  14263. @note The result is NOT null-terminated.
  14264. */
  14265. template<typename FloatType>
  14266. JSON_HEDLEY_NON_NULL(1, 2)
  14267. JSON_HEDLEY_RETURNS_NON_NULL
  14268. char* to_chars(char* first, const char* last, FloatType value)
  14269. {
  14270. static_cast<void>(last); // maybe unused - fix warning
  14271. JSON_ASSERT(std::isfinite(value));
  14272. // Use signbit(value) instead of (value < 0) since signbit works for -0.
  14273. if (std::signbit(value))
  14274. {
  14275. value = -value;
  14276. *first++ = '-';
  14277. }
  14278. #ifdef __GNUC__
  14279. #pragma GCC diagnostic push
  14280. #pragma GCC diagnostic ignored "-Wfloat-equal"
  14281. #endif
  14282. if (value == 0) // +-0
  14283. {
  14284. *first++ = '0';
  14285. // Make it look like a floating-point number (#362, #378)
  14286. *first++ = '.';
  14287. *first++ = '0';
  14288. return first;
  14289. }
  14290. #ifdef __GNUC__
  14291. #pragma GCC diagnostic pop
  14292. #endif
  14293. JSON_ASSERT(last - first >= std::numeric_limits<FloatType>::max_digits10);
  14294. // Compute v = buffer * 10^decimal_exponent.
  14295. // The decimal digits are stored in the buffer, which needs to be interpreted
  14296. // as an unsigned decimal integer.
  14297. // len is the length of the buffer, i.e. the number of decimal digits.
  14298. int len = 0;
  14299. int decimal_exponent = 0;
  14300. dtoa_impl::grisu2(first, len, decimal_exponent, value);
  14301. JSON_ASSERT(len <= std::numeric_limits<FloatType>::max_digits10);
  14302. // Format the buffer like printf("%.*g", prec, value)
  14303. constexpr int kMinExp = -4;
  14304. // Use digits10 here to increase compatibility with version 2.
  14305. constexpr int kMaxExp = std::numeric_limits<FloatType>::digits10;
  14306. JSON_ASSERT(last - first >= kMaxExp + 2);
  14307. JSON_ASSERT(last - first >= 2 + (-kMinExp - 1) + std::numeric_limits<FloatType>::max_digits10);
  14308. JSON_ASSERT(last - first >= std::numeric_limits<FloatType>::max_digits10 + 6);
  14309. return dtoa_impl::format_buffer(first, len, decimal_exponent, kMinExp, kMaxExp);
  14310. }
  14311. } // namespace detail
  14312. } // namespace nlohmann
  14313. // #include <nlohmann/detail/exceptions.hpp>
  14314. // #include <nlohmann/detail/macro_scope.hpp>
  14315. // #include <nlohmann/detail/meta/cpp_future.hpp>
  14316. // #include <nlohmann/detail/output/binary_writer.hpp>
  14317. // #include <nlohmann/detail/output/output_adapters.hpp>
  14318. // #include <nlohmann/detail/value_t.hpp>
  14319. namespace nlohmann
  14320. {
  14321. namespace detail
  14322. {
  14323. ///////////////////
  14324. // serialization //
  14325. ///////////////////
  14326. /// how to treat decoding errors
  14327. enum class error_handler_t
  14328. {
  14329. strict, ///< throw a type_error exception in case of invalid UTF-8
  14330. replace, ///< replace invalid UTF-8 sequences with U+FFFD
  14331. ignore ///< ignore invalid UTF-8 sequences
  14332. };
  14333. template<typename BasicJsonType>
  14334. class serializer
  14335. {
  14336. using string_t = typename BasicJsonType::string_t;
  14337. using number_float_t = typename BasicJsonType::number_float_t;
  14338. using number_integer_t = typename BasicJsonType::number_integer_t;
  14339. using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
  14340. using binary_char_t = typename BasicJsonType::binary_t::value_type;
  14341. static constexpr std::uint8_t UTF8_ACCEPT = 0;
  14342. static constexpr std::uint8_t UTF8_REJECT = 1;
  14343. public:
  14344. /*!
  14345. @param[in] s output stream to serialize to
  14346. @param[in] ichar indentation character to use
  14347. @param[in] error_handler_ how to react on decoding errors
  14348. */
  14349. serializer(output_adapter_t<char> s, const char ichar,
  14350. error_handler_t error_handler_ = error_handler_t::strict)
  14351. : o(std::move(s))
  14352. , loc(std::localeconv())
  14353. , thousands_sep(loc->thousands_sep == nullptr ? '\0' : std::char_traits<char>::to_char_type(* (loc->thousands_sep)))
  14354. , decimal_point(loc->decimal_point == nullptr ? '\0' : std::char_traits<char>::to_char_type(* (loc->decimal_point)))
  14355. , indent_char(ichar)
  14356. , indent_string(512, indent_char)
  14357. , error_handler(error_handler_)
  14358. {}
  14359. // delete because of pointer members
  14360. serializer(const serializer&) = delete;
  14361. serializer& operator=(const serializer&) = delete;
  14362. serializer(serializer&&) = delete;
  14363. serializer& operator=(serializer&&) = delete;
  14364. ~serializer() = default;
  14365. /*!
  14366. @brief internal implementation of the serialization function
  14367. This function is called by the public member function dump and organizes
  14368. the serialization internally. The indentation level is propagated as
  14369. additional parameter. In case of arrays and objects, the function is
  14370. called recursively.
  14371. - strings and object keys are escaped using `escape_string()`
  14372. - integer numbers are converted implicitly via `operator<<`
  14373. - floating-point numbers are converted to a string using `"%g"` format
  14374. - binary values are serialized as objects containing the subtype and the
  14375. byte array
  14376. @param[in] val value to serialize
  14377. @param[in] pretty_print whether the output shall be pretty-printed
  14378. @param[in] ensure_ascii If @a ensure_ascii is true, all non-ASCII characters
  14379. in the output are escaped with `\uXXXX` sequences, and the result consists
  14380. of ASCII characters only.
  14381. @param[in] indent_step the indent level
  14382. @param[in] current_indent the current indent level (only used internally)
  14383. */
  14384. void dump(const BasicJsonType& val,
  14385. const bool pretty_print,
  14386. const bool ensure_ascii,
  14387. const unsigned int indent_step,
  14388. const unsigned int current_indent = 0)
  14389. {
  14390. switch (val.m_type)
  14391. {
  14392. case value_t::object:
  14393. {
  14394. if (val.m_value.object->empty())
  14395. {
  14396. o->write_characters("{}", 2);
  14397. return;
  14398. }
  14399. if (pretty_print)
  14400. {
  14401. o->write_characters("{\n", 2);
  14402. // variable to hold indentation for recursive calls
  14403. const auto new_indent = current_indent + indent_step;
  14404. if (JSON_HEDLEY_UNLIKELY(indent_string.size() < new_indent))
  14405. {
  14406. indent_string.resize(indent_string.size() * 2, ' ');
  14407. }
  14408. // first n-1 elements
  14409. auto i = val.m_value.object->cbegin();
  14410. for (std::size_t cnt = 0; cnt < val.m_value.object->size() - 1; ++cnt, ++i)
  14411. {
  14412. o->write_characters(indent_string.c_str(), new_indent);
  14413. o->write_character('\"');
  14414. dump_escaped(i->first, ensure_ascii);
  14415. o->write_characters("\": ", 3);
  14416. dump(i->second, true, ensure_ascii, indent_step, new_indent);
  14417. o->write_characters(",\n", 2);
  14418. }
  14419. // last element
  14420. JSON_ASSERT(i != val.m_value.object->cend());
  14421. JSON_ASSERT(std::next(i) == val.m_value.object->cend());
  14422. o->write_characters(indent_string.c_str(), new_indent);
  14423. o->write_character('\"');
  14424. dump_escaped(i->first, ensure_ascii);
  14425. o->write_characters("\": ", 3);
  14426. dump(i->second, true, ensure_ascii, indent_step, new_indent);
  14427. o->write_character('\n');
  14428. o->write_characters(indent_string.c_str(), current_indent);
  14429. o->write_character('}');
  14430. }
  14431. else
  14432. {
  14433. o->write_character('{');
  14434. // first n-1 elements
  14435. auto i = val.m_value.object->cbegin();
  14436. for (std::size_t cnt = 0; cnt < val.m_value.object->size() - 1; ++cnt, ++i)
  14437. {
  14438. o->write_character('\"');
  14439. dump_escaped(i->first, ensure_ascii);
  14440. o->write_characters("\":", 2);
  14441. dump(i->second, false, ensure_ascii, indent_step, current_indent);
  14442. o->write_character(',');
  14443. }
  14444. // last element
  14445. JSON_ASSERT(i != val.m_value.object->cend());
  14446. JSON_ASSERT(std::next(i) == val.m_value.object->cend());
  14447. o->write_character('\"');
  14448. dump_escaped(i->first, ensure_ascii);
  14449. o->write_characters("\":", 2);
  14450. dump(i->second, false, ensure_ascii, indent_step, current_indent);
  14451. o->write_character('}');
  14452. }
  14453. return;
  14454. }
  14455. case value_t::array:
  14456. {
  14457. if (val.m_value.array->empty())
  14458. {
  14459. o->write_characters("[]", 2);
  14460. return;
  14461. }
  14462. if (pretty_print)
  14463. {
  14464. o->write_characters("[\n", 2);
  14465. // variable to hold indentation for recursive calls
  14466. const auto new_indent = current_indent + indent_step;
  14467. if (JSON_HEDLEY_UNLIKELY(indent_string.size() < new_indent))
  14468. {
  14469. indent_string.resize(indent_string.size() * 2, ' ');
  14470. }
  14471. // first n-1 elements
  14472. for (auto i = val.m_value.array->cbegin();
  14473. i != val.m_value.array->cend() - 1; ++i)
  14474. {
  14475. o->write_characters(indent_string.c_str(), new_indent);
  14476. dump(*i, true, ensure_ascii, indent_step, new_indent);
  14477. o->write_characters(",\n", 2);
  14478. }
  14479. // last element
  14480. JSON_ASSERT(!val.m_value.array->empty());
  14481. o->write_characters(indent_string.c_str(), new_indent);
  14482. dump(val.m_value.array->back(), true, ensure_ascii, indent_step, new_indent);
  14483. o->write_character('\n');
  14484. o->write_characters(indent_string.c_str(), current_indent);
  14485. o->write_character(']');
  14486. }
  14487. else
  14488. {
  14489. o->write_character('[');
  14490. // first n-1 elements
  14491. for (auto i = val.m_value.array->cbegin();
  14492. i != val.m_value.array->cend() - 1; ++i)
  14493. {
  14494. dump(*i, false, ensure_ascii, indent_step, current_indent);
  14495. o->write_character(',');
  14496. }
  14497. // last element
  14498. JSON_ASSERT(!val.m_value.array->empty());
  14499. dump(val.m_value.array->back(), false, ensure_ascii, indent_step, current_indent);
  14500. o->write_character(']');
  14501. }
  14502. return;
  14503. }
  14504. case value_t::string:
  14505. {
  14506. o->write_character('\"');
  14507. dump_escaped(*val.m_value.string, ensure_ascii);
  14508. o->write_character('\"');
  14509. return;
  14510. }
  14511. case value_t::binary:
  14512. {
  14513. if (pretty_print)
  14514. {
  14515. o->write_characters("{\n", 2);
  14516. // variable to hold indentation for recursive calls
  14517. const auto new_indent = current_indent + indent_step;
  14518. if (JSON_HEDLEY_UNLIKELY(indent_string.size() < new_indent))
  14519. {
  14520. indent_string.resize(indent_string.size() * 2, ' ');
  14521. }
  14522. o->write_characters(indent_string.c_str(), new_indent);
  14523. o->write_characters("\"bytes\": [", 10);
  14524. if (!val.m_value.binary->empty())
  14525. {
  14526. for (auto i = val.m_value.binary->cbegin();
  14527. i != val.m_value.binary->cend() - 1; ++i)
  14528. {
  14529. dump_integer(*i);
  14530. o->write_characters(", ", 2);
  14531. }
  14532. dump_integer(val.m_value.binary->back());
  14533. }
  14534. o->write_characters("],\n", 3);
  14535. o->write_characters(indent_string.c_str(), new_indent);
  14536. o->write_characters("\"subtype\": ", 11);
  14537. if (val.m_value.binary->has_subtype())
  14538. {
  14539. dump_integer(val.m_value.binary->subtype());
  14540. }
  14541. else
  14542. {
  14543. o->write_characters("null", 4);
  14544. }
  14545. o->write_character('\n');
  14546. o->write_characters(indent_string.c_str(), current_indent);
  14547. o->write_character('}');
  14548. }
  14549. else
  14550. {
  14551. o->write_characters("{\"bytes\":[", 10);
  14552. if (!val.m_value.binary->empty())
  14553. {
  14554. for (auto i = val.m_value.binary->cbegin();
  14555. i != val.m_value.binary->cend() - 1; ++i)
  14556. {
  14557. dump_integer(*i);
  14558. o->write_character(',');
  14559. }
  14560. dump_integer(val.m_value.binary->back());
  14561. }
  14562. o->write_characters("],\"subtype\":", 12);
  14563. if (val.m_value.binary->has_subtype())
  14564. {
  14565. dump_integer(val.m_value.binary->subtype());
  14566. o->write_character('}');
  14567. }
  14568. else
  14569. {
  14570. o->write_characters("null}", 5);
  14571. }
  14572. }
  14573. return;
  14574. }
  14575. case value_t::boolean:
  14576. {
  14577. if (val.m_value.boolean)
  14578. {
  14579. o->write_characters("true", 4);
  14580. }
  14581. else
  14582. {
  14583. o->write_characters("false", 5);
  14584. }
  14585. return;
  14586. }
  14587. case value_t::number_integer:
  14588. {
  14589. dump_integer(val.m_value.number_integer);
  14590. return;
  14591. }
  14592. case value_t::number_unsigned:
  14593. {
  14594. dump_integer(val.m_value.number_unsigned);
  14595. return;
  14596. }
  14597. case value_t::number_float:
  14598. {
  14599. dump_float(val.m_value.number_float);
  14600. return;
  14601. }
  14602. case value_t::discarded:
  14603. {
  14604. o->write_characters("<discarded>", 11);
  14605. return;
  14606. }
  14607. case value_t::null:
  14608. {
  14609. o->write_characters("null", 4);
  14610. return;
  14611. }
  14612. default: // LCOV_EXCL_LINE
  14613. JSON_ASSERT(false); // NOLINT(cert-dcl03-c,hicpp-static-assert,misc-static-assert) LCOV_EXCL_LINE
  14614. }
  14615. }
  14616. JSON_PRIVATE_UNLESS_TESTED:
  14617. /*!
  14618. @brief dump escaped string
  14619. Escape a string by replacing certain special characters by a sequence of an
  14620. escape character (backslash) and another character and other control
  14621. characters by a sequence of "\u" followed by a four-digit hex
  14622. representation. The escaped string is written to output stream @a o.
  14623. @param[in] s the string to escape
  14624. @param[in] ensure_ascii whether to escape non-ASCII characters with
  14625. \uXXXX sequences
  14626. @complexity Linear in the length of string @a s.
  14627. */
  14628. void dump_escaped(const string_t& s, const bool ensure_ascii)
  14629. {
  14630. std::uint32_t codepoint{};
  14631. std::uint8_t state = UTF8_ACCEPT;
  14632. std::size_t bytes = 0; // number of bytes written to string_buffer
  14633. // number of bytes written at the point of the last valid byte
  14634. std::size_t bytes_after_last_accept = 0;
  14635. std::size_t undumped_chars = 0;
  14636. for (std::size_t i = 0; i < s.size(); ++i)
  14637. {
  14638. const auto byte = static_cast<std::uint8_t>(s[i]);
  14639. switch (decode(state, codepoint, byte))
  14640. {
  14641. case UTF8_ACCEPT: // decode found a new code point
  14642. {
  14643. switch (codepoint)
  14644. {
  14645. case 0x08: // backspace
  14646. {
  14647. string_buffer[bytes++] = '\\';
  14648. string_buffer[bytes++] = 'b';
  14649. break;
  14650. }
  14651. case 0x09: // horizontal tab
  14652. {
  14653. string_buffer[bytes++] = '\\';
  14654. string_buffer[bytes++] = 't';
  14655. break;
  14656. }
  14657. case 0x0A: // newline
  14658. {
  14659. string_buffer[bytes++] = '\\';
  14660. string_buffer[bytes++] = 'n';
  14661. break;
  14662. }
  14663. case 0x0C: // formfeed
  14664. {
  14665. string_buffer[bytes++] = '\\';
  14666. string_buffer[bytes++] = 'f';
  14667. break;
  14668. }
  14669. case 0x0D: // carriage return
  14670. {
  14671. string_buffer[bytes++] = '\\';
  14672. string_buffer[bytes++] = 'r';
  14673. break;
  14674. }
  14675. case 0x22: // quotation mark
  14676. {
  14677. string_buffer[bytes++] = '\\';
  14678. string_buffer[bytes++] = '\"';
  14679. break;
  14680. }
  14681. case 0x5C: // reverse solidus
  14682. {
  14683. string_buffer[bytes++] = '\\';
  14684. string_buffer[bytes++] = '\\';
  14685. break;
  14686. }
  14687. default:
  14688. {
  14689. // escape control characters (0x00..0x1F) or, if
  14690. // ensure_ascii parameter is used, non-ASCII characters
  14691. if ((codepoint <= 0x1F) || (ensure_ascii && (codepoint >= 0x7F)))
  14692. {
  14693. if (codepoint <= 0xFFFF)
  14694. {
  14695. // NOLINTNEXTLINE(cppcoreguidelines-pro-type-vararg,hicpp-vararg)
  14696. (std::snprintf)(string_buffer.data() + bytes, 7, "\\u%04x",
  14697. static_cast<std::uint16_t>(codepoint));
  14698. bytes += 6;
  14699. }
  14700. else
  14701. {
  14702. // NOLINTNEXTLINE(cppcoreguidelines-pro-type-vararg,hicpp-vararg)
  14703. (std::snprintf)(string_buffer.data() + bytes, 13, "\\u%04x\\u%04x",
  14704. static_cast<std::uint16_t>(0xD7C0u + (codepoint >> 10u)),
  14705. static_cast<std::uint16_t>(0xDC00u + (codepoint & 0x3FFu)));
  14706. bytes += 12;
  14707. }
  14708. }
  14709. else
  14710. {
  14711. // copy byte to buffer (all previous bytes
  14712. // been copied have in default case above)
  14713. string_buffer[bytes++] = s[i];
  14714. }
  14715. break;
  14716. }
  14717. }
  14718. // write buffer and reset index; there must be 13 bytes
  14719. // left, as this is the maximal number of bytes to be
  14720. // written ("\uxxxx\uxxxx\0") for one code point
  14721. if (string_buffer.size() - bytes < 13)
  14722. {
  14723. o->write_characters(string_buffer.data(), bytes);
  14724. bytes = 0;
  14725. }
  14726. // remember the byte position of this accept
  14727. bytes_after_last_accept = bytes;
  14728. undumped_chars = 0;
  14729. break;
  14730. }
  14731. case UTF8_REJECT: // decode found invalid UTF-8 byte
  14732. {
  14733. switch (error_handler)
  14734. {
  14735. case error_handler_t::strict:
  14736. {
  14737. std::string sn(9, '\0');
  14738. // NOLINTNEXTLINE(cppcoreguidelines-pro-type-vararg,hicpp-vararg)
  14739. (std::snprintf)(&sn[0], sn.size(), "%.2X", byte);
  14740. JSON_THROW(type_error::create(316, "invalid UTF-8 byte at index " + std::to_string(i) + ": 0x" + sn, BasicJsonType()));
  14741. }
  14742. case error_handler_t::ignore:
  14743. case error_handler_t::replace:
  14744. {
  14745. // in case we saw this character the first time, we
  14746. // would like to read it again, because the byte
  14747. // may be OK for itself, but just not OK for the
  14748. // previous sequence
  14749. if (undumped_chars > 0)
  14750. {
  14751. --i;
  14752. }
  14753. // reset length buffer to the last accepted index;
  14754. // thus removing/ignoring the invalid characters
  14755. bytes = bytes_after_last_accept;
  14756. if (error_handler == error_handler_t::replace)
  14757. {
  14758. // add a replacement character
  14759. if (ensure_ascii)
  14760. {
  14761. string_buffer[bytes++] = '\\';
  14762. string_buffer[bytes++] = 'u';
  14763. string_buffer[bytes++] = 'f';
  14764. string_buffer[bytes++] = 'f';
  14765. string_buffer[bytes++] = 'f';
  14766. string_buffer[bytes++] = 'd';
  14767. }
  14768. else
  14769. {
  14770. string_buffer[bytes++] = detail::binary_writer<BasicJsonType, char>::to_char_type('\xEF');
  14771. string_buffer[bytes++] = detail::binary_writer<BasicJsonType, char>::to_char_type('\xBF');
  14772. string_buffer[bytes++] = detail::binary_writer<BasicJsonType, char>::to_char_type('\xBD');
  14773. }
  14774. // write buffer and reset index; there must be 13 bytes
  14775. // left, as this is the maximal number of bytes to be
  14776. // written ("\uxxxx\uxxxx\0") for one code point
  14777. if (string_buffer.size() - bytes < 13)
  14778. {
  14779. o->write_characters(string_buffer.data(), bytes);
  14780. bytes = 0;
  14781. }
  14782. bytes_after_last_accept = bytes;
  14783. }
  14784. undumped_chars = 0;
  14785. // continue processing the string
  14786. state = UTF8_ACCEPT;
  14787. break;
  14788. }
  14789. default: // LCOV_EXCL_LINE
  14790. JSON_ASSERT(false); // NOLINT(cert-dcl03-c,hicpp-static-assert,misc-static-assert) LCOV_EXCL_LINE
  14791. }
  14792. break;
  14793. }
  14794. default: // decode found yet incomplete multi-byte code point
  14795. {
  14796. if (!ensure_ascii)
  14797. {
  14798. // code point will not be escaped - copy byte to buffer
  14799. string_buffer[bytes++] = s[i];
  14800. }
  14801. ++undumped_chars;
  14802. break;
  14803. }
  14804. }
  14805. }
  14806. // we finished processing the string
  14807. if (JSON_HEDLEY_LIKELY(state == UTF8_ACCEPT))
  14808. {
  14809. // write buffer
  14810. if (bytes > 0)
  14811. {
  14812. o->write_characters(string_buffer.data(), bytes);
  14813. }
  14814. }
  14815. else
  14816. {
  14817. // we finish reading, but do not accept: string was incomplete
  14818. switch (error_handler)
  14819. {
  14820. case error_handler_t::strict:
  14821. {
  14822. std::string sn(9, '\0');
  14823. // NOLINTNEXTLINE(cppcoreguidelines-pro-type-vararg,hicpp-vararg)
  14824. (std::snprintf)(&sn[0], sn.size(), "%.2X", static_cast<std::uint8_t>(s.back()));
  14825. JSON_THROW(type_error::create(316, "incomplete UTF-8 string; last byte: 0x" + sn, BasicJsonType()));
  14826. }
  14827. case error_handler_t::ignore:
  14828. {
  14829. // write all accepted bytes
  14830. o->write_characters(string_buffer.data(), bytes_after_last_accept);
  14831. break;
  14832. }
  14833. case error_handler_t::replace:
  14834. {
  14835. // write all accepted bytes
  14836. o->write_characters(string_buffer.data(), bytes_after_last_accept);
  14837. // add a replacement character
  14838. if (ensure_ascii)
  14839. {
  14840. o->write_characters("\\ufffd", 6);
  14841. }
  14842. else
  14843. {
  14844. o->write_characters("\xEF\xBF\xBD", 3);
  14845. }
  14846. break;
  14847. }
  14848. default: // LCOV_EXCL_LINE
  14849. JSON_ASSERT(false); // NOLINT(cert-dcl03-c,hicpp-static-assert,misc-static-assert) LCOV_EXCL_LINE
  14850. }
  14851. }
  14852. }
  14853. private:
  14854. /*!
  14855. @brief count digits
  14856. Count the number of decimal (base 10) digits for an input unsigned integer.
  14857. @param[in] x unsigned integer number to count its digits
  14858. @return number of decimal digits
  14859. */
  14860. inline unsigned int count_digits(number_unsigned_t x) noexcept
  14861. {
  14862. unsigned int n_digits = 1;
  14863. for (;;)
  14864. {
  14865. if (x < 10)
  14866. {
  14867. return n_digits;
  14868. }
  14869. if (x < 100)
  14870. {
  14871. return n_digits + 1;
  14872. }
  14873. if (x < 1000)
  14874. {
  14875. return n_digits + 2;
  14876. }
  14877. if (x < 10000)
  14878. {
  14879. return n_digits + 3;
  14880. }
  14881. x = x / 10000u;
  14882. n_digits += 4;
  14883. }
  14884. }
  14885. /*!
  14886. @brief dump an integer
  14887. Dump a given integer to output stream @a o. Works internally with
  14888. @a number_buffer.
  14889. @param[in] x integer number (signed or unsigned) to dump
  14890. @tparam NumberType either @a number_integer_t or @a number_unsigned_t
  14891. */
  14892. template < typename NumberType, detail::enable_if_t <
  14893. std::is_integral<NumberType>::value ||
  14894. std::is_same<NumberType, number_unsigned_t>::value ||
  14895. std::is_same<NumberType, number_integer_t>::value ||
  14896. std::is_same<NumberType, binary_char_t>::value,
  14897. int > = 0 >
  14898. void dump_integer(NumberType x)
  14899. {
  14900. static constexpr std::array<std::array<char, 2>, 100> digits_to_99
  14901. {
  14902. {
  14903. {{'0', '0'}}, {{'0', '1'}}, {{'0', '2'}}, {{'0', '3'}}, {{'0', '4'}}, {{'0', '5'}}, {{'0', '6'}}, {{'0', '7'}}, {{'0', '8'}}, {{'0', '9'}},
  14904. {{'1', '0'}}, {{'1', '1'}}, {{'1', '2'}}, {{'1', '3'}}, {{'1', '4'}}, {{'1', '5'}}, {{'1', '6'}}, {{'1', '7'}}, {{'1', '8'}}, {{'1', '9'}},
  14905. {{'2', '0'}}, {{'2', '1'}}, {{'2', '2'}}, {{'2', '3'}}, {{'2', '4'}}, {{'2', '5'}}, {{'2', '6'}}, {{'2', '7'}}, {{'2', '8'}}, {{'2', '9'}},
  14906. {{'3', '0'}}, {{'3', '1'}}, {{'3', '2'}}, {{'3', '3'}}, {{'3', '4'}}, {{'3', '5'}}, {{'3', '6'}}, {{'3', '7'}}, {{'3', '8'}}, {{'3', '9'}},
  14907. {{'4', '0'}}, {{'4', '1'}}, {{'4', '2'}}, {{'4', '3'}}, {{'4', '4'}}, {{'4', '5'}}, {{'4', '6'}}, {{'4', '7'}}, {{'4', '8'}}, {{'4', '9'}},
  14908. {{'5', '0'}}, {{'5', '1'}}, {{'5', '2'}}, {{'5', '3'}}, {{'5', '4'}}, {{'5', '5'}}, {{'5', '6'}}, {{'5', '7'}}, {{'5', '8'}}, {{'5', '9'}},
  14909. {{'6', '0'}}, {{'6', '1'}}, {{'6', '2'}}, {{'6', '3'}}, {{'6', '4'}}, {{'6', '5'}}, {{'6', '6'}}, {{'6', '7'}}, {{'6', '8'}}, {{'6', '9'}},
  14910. {{'7', '0'}}, {{'7', '1'}}, {{'7', '2'}}, {{'7', '3'}}, {{'7', '4'}}, {{'7', '5'}}, {{'7', '6'}}, {{'7', '7'}}, {{'7', '8'}}, {{'7', '9'}},
  14911. {{'8', '0'}}, {{'8', '1'}}, {{'8', '2'}}, {{'8', '3'}}, {{'8', '4'}}, {{'8', '5'}}, {{'8', '6'}}, {{'8', '7'}}, {{'8', '8'}}, {{'8', '9'}},
  14912. {{'9', '0'}}, {{'9', '1'}}, {{'9', '2'}}, {{'9', '3'}}, {{'9', '4'}}, {{'9', '5'}}, {{'9', '6'}}, {{'9', '7'}}, {{'9', '8'}}, {{'9', '9'}},
  14913. }
  14914. };
  14915. // special case for "0"
  14916. if (x == 0)
  14917. {
  14918. o->write_character('0');
  14919. return;
  14920. }
  14921. // use a pointer to fill the buffer
  14922. auto buffer_ptr = number_buffer.begin(); // NOLINT(llvm-qualified-auto,readability-qualified-auto,cppcoreguidelines-pro-type-vararg,hicpp-vararg)
  14923. const bool is_negative = std::is_signed<NumberType>::value && !(x >= 0); // see issue #755
  14924. number_unsigned_t abs_value;
  14925. unsigned int n_chars{};
  14926. if (is_negative)
  14927. {
  14928. *buffer_ptr = '-';
  14929. abs_value = remove_sign(static_cast<number_integer_t>(x));
  14930. // account one more byte for the minus sign
  14931. n_chars = 1 + count_digits(abs_value);
  14932. }
  14933. else
  14934. {
  14935. abs_value = static_cast<number_unsigned_t>(x);
  14936. n_chars = count_digits(abs_value);
  14937. }
  14938. // spare 1 byte for '\0'
  14939. JSON_ASSERT(n_chars < number_buffer.size() - 1);
  14940. // jump to the end to generate the string from backward
  14941. // so we later avoid reversing the result
  14942. buffer_ptr += n_chars;
  14943. // Fast int2ascii implementation inspired by "Fastware" talk by Andrei Alexandrescu
  14944. // See: https://www.youtube.com/watch?v=o4-CwDo2zpg
  14945. while (abs_value >= 100)
  14946. {
  14947. const auto digits_index = static_cast<unsigned>((abs_value % 100));
  14948. abs_value /= 100;
  14949. *(--buffer_ptr) = digits_to_99[digits_index][1];
  14950. *(--buffer_ptr) = digits_to_99[digits_index][0];
  14951. }
  14952. if (abs_value >= 10)
  14953. {
  14954. const auto digits_index = static_cast<unsigned>(abs_value);
  14955. *(--buffer_ptr) = digits_to_99[digits_index][1];
  14956. *(--buffer_ptr) = digits_to_99[digits_index][0];
  14957. }
  14958. else
  14959. {
  14960. *(--buffer_ptr) = static_cast<char>('0' + abs_value);
  14961. }
  14962. o->write_characters(number_buffer.data(), n_chars);
  14963. }
  14964. /*!
  14965. @brief dump a floating-point number
  14966. Dump a given floating-point number to output stream @a o. Works internally
  14967. with @a number_buffer.
  14968. @param[in] x floating-point number to dump
  14969. */
  14970. void dump_float(number_float_t x)
  14971. {
  14972. // NaN / inf
  14973. if (!std::isfinite(x))
  14974. {
  14975. o->write_characters("null", 4);
  14976. return;
  14977. }
  14978. // If number_float_t is an IEEE-754 single or double precision number,
  14979. // use the Grisu2 algorithm to produce short numbers which are
  14980. // guaranteed to round-trip, using strtof and strtod, resp.
  14981. //
  14982. // NB: The test below works if <long double> == <double>.
  14983. static constexpr bool is_ieee_single_or_double
  14984. = (std::numeric_limits<number_float_t>::is_iec559 && std::numeric_limits<number_float_t>::digits == 24 && std::numeric_limits<number_float_t>::max_exponent == 128) ||
  14985. (std::numeric_limits<number_float_t>::is_iec559 && std::numeric_limits<number_float_t>::digits == 53 && std::numeric_limits<number_float_t>::max_exponent == 1024);
  14986. dump_float(x, std::integral_constant<bool, is_ieee_single_or_double>());
  14987. }
  14988. void dump_float(number_float_t x, std::true_type /*is_ieee_single_or_double*/)
  14989. {
  14990. auto* begin = number_buffer.data();
  14991. auto* end = ::nlohmann::detail::to_chars(begin, begin + number_buffer.size(), x);
  14992. o->write_characters(begin, static_cast<size_t>(end - begin));
  14993. }
  14994. void dump_float(number_float_t x, std::false_type /*is_ieee_single_or_double*/)
  14995. {
  14996. // get number of digits for a float -> text -> float round-trip
  14997. static constexpr auto d = std::numeric_limits<number_float_t>::max_digits10;
  14998. // the actual conversion
  14999. // NOLINTNEXTLINE(cppcoreguidelines-pro-type-vararg,hicpp-vararg)
  15000. std::ptrdiff_t len = (std::snprintf)(number_buffer.data(), number_buffer.size(), "%.*g", d, x);
  15001. // negative value indicates an error
  15002. JSON_ASSERT(len > 0);
  15003. // check if buffer was large enough
  15004. JSON_ASSERT(static_cast<std::size_t>(len) < number_buffer.size());
  15005. // erase thousands separator
  15006. if (thousands_sep != '\0')
  15007. {
  15008. // NOLINTNEXTLINE(readability-qualified-auto,llvm-qualified-auto): std::remove returns an iterator, see https://github.com/nlohmann/json/issues/3081
  15009. const auto end = std::remove(number_buffer.begin(), number_buffer.begin() + len, thousands_sep);
  15010. std::fill(end, number_buffer.end(), '\0');
  15011. JSON_ASSERT((end - number_buffer.begin()) <= len);
  15012. len = (end - number_buffer.begin());
  15013. }
  15014. // convert decimal point to '.'
  15015. if (decimal_point != '\0' && decimal_point != '.')
  15016. {
  15017. // NOLINTNEXTLINE(readability-qualified-auto,llvm-qualified-auto): std::find returns an iterator, see https://github.com/nlohmann/json/issues/3081
  15018. const auto dec_pos = std::find(number_buffer.begin(), number_buffer.end(), decimal_point);
  15019. if (dec_pos != number_buffer.end())
  15020. {
  15021. *dec_pos = '.';
  15022. }
  15023. }
  15024. o->write_characters(number_buffer.data(), static_cast<std::size_t>(len));
  15025. // determine if need to append ".0"
  15026. const bool value_is_int_like =
  15027. std::none_of(number_buffer.begin(), number_buffer.begin() + len + 1,
  15028. [](char c)
  15029. {
  15030. return c == '.' || c == 'e';
  15031. });
  15032. if (value_is_int_like)
  15033. {
  15034. o->write_characters(".0", 2);
  15035. }
  15036. }
  15037. /*!
  15038. @brief check whether a string is UTF-8 encoded
  15039. The function checks each byte of a string whether it is UTF-8 encoded. The
  15040. result of the check is stored in the @a state parameter. The function must
  15041. be called initially with state 0 (accept). State 1 means the string must
  15042. be rejected, because the current byte is not allowed. If the string is
  15043. completely processed, but the state is non-zero, the string ended
  15044. prematurely; that is, the last byte indicated more bytes should have
  15045. followed.
  15046. @param[in,out] state the state of the decoding
  15047. @param[in,out] codep codepoint (valid only if resulting state is UTF8_ACCEPT)
  15048. @param[in] byte next byte to decode
  15049. @return new state
  15050. @note The function has been edited: a std::array is used.
  15051. @copyright Copyright (c) 2008-2009 Bjoern Hoehrmann <[email protected]>
  15052. @sa http://bjoern.hoehrmann.de/utf-8/decoder/dfa/
  15053. */
  15054. static std::uint8_t decode(std::uint8_t& state, std::uint32_t& codep, const std::uint8_t byte) noexcept
  15055. {
  15056. static const std::array<std::uint8_t, 400> utf8d =
  15057. {
  15058. {
  15059. 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
  15060. 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
  15061. 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
  15062. 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
  15063. 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
  15064. 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
  15065. 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
  15066. 0xA, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x4, 0x3, 0x3, // E0..EF
  15067. 0xB, 0x6, 0x6, 0x6, 0x5, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, // F0..FF
  15068. 0x0, 0x1, 0x2, 0x3, 0x5, 0x8, 0x7, 0x1, 0x1, 0x1, 0x4, 0x6, 0x1, 0x1, 0x1, 0x1, // s0..s0
  15069. 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
  15070. 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
  15071. 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
  15072. 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
  15073. }
  15074. };
  15075. JSON_ASSERT(byte < utf8d.size());
  15076. const std::uint8_t type = utf8d[byte];
  15077. codep = (state != UTF8_ACCEPT)
  15078. ? (byte & 0x3fu) | (codep << 6u)
  15079. : (0xFFu >> type) & (byte);
  15080. std::size_t index = 256u + static_cast<size_t>(state) * 16u + static_cast<size_t>(type);
  15081. JSON_ASSERT(index < 400);
  15082. state = utf8d[index];
  15083. return state;
  15084. }
  15085. /*
  15086. * Overload to make the compiler happy while it is instantiating
  15087. * dump_integer for number_unsigned_t.
  15088. * Must never be called.
  15089. */
  15090. number_unsigned_t remove_sign(number_unsigned_t x)
  15091. {
  15092. JSON_ASSERT(false); // NOLINT(cert-dcl03-c,hicpp-static-assert,misc-static-assert) LCOV_EXCL_LINE
  15093. return x; // LCOV_EXCL_LINE
  15094. }
  15095. /*
  15096. * Helper function for dump_integer
  15097. *
  15098. * This function takes a negative signed integer and returns its absolute
  15099. * value as unsigned integer. The plus/minus shuffling is necessary as we can
  15100. * not directly remove the sign of an arbitrary signed integer as the
  15101. * absolute values of INT_MIN and INT_MAX are usually not the same. See
  15102. * #1708 for details.
  15103. */
  15104. inline number_unsigned_t remove_sign(number_integer_t x) noexcept
  15105. {
  15106. JSON_ASSERT(x < 0 && x < (std::numeric_limits<number_integer_t>::max)()); // NOLINT(misc-redundant-expression)
  15107. return static_cast<number_unsigned_t>(-(x + 1)) + 1;
  15108. }
  15109. private:
  15110. /// the output of the serializer
  15111. output_adapter_t<char> o = nullptr;
  15112. /// a (hopefully) large enough character buffer
  15113. std::array<char, 64> number_buffer{{}};
  15114. /// the locale
  15115. const std::lconv* loc = nullptr;
  15116. /// the locale's thousand separator character
  15117. const char thousands_sep = '\0';
  15118. /// the locale's decimal point character
  15119. const char decimal_point = '\0';
  15120. /// string buffer
  15121. std::array<char, 512> string_buffer{{}};
  15122. /// the indentation character
  15123. const char indent_char;
  15124. /// the indentation string
  15125. string_t indent_string;
  15126. /// error_handler how to react on decoding errors
  15127. const error_handler_t error_handler;
  15128. };
  15129. } // namespace detail
  15130. } // namespace nlohmann
  15131. // #include <nlohmann/detail/value_t.hpp>
  15132. // #include <nlohmann/json_fwd.hpp>
  15133. // #include <nlohmann/ordered_map.hpp>
  15134. #include <functional> // less
  15135. #include <initializer_list> // initializer_list
  15136. #include <iterator> // input_iterator_tag, iterator_traits
  15137. #include <memory> // allocator
  15138. #include <stdexcept> // for out_of_range
  15139. #include <type_traits> // enable_if, is_convertible
  15140. #include <utility> // pair
  15141. #include <vector> // vector
  15142. // #include <nlohmann/detail/macro_scope.hpp>
  15143. namespace nlohmann
  15144. {
  15145. /// ordered_map: a minimal map-like container that preserves insertion order
  15146. /// for use within nlohmann::basic_json<ordered_map>
  15147. template <class Key, class T, class IgnoredLess = std::less<Key>,
  15148. class Allocator = std::allocator<std::pair<const Key, T>>>
  15149. struct ordered_map : std::vector<std::pair<const Key, T>, Allocator>
  15150. {
  15151. using key_type = Key;
  15152. using mapped_type = T;
  15153. using Container = std::vector<std::pair<const Key, T>, Allocator>;
  15154. using typename Container::iterator;
  15155. using typename Container::const_iterator;
  15156. using typename Container::size_type;
  15157. using typename Container::value_type;
  15158. // Explicit constructors instead of `using Container::Container`
  15159. // otherwise older compilers choke on it (GCC <= 5.5, xcode <= 9.4)
  15160. ordered_map(const Allocator& alloc = Allocator()) : Container{alloc} {}
  15161. template <class It>
  15162. ordered_map(It first, It last, const Allocator& alloc = Allocator())
  15163. : Container{first, last, alloc} {}
  15164. ordered_map(std::initializer_list<T> init, const Allocator& alloc = Allocator() )
  15165. : Container{init, alloc} {}
  15166. std::pair<iterator, bool> emplace(const key_type& key, T&& t)
  15167. {
  15168. for (auto it = this->begin(); it != this->end(); ++it)
  15169. {
  15170. if (it->first == key)
  15171. {
  15172. return {it, false};
  15173. }
  15174. }
  15175. Container::emplace_back(key, t);
  15176. return {--this->end(), true};
  15177. }
  15178. T& operator[](const Key& key)
  15179. {
  15180. return emplace(key, T{}).first->second;
  15181. }
  15182. const T& operator[](const Key& key) const
  15183. {
  15184. return at(key);
  15185. }
  15186. T& at(const Key& key)
  15187. {
  15188. for (auto it = this->begin(); it != this->end(); ++it)
  15189. {
  15190. if (it->first == key)
  15191. {
  15192. return it->second;
  15193. }
  15194. }
  15195. JSON_THROW(std::out_of_range("key not found"));
  15196. }
  15197. const T& at(const Key& key) const
  15198. {
  15199. for (auto it = this->begin(); it != this->end(); ++it)
  15200. {
  15201. if (it->first == key)
  15202. {
  15203. return it->second;
  15204. }
  15205. }
  15206. JSON_THROW(std::out_of_range("key not found"));
  15207. }
  15208. size_type erase(const Key& key)
  15209. {
  15210. for (auto it = this->begin(); it != this->end(); ++it)
  15211. {
  15212. if (it->first == key)
  15213. {
  15214. // Since we cannot move const Keys, re-construct them in place
  15215. for (auto next = it; ++next != this->end(); ++it)
  15216. {
  15217. it->~value_type(); // Destroy but keep allocation
  15218. new (&*it) value_type{std::move(*next)};
  15219. }
  15220. Container::pop_back();
  15221. return 1;
  15222. }
  15223. }
  15224. return 0;
  15225. }
  15226. iterator erase(iterator pos)
  15227. {
  15228. auto it = pos;
  15229. // Since we cannot move const Keys, re-construct them in place
  15230. for (auto next = it; ++next != this->end(); ++it)
  15231. {
  15232. it->~value_type(); // Destroy but keep allocation
  15233. new (&*it) value_type{std::move(*next)};
  15234. }
  15235. Container::pop_back();
  15236. return pos;
  15237. }
  15238. size_type count(const Key& key) const
  15239. {
  15240. for (auto it = this->begin(); it != this->end(); ++it)
  15241. {
  15242. if (it->first == key)
  15243. {
  15244. return 1;
  15245. }
  15246. }
  15247. return 0;
  15248. }
  15249. iterator find(const Key& key)
  15250. {
  15251. for (auto it = this->begin(); it != this->end(); ++it)
  15252. {
  15253. if (it->first == key)
  15254. {
  15255. return it;
  15256. }
  15257. }
  15258. return Container::end();
  15259. }
  15260. const_iterator find(const Key& key) const
  15261. {
  15262. for (auto it = this->begin(); it != this->end(); ++it)
  15263. {
  15264. if (it->first == key)
  15265. {
  15266. return it;
  15267. }
  15268. }
  15269. return Container::end();
  15270. }
  15271. std::pair<iterator, bool> insert( value_type&& value )
  15272. {
  15273. return emplace(value.first, std::move(value.second));
  15274. }
  15275. std::pair<iterator, bool> insert( const value_type& value )
  15276. {
  15277. for (auto it = this->begin(); it != this->end(); ++it)
  15278. {
  15279. if (it->first == value.first)
  15280. {
  15281. return {it, false};
  15282. }
  15283. }
  15284. Container::push_back(value);
  15285. return {--this->end(), true};
  15286. }
  15287. template<typename InputIt>
  15288. using require_input_iter = typename std::enable_if<std::is_convertible<typename std::iterator_traits<InputIt>::iterator_category,
  15289. std::input_iterator_tag>::value>::type;
  15290. template<typename InputIt, typename = require_input_iter<InputIt>>
  15291. void insert(InputIt first, InputIt last)
  15292. {
  15293. for (auto it = first; it != last; ++it)
  15294. {
  15295. insert(*it);
  15296. }
  15297. }
  15298. };
  15299. } // namespace nlohmann
  15300. #if defined(JSON_HAS_CPP_17)
  15301. #include <string_view>
  15302. #endif
  15303. /*!
  15304. @brief namespace for Niels Lohmann
  15305. @see https://github.com/nlohmann
  15306. @since version 1.0.0
  15307. */
  15308. namespace nlohmann
  15309. {
  15310. /*!
  15311. @brief a class to store JSON values
  15312. @tparam ObjectType type for JSON objects (`std::map` by default; will be used
  15313. in @ref object_t)
  15314. @tparam ArrayType type for JSON arrays (`std::vector` by default; will be used
  15315. in @ref array_t)
  15316. @tparam StringType type for JSON strings and object keys (`std::string` by
  15317. default; will be used in @ref string_t)
  15318. @tparam BooleanType type for JSON booleans (`bool` by default; will be used
  15319. in @ref boolean_t)
  15320. @tparam NumberIntegerType type for JSON integer numbers (`int64_t` by
  15321. default; will be used in @ref number_integer_t)
  15322. @tparam NumberUnsignedType type for JSON unsigned integer numbers (@c
  15323. `uint64_t` by default; will be used in @ref number_unsigned_t)
  15324. @tparam NumberFloatType type for JSON floating-point numbers (`double` by
  15325. default; will be used in @ref number_float_t)
  15326. @tparam BinaryType type for packed binary data for compatibility with binary
  15327. serialization formats (`std::vector<std::uint8_t>` by default; will be used in
  15328. @ref binary_t)
  15329. @tparam AllocatorType type of the allocator to use (`std::allocator` by
  15330. default)
  15331. @tparam JSONSerializer the serializer to resolve internal calls to `to_json()`
  15332. and `from_json()` (@ref adl_serializer by default)
  15333. @requirement The class satisfies the following concept requirements:
  15334. - Basic
  15335. - [DefaultConstructible](https://en.cppreference.com/w/cpp/named_req/DefaultConstructible):
  15336. JSON values can be default constructed. The result will be a JSON null
  15337. value.
  15338. - [MoveConstructible](https://en.cppreference.com/w/cpp/named_req/MoveConstructible):
  15339. A JSON value can be constructed from an rvalue argument.
  15340. - [CopyConstructible](https://en.cppreference.com/w/cpp/named_req/CopyConstructible):
  15341. A JSON value can be copy-constructed from an lvalue expression.
  15342. - [MoveAssignable](https://en.cppreference.com/w/cpp/named_req/MoveAssignable):
  15343. A JSON value van be assigned from an rvalue argument.
  15344. - [CopyAssignable](https://en.cppreference.com/w/cpp/named_req/CopyAssignable):
  15345. A JSON value can be copy-assigned from an lvalue expression.
  15346. - [Destructible](https://en.cppreference.com/w/cpp/named_req/Destructible):
  15347. JSON values can be destructed.
  15348. - Layout
  15349. - [StandardLayoutType](https://en.cppreference.com/w/cpp/named_req/StandardLayoutType):
  15350. JSON values have
  15351. [standard layout](https://en.cppreference.com/w/cpp/language/data_members#Standard_layout):
  15352. All non-static data members are private and standard layout types, the
  15353. class has no virtual functions or (virtual) base classes.
  15354. - Library-wide
  15355. - [EqualityComparable](https://en.cppreference.com/w/cpp/named_req/EqualityComparable):
  15356. JSON values can be compared with `==`, see @ref
  15357. operator==(const_reference,const_reference).
  15358. - [LessThanComparable](https://en.cppreference.com/w/cpp/named_req/LessThanComparable):
  15359. JSON values can be compared with `<`, see @ref
  15360. operator<(const_reference,const_reference).
  15361. - [Swappable](https://en.cppreference.com/w/cpp/named_req/Swappable):
  15362. Any JSON lvalue or rvalue of can be swapped with any lvalue or rvalue of
  15363. other compatible types, using unqualified function call @ref swap().
  15364. - [NullablePointer](https://en.cppreference.com/w/cpp/named_req/NullablePointer):
  15365. JSON values can be compared against `std::nullptr_t` objects which are used
  15366. to model the `null` value.
  15367. - Container
  15368. - [Container](https://en.cppreference.com/w/cpp/named_req/Container):
  15369. JSON values can be used like STL containers and provide iterator access.
  15370. - [ReversibleContainer](https://en.cppreference.com/w/cpp/named_req/ReversibleContainer);
  15371. JSON values can be used like STL containers and provide reverse iterator
  15372. access.
  15373. @invariant The member variables @a m_value and @a m_type have the following
  15374. relationship:
  15375. - If `m_type == value_t::object`, then `m_value.object != nullptr`.
  15376. - If `m_type == value_t::array`, then `m_value.array != nullptr`.
  15377. - If `m_type == value_t::string`, then `m_value.string != nullptr`.
  15378. The invariants are checked by member function assert_invariant().
  15379. @internal
  15380. @note ObjectType trick from https://stackoverflow.com/a/9860911
  15381. @endinternal
  15382. @see [RFC 8259: The JavaScript Object Notation (JSON) Data Interchange
  15383. Format](https://tools.ietf.org/html/rfc8259)
  15384. @since version 1.0.0
  15385. @nosubgrouping
  15386. */
  15387. NLOHMANN_BASIC_JSON_TPL_DECLARATION
  15388. class basic_json // NOLINT(cppcoreguidelines-special-member-functions,hicpp-special-member-functions)
  15389. {
  15390. private:
  15391. template<detail::value_t> friend struct detail::external_constructor;
  15392. friend ::nlohmann::json_pointer<basic_json>;
  15393. template<typename BasicJsonType, typename InputType>
  15394. friend class ::nlohmann::detail::parser;
  15395. friend ::nlohmann::detail::serializer<basic_json>;
  15396. template<typename BasicJsonType>
  15397. friend class ::nlohmann::detail::iter_impl;
  15398. template<typename BasicJsonType, typename CharType>
  15399. friend class ::nlohmann::detail::binary_writer;
  15400. template<typename BasicJsonType, typename InputType, typename SAX>
  15401. friend class ::nlohmann::detail::binary_reader;
  15402. template<typename BasicJsonType>
  15403. friend class ::nlohmann::detail::json_sax_dom_parser;
  15404. template<typename BasicJsonType>
  15405. friend class ::nlohmann::detail::json_sax_dom_callback_parser;
  15406. friend class ::nlohmann::detail::exception;
  15407. /// workaround type for MSVC
  15408. using basic_json_t = NLOHMANN_BASIC_JSON_TPL;
  15409. JSON_PRIVATE_UNLESS_TESTED:
  15410. // convenience aliases for types residing in namespace detail;
  15411. using lexer = ::nlohmann::detail::lexer_base<basic_json>;
  15412. template<typename InputAdapterType>
  15413. static ::nlohmann::detail::parser<basic_json, InputAdapterType> parser(
  15414. InputAdapterType adapter,
  15415. detail::parser_callback_t<basic_json>cb = nullptr,
  15416. const bool allow_exceptions = true,
  15417. const bool ignore_comments = false
  15418. )
  15419. {
  15420. return ::nlohmann::detail::parser<basic_json, InputAdapterType>(std::move(adapter),
  15421. std::move(cb), allow_exceptions, ignore_comments);
  15422. }
  15423. private:
  15424. using primitive_iterator_t = ::nlohmann::detail::primitive_iterator_t;
  15425. template<typename BasicJsonType>
  15426. using internal_iterator = ::nlohmann::detail::internal_iterator<BasicJsonType>;
  15427. template<typename BasicJsonType>
  15428. using iter_impl = ::nlohmann::detail::iter_impl<BasicJsonType>;
  15429. template<typename Iterator>
  15430. using iteration_proxy = ::nlohmann::detail::iteration_proxy<Iterator>;
  15431. template<typename Base> using json_reverse_iterator = ::nlohmann::detail::json_reverse_iterator<Base>;
  15432. template<typename CharType>
  15433. using output_adapter_t = ::nlohmann::detail::output_adapter_t<CharType>;
  15434. template<typename InputType>
  15435. using binary_reader = ::nlohmann::detail::binary_reader<basic_json, InputType>;
  15436. template<typename CharType> using binary_writer = ::nlohmann::detail::binary_writer<basic_json, CharType>;
  15437. JSON_PRIVATE_UNLESS_TESTED:
  15438. using serializer = ::nlohmann::detail::serializer<basic_json>;
  15439. public:
  15440. using value_t = detail::value_t;
  15441. /// JSON Pointer, see @ref nlohmann::json_pointer
  15442. using json_pointer = ::nlohmann::json_pointer<basic_json>;
  15443. template<typename T, typename SFINAE>
  15444. using json_serializer = JSONSerializer<T, SFINAE>;
  15445. /// how to treat decoding errors
  15446. using error_handler_t = detail::error_handler_t;
  15447. /// how to treat CBOR tags
  15448. using cbor_tag_handler_t = detail::cbor_tag_handler_t;
  15449. /// helper type for initializer lists of basic_json values
  15450. using initializer_list_t = std::initializer_list<detail::json_ref<basic_json>>;
  15451. using input_format_t = detail::input_format_t;
  15452. /// SAX interface type, see @ref nlohmann::json_sax
  15453. using json_sax_t = json_sax<basic_json>;
  15454. ////////////////
  15455. // exceptions //
  15456. ////////////////
  15457. /// @name exceptions
  15458. /// Classes to implement user-defined exceptions.
  15459. /// @{
  15460. /// @copydoc detail::exception
  15461. using exception = detail::exception;
  15462. /// @copydoc detail::parse_error
  15463. using parse_error = detail::parse_error;
  15464. /// @copydoc detail::invalid_iterator
  15465. using invalid_iterator = detail::invalid_iterator;
  15466. /// @copydoc detail::type_error
  15467. using type_error = detail::type_error;
  15468. /// @copydoc detail::out_of_range
  15469. using out_of_range = detail::out_of_range;
  15470. /// @copydoc detail::other_error
  15471. using other_error = detail::other_error;
  15472. /// @}
  15473. /////////////////////
  15474. // container types //
  15475. /////////////////////
  15476. /// @name container types
  15477. /// The canonic container types to use @ref basic_json like any other STL
  15478. /// container.
  15479. /// @{
  15480. /// the type of elements in a basic_json container
  15481. using value_type = basic_json;
  15482. /// the type of an element reference
  15483. using reference = value_type&;
  15484. /// the type of an element const reference
  15485. using const_reference = const value_type&;
  15486. /// a type to represent differences between iterators
  15487. using difference_type = std::ptrdiff_t;
  15488. /// a type to represent container sizes
  15489. using size_type = std::size_t;
  15490. /// the allocator type
  15491. using allocator_type = AllocatorType<basic_json>;
  15492. /// the type of an element pointer
  15493. using pointer = typename std::allocator_traits<allocator_type>::pointer;
  15494. /// the type of an element const pointer
  15495. using const_pointer = typename std::allocator_traits<allocator_type>::const_pointer;
  15496. /// an iterator for a basic_json container
  15497. using iterator = iter_impl<basic_json>;
  15498. /// a const iterator for a basic_json container
  15499. using const_iterator = iter_impl<const basic_json>;
  15500. /// a reverse iterator for a basic_json container
  15501. using reverse_iterator = json_reverse_iterator<typename basic_json::iterator>;
  15502. /// a const reverse iterator for a basic_json container
  15503. using const_reverse_iterator = json_reverse_iterator<typename basic_json::const_iterator>;
  15504. /// @}
  15505. /*!
  15506. @brief returns the allocator associated with the container
  15507. */
  15508. static allocator_type get_allocator()
  15509. {
  15510. return allocator_type();
  15511. }
  15512. /*!
  15513. @brief returns version information on the library
  15514. This function returns a JSON object with information about the library,
  15515. including the version number and information on the platform and compiler.
  15516. @return JSON object holding version information
  15517. key | description
  15518. ----------- | ---------------
  15519. `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).
  15520. `copyright` | The copyright line for the library as string.
  15521. `name` | The name of the library as string.
  15522. `platform` | The used platform as string. Possible values are `win32`, `linux`, `apple`, `unix`, and `unknown`.
  15523. `url` | The URL of the project as string.
  15524. `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).
  15525. @liveexample{The following code shows an example output of the `meta()`
  15526. function.,meta}
  15527. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  15528. changes to any JSON value.
  15529. @complexity Constant.
  15530. @since 2.1.0
  15531. */
  15532. JSON_HEDLEY_WARN_UNUSED_RESULT
  15533. static basic_json meta()
  15534. {
  15535. basic_json result;
  15536. result["copyright"] = "(C) 2013-2021 Niels Lohmann";
  15537. result["name"] = "JSON for Modern C++";
  15538. result["url"] = "https://github.com/nlohmann/json";
  15539. result["version"]["string"] =
  15540. std::to_string(NLOHMANN_JSON_VERSION_MAJOR) + "." +
  15541. std::to_string(NLOHMANN_JSON_VERSION_MINOR) + "." +
  15542. std::to_string(NLOHMANN_JSON_VERSION_PATCH);
  15543. result["version"]["major"] = NLOHMANN_JSON_VERSION_MAJOR;
  15544. result["version"]["minor"] = NLOHMANN_JSON_VERSION_MINOR;
  15545. result["version"]["patch"] = NLOHMANN_JSON_VERSION_PATCH;
  15546. #ifdef _WIN32
  15547. result["platform"] = "win32";
  15548. #elif defined __linux__
  15549. result["platform"] = "linux";
  15550. #elif defined __APPLE__
  15551. result["platform"] = "apple";
  15552. #elif defined __unix__
  15553. result["platform"] = "unix";
  15554. #else
  15555. result["platform"] = "unknown";
  15556. #endif
  15557. #if defined(__ICC) || defined(__INTEL_COMPILER)
  15558. result["compiler"] = {{"family", "icc"}, {"version", __INTEL_COMPILER}};
  15559. #elif defined(__clang__)
  15560. result["compiler"] = {{"family", "clang"}, {"version", __clang_version__}};
  15561. #elif defined(__GNUC__) || defined(__GNUG__)
  15562. result["compiler"] = {{"family", "gcc"}, {"version", std::to_string(__GNUC__) + "." + std::to_string(__GNUC_MINOR__) + "." + std::to_string(__GNUC_PATCHLEVEL__)}};
  15563. #elif defined(__HP_cc) || defined(__HP_aCC)
  15564. result["compiler"] = "hp"
  15565. #elif defined(__IBMCPP__)
  15566. result["compiler"] = {{"family", "ilecpp"}, {"version", __IBMCPP__}};
  15567. #elif defined(_MSC_VER)
  15568. result["compiler"] = {{"family", "msvc"}, {"version", _MSC_VER}};
  15569. #elif defined(__PGI)
  15570. result["compiler"] = {{"family", "pgcpp"}, {"version", __PGI}};
  15571. #elif defined(__SUNPRO_CC)
  15572. result["compiler"] = {{"family", "sunpro"}, {"version", __SUNPRO_CC}};
  15573. #else
  15574. result["compiler"] = {{"family", "unknown"}, {"version", "unknown"}};
  15575. #endif
  15576. #ifdef __cplusplus
  15577. result["compiler"]["c++"] = std::to_string(__cplusplus);
  15578. #else
  15579. result["compiler"]["c++"] = "unknown";
  15580. #endif
  15581. return result;
  15582. }
  15583. ///////////////////////////
  15584. // JSON value data types //
  15585. ///////////////////////////
  15586. /// @name JSON value data types
  15587. /// The data types to store a JSON value. These types are derived from
  15588. /// the template arguments passed to class @ref basic_json.
  15589. /// @{
  15590. #if defined(JSON_HAS_CPP_14)
  15591. // Use transparent comparator if possible, combined with perfect forwarding
  15592. // on find() and count() calls prevents unnecessary string construction.
  15593. using object_comparator_t = std::less<>;
  15594. #else
  15595. using object_comparator_t = std::less<StringType>;
  15596. #endif
  15597. /*!
  15598. @brief a type for an object
  15599. [RFC 8259](https://tools.ietf.org/html/rfc8259) describes JSON objects as follows:
  15600. > An object is an unordered collection of zero or more name/value pairs,
  15601. > where a name is a string and a value is a string, number, boolean, null,
  15602. > object, or array.
  15603. To store objects in C++, a type is defined by the template parameters
  15604. described below.
  15605. @tparam ObjectType the container to store objects (e.g., `std::map` or
  15606. `std::unordered_map`)
  15607. @tparam StringType the type of the keys or names (e.g., `std::string`).
  15608. The comparison function `std::less<StringType>` is used to order elements
  15609. inside the container.
  15610. @tparam AllocatorType the allocator to use for objects (e.g.,
  15611. `std::allocator`)
  15612. #### Default type
  15613. With the default values for @a ObjectType (`std::map`), @a StringType
  15614. (`std::string`), and @a AllocatorType (`std::allocator`), the default
  15615. value for @a object_t is:
  15616. @code {.cpp}
  15617. std::map<
  15618. std::string, // key_type
  15619. basic_json, // value_type
  15620. std::less<std::string>, // key_compare
  15621. std::allocator<std::pair<const std::string, basic_json>> // allocator_type
  15622. >
  15623. @endcode
  15624. #### Behavior
  15625. The choice of @a object_t influences the behavior of the JSON class. With
  15626. the default type, objects have the following behavior:
  15627. - When all names are unique, objects will be interoperable in the sense
  15628. that all software implementations receiving that object will agree on
  15629. the name-value mappings.
  15630. - When the names within an object are not unique, it is unspecified which
  15631. one of the values for a given key will be chosen. For instance,
  15632. `{"key": 2, "key": 1}` could be equal to either `{"key": 1}` or
  15633. `{"key": 2}`.
  15634. - Internally, name/value pairs are stored in lexicographical order of the
  15635. names. Objects will also be serialized (see @ref dump) in this order.
  15636. For instance, `{"b": 1, "a": 2}` and `{"a": 2, "b": 1}` will be stored
  15637. and serialized as `{"a": 2, "b": 1}`.
  15638. - When comparing objects, the order of the name/value pairs is irrelevant.
  15639. This makes objects interoperable in the sense that they will not be
  15640. affected by these differences. For instance, `{"b": 1, "a": 2}` and
  15641. `{"a": 2, "b": 1}` will be treated as equal.
  15642. #### Limits
  15643. [RFC 8259](https://tools.ietf.org/html/rfc8259) specifies:
  15644. > An implementation may set limits on the maximum depth of nesting.
  15645. In this class, the object's limit of nesting is not explicitly constrained.
  15646. However, a maximum depth of nesting may be introduced by the compiler or
  15647. runtime environment. A theoretical limit can be queried by calling the
  15648. @ref max_size function of a JSON object.
  15649. #### Storage
  15650. Objects are stored as pointers in a @ref basic_json type. That is, for any
  15651. access to object values, a pointer of type `object_t*` must be
  15652. dereferenced.
  15653. @sa see @ref array_t -- type for an array value
  15654. @since version 1.0.0
  15655. @note The order name/value pairs are added to the object is *not*
  15656. preserved by the library. Therefore, iterating an object may return
  15657. name/value pairs in a different order than they were originally stored. In
  15658. fact, keys will be traversed in alphabetical order as `std::map` with
  15659. `std::less` is used by default. Please note this behavior conforms to [RFC
  15660. 8259](https://tools.ietf.org/html/rfc8259), because any order implements the
  15661. specified "unordered" nature of JSON objects.
  15662. */
  15663. using object_t = ObjectType<StringType,
  15664. basic_json,
  15665. object_comparator_t,
  15666. AllocatorType<std::pair<const StringType,
  15667. basic_json>>>;
  15668. /*!
  15669. @brief a type for an array
  15670. [RFC 8259](https://tools.ietf.org/html/rfc8259) describes JSON arrays as follows:
  15671. > An array is an ordered sequence of zero or more values.
  15672. To store objects in C++, a type is defined by the template parameters
  15673. explained below.
  15674. @tparam ArrayType container type to store arrays (e.g., `std::vector` or
  15675. `std::list`)
  15676. @tparam AllocatorType allocator to use for arrays (e.g., `std::allocator`)
  15677. #### Default type
  15678. With the default values for @a ArrayType (`std::vector`) and @a
  15679. AllocatorType (`std::allocator`), the default value for @a array_t is:
  15680. @code {.cpp}
  15681. std::vector<
  15682. basic_json, // value_type
  15683. std::allocator<basic_json> // allocator_type
  15684. >
  15685. @endcode
  15686. #### Limits
  15687. [RFC 8259](https://tools.ietf.org/html/rfc8259) specifies:
  15688. > An implementation may set limits on the maximum depth of nesting.
  15689. In this class, the array's limit of nesting is not explicitly constrained.
  15690. However, a maximum depth of nesting may be introduced by the compiler or
  15691. runtime environment. A theoretical limit can be queried by calling the
  15692. @ref max_size function of a JSON array.
  15693. #### Storage
  15694. Arrays are stored as pointers in a @ref basic_json type. That is, for any
  15695. access to array values, a pointer of type `array_t*` must be dereferenced.
  15696. @sa see @ref object_t -- type for an object value
  15697. @since version 1.0.0
  15698. */
  15699. using array_t = ArrayType<basic_json, AllocatorType<basic_json>>;
  15700. /*!
  15701. @brief a type for a string
  15702. [RFC 8259](https://tools.ietf.org/html/rfc8259) describes JSON strings as follows:
  15703. > A string is a sequence of zero or more Unicode characters.
  15704. To store objects in C++, a type is defined by the template parameter
  15705. described below. Unicode values are split by the JSON class into
  15706. byte-sized characters during deserialization.
  15707. @tparam StringType the container to store strings (e.g., `std::string`).
  15708. Note this container is used for keys/names in objects, see @ref object_t.
  15709. #### Default type
  15710. With the default values for @a StringType (`std::string`), the default
  15711. value for @a string_t is:
  15712. @code {.cpp}
  15713. std::string
  15714. @endcode
  15715. #### Encoding
  15716. Strings are stored in UTF-8 encoding. Therefore, functions like
  15717. `std::string::size()` or `std::string::length()` return the number of
  15718. bytes in the string rather than the number of characters or glyphs.
  15719. #### String comparison
  15720. [RFC 8259](https://tools.ietf.org/html/rfc8259) states:
  15721. > Software implementations are typically required to test names of object
  15722. > members for equality. Implementations that transform the textual
  15723. > representation into sequences of Unicode code units and then perform the
  15724. > comparison numerically, code unit by code unit, are interoperable in the
  15725. > sense that implementations will agree in all cases on equality or
  15726. > inequality of two strings. For example, implementations that compare
  15727. > strings with escaped characters unconverted may incorrectly find that
  15728. > `"a\\b"` and `"a\u005Cb"` are not equal.
  15729. This implementation is interoperable as it does compare strings code unit
  15730. by code unit.
  15731. #### Storage
  15732. String values are stored as pointers in a @ref basic_json type. That is,
  15733. for any access to string values, a pointer of type `string_t*` must be
  15734. dereferenced.
  15735. @since version 1.0.0
  15736. */
  15737. using string_t = StringType;
  15738. /*!
  15739. @brief a type for a boolean
  15740. [RFC 8259](https://tools.ietf.org/html/rfc8259) implicitly describes a boolean as a
  15741. type which differentiates the two literals `true` and `false`.
  15742. To store objects in C++, a type is defined by the template parameter @a
  15743. BooleanType which chooses the type to use.
  15744. #### Default type
  15745. With the default values for @a BooleanType (`bool`), the default value for
  15746. @a boolean_t is:
  15747. @code {.cpp}
  15748. bool
  15749. @endcode
  15750. #### Storage
  15751. Boolean values are stored directly inside a @ref basic_json type.
  15752. @since version 1.0.0
  15753. */
  15754. using boolean_t = BooleanType;
  15755. /*!
  15756. @brief a type for a number (integer)
  15757. [RFC 8259](https://tools.ietf.org/html/rfc8259) describes numbers as follows:
  15758. > The representation of numbers is similar to that used in most
  15759. > programming languages. A number is represented in base 10 using decimal
  15760. > digits. It contains an integer component that may be prefixed with an
  15761. > optional minus sign, which may be followed by a fraction part and/or an
  15762. > exponent part. Leading zeros are not allowed. (...) Numeric values that
  15763. > cannot be represented in the grammar below (such as Infinity and NaN)
  15764. > are not permitted.
  15765. This description includes both integer and floating-point numbers.
  15766. However, C++ allows more precise storage if it is known whether the number
  15767. is a signed integer, an unsigned integer or a floating-point number.
  15768. Therefore, three different types, @ref number_integer_t, @ref
  15769. number_unsigned_t and @ref number_float_t are used.
  15770. To store integer numbers in C++, a type is defined by the template
  15771. parameter @a NumberIntegerType which chooses the type to use.
  15772. #### Default type
  15773. With the default values for @a NumberIntegerType (`int64_t`), the default
  15774. value for @a number_integer_t is:
  15775. @code {.cpp}
  15776. int64_t
  15777. @endcode
  15778. #### Default behavior
  15779. - The restrictions about leading zeros is not enforced in C++. Instead,
  15780. leading zeros in integer literals lead to an interpretation as octal
  15781. number. Internally, the value will be stored as decimal number. For
  15782. instance, the C++ integer literal `010` will be serialized to `8`.
  15783. During deserialization, leading zeros yield an error.
  15784. - Not-a-number (NaN) values will be serialized to `null`.
  15785. #### Limits
  15786. [RFC 8259](https://tools.ietf.org/html/rfc8259) specifies:
  15787. > An implementation may set limits on the range and precision of numbers.
  15788. When the default type is used, the maximal integer number that can be
  15789. stored is `9223372036854775807` (INT64_MAX) and the minimal integer number
  15790. that can be stored is `-9223372036854775808` (INT64_MIN). Integer numbers
  15791. that are out of range will yield over/underflow when used in a
  15792. constructor. During deserialization, too large or small integer numbers
  15793. will be automatically be stored as @ref number_unsigned_t or @ref
  15794. number_float_t.
  15795. [RFC 8259](https://tools.ietf.org/html/rfc8259) further states:
  15796. > Note that when such software is used, numbers that are integers and are
  15797. > in the range \f$[-2^{53}+1, 2^{53}-1]\f$ are interoperable in the sense
  15798. > that implementations will agree exactly on their numeric values.
  15799. As this range is a subrange of the exactly supported range [INT64_MIN,
  15800. INT64_MAX], this class's integer type is interoperable.
  15801. #### Storage
  15802. Integer number values are stored directly inside a @ref basic_json type.
  15803. @sa see @ref number_float_t -- type for number values (floating-point)
  15804. @sa see @ref number_unsigned_t -- type for number values (unsigned integer)
  15805. @since version 1.0.0
  15806. */
  15807. using number_integer_t = NumberIntegerType;
  15808. /*!
  15809. @brief a type for a number (unsigned)
  15810. [RFC 8259](https://tools.ietf.org/html/rfc8259) describes numbers as follows:
  15811. > The representation of numbers is similar to that used in most
  15812. > programming languages. A number is represented in base 10 using decimal
  15813. > digits. It contains an integer component that may be prefixed with an
  15814. > optional minus sign, which may be followed by a fraction part and/or an
  15815. > exponent part. Leading zeros are not allowed. (...) Numeric values that
  15816. > cannot be represented in the grammar below (such as Infinity and NaN)
  15817. > are not permitted.
  15818. This description includes both integer and floating-point numbers.
  15819. However, C++ allows more precise storage if it is known whether the number
  15820. is a signed integer, an unsigned integer or a floating-point number.
  15821. Therefore, three different types, @ref number_integer_t, @ref
  15822. number_unsigned_t and @ref number_float_t are used.
  15823. To store unsigned integer numbers in C++, a type is defined by the
  15824. template parameter @a NumberUnsignedType which chooses the type to use.
  15825. #### Default type
  15826. With the default values for @a NumberUnsignedType (`uint64_t`), the
  15827. default value for @a number_unsigned_t is:
  15828. @code {.cpp}
  15829. uint64_t
  15830. @endcode
  15831. #### Default behavior
  15832. - The restrictions about leading zeros is not enforced in C++. Instead,
  15833. leading zeros in integer literals lead to an interpretation as octal
  15834. number. Internally, the value will be stored as decimal number. For
  15835. instance, the C++ integer literal `010` will be serialized to `8`.
  15836. During deserialization, leading zeros yield an error.
  15837. - Not-a-number (NaN) values will be serialized to `null`.
  15838. #### Limits
  15839. [RFC 8259](https://tools.ietf.org/html/rfc8259) specifies:
  15840. > An implementation may set limits on the range and precision of numbers.
  15841. When the default type is used, the maximal integer number that can be
  15842. stored is `18446744073709551615` (UINT64_MAX) and the minimal integer
  15843. number that can be stored is `0`. Integer numbers that are out of range
  15844. will yield over/underflow when used in a constructor. During
  15845. deserialization, too large or small integer numbers will be automatically
  15846. be stored as @ref number_integer_t or @ref number_float_t.
  15847. [RFC 8259](https://tools.ietf.org/html/rfc8259) further states:
  15848. > Note that when such software is used, numbers that are integers and are
  15849. > in the range \f$[-2^{53}+1, 2^{53}-1]\f$ are interoperable in the sense
  15850. > that implementations will agree exactly on their numeric values.
  15851. As this range is a subrange (when considered in conjunction with the
  15852. number_integer_t type) of the exactly supported range [0, UINT64_MAX],
  15853. this class's integer type is interoperable.
  15854. #### Storage
  15855. Integer number values are stored directly inside a @ref basic_json type.
  15856. @sa see @ref number_float_t -- type for number values (floating-point)
  15857. @sa see @ref number_integer_t -- type for number values (integer)
  15858. @since version 2.0.0
  15859. */
  15860. using number_unsigned_t = NumberUnsignedType;
  15861. /*!
  15862. @brief a type for a number (floating-point)
  15863. [RFC 8259](https://tools.ietf.org/html/rfc8259) describes numbers as follows:
  15864. > The representation of numbers is similar to that used in most
  15865. > programming languages. A number is represented in base 10 using decimal
  15866. > digits. It contains an integer component that may be prefixed with an
  15867. > optional minus sign, which may be followed by a fraction part and/or an
  15868. > exponent part. Leading zeros are not allowed. (...) Numeric values that
  15869. > cannot be represented in the grammar below (such as Infinity and NaN)
  15870. > are not permitted.
  15871. This description includes both integer and floating-point numbers.
  15872. However, C++ allows more precise storage if it is known whether the number
  15873. is a signed integer, an unsigned integer or a floating-point number.
  15874. Therefore, three different types, @ref number_integer_t, @ref
  15875. number_unsigned_t and @ref number_float_t are used.
  15876. To store floating-point numbers in C++, a type is defined by the template
  15877. parameter @a NumberFloatType which chooses the type to use.
  15878. #### Default type
  15879. With the default values for @a NumberFloatType (`double`), the default
  15880. value for @a number_float_t is:
  15881. @code {.cpp}
  15882. double
  15883. @endcode
  15884. #### Default behavior
  15885. - The restrictions about leading zeros is not enforced in C++. Instead,
  15886. leading zeros in floating-point literals will be ignored. Internally,
  15887. the value will be stored as decimal number. For instance, the C++
  15888. floating-point literal `01.2` will be serialized to `1.2`. During
  15889. deserialization, leading zeros yield an error.
  15890. - Not-a-number (NaN) values will be serialized to `null`.
  15891. #### Limits
  15892. [RFC 8259](https://tools.ietf.org/html/rfc8259) states:
  15893. > This specification allows implementations to set limits on the range and
  15894. > precision of numbers accepted. Since software that implements IEEE
  15895. > 754-2008 binary64 (double precision) numbers is generally available and
  15896. > widely used, good interoperability can be achieved by implementations
  15897. > that expect no more precision or range than these provide, in the sense
  15898. > that implementations will approximate JSON numbers within the expected
  15899. > precision.
  15900. This implementation does exactly follow this approach, as it uses double
  15901. precision floating-point numbers. Note values smaller than
  15902. `-1.79769313486232e+308` and values greater than `1.79769313486232e+308`
  15903. will be stored as NaN internally and be serialized to `null`.
  15904. #### Storage
  15905. Floating-point number values are stored directly inside a @ref basic_json
  15906. type.
  15907. @sa see @ref number_integer_t -- type for number values (integer)
  15908. @sa see @ref number_unsigned_t -- type for number values (unsigned integer)
  15909. @since version 1.0.0
  15910. */
  15911. using number_float_t = NumberFloatType;
  15912. /*!
  15913. @brief a type for a packed binary type
  15914. This type is a type designed to carry binary data that appears in various
  15915. serialized formats, such as CBOR's Major Type 2, MessagePack's bin, and
  15916. BSON's generic binary subtype. This type is NOT a part of standard JSON and
  15917. exists solely for compatibility with these binary types. As such, it is
  15918. simply defined as an ordered sequence of zero or more byte values.
  15919. Additionally, as an implementation detail, the subtype of the binary data is
  15920. carried around as a `std::uint8_t`, which is compatible with both of the
  15921. binary data formats that use binary subtyping, (though the specific
  15922. numbering is incompatible with each other, and it is up to the user to
  15923. translate between them).
  15924. [CBOR's RFC 7049](https://tools.ietf.org/html/rfc7049) describes this type
  15925. as:
  15926. > Major type 2: a byte string. The string's length in bytes is represented
  15927. > following the rules for positive integers (major type 0).
  15928. [MessagePack's documentation on the bin type
  15929. family](https://github.com/msgpack/msgpack/blob/master/spec.md#bin-format-family)
  15930. describes this type as:
  15931. > Bin format family stores an byte array in 2, 3, or 5 bytes of extra bytes
  15932. > in addition to the size of the byte array.
  15933. [BSON's specifications](http://bsonspec.org/spec.html) describe several
  15934. binary types; however, this type is intended to represent the generic binary
  15935. type which has the description:
  15936. > Generic binary subtype - This is the most commonly used binary subtype and
  15937. > should be the 'default' for drivers and tools.
  15938. None of these impose any limitations on the internal representation other
  15939. than the basic unit of storage be some type of array whose parts are
  15940. decomposable into bytes.
  15941. The default representation of this binary format is a
  15942. `std::vector<std::uint8_t>`, which is a very common way to represent a byte
  15943. array in modern C++.
  15944. #### Default type
  15945. The default values for @a BinaryType is `std::vector<std::uint8_t>`
  15946. #### Storage
  15947. Binary Arrays are stored as pointers in a @ref basic_json type. That is,
  15948. for any access to array values, a pointer of the type `binary_t*` must be
  15949. dereferenced.
  15950. #### Notes on subtypes
  15951. - CBOR
  15952. - Binary values are represented as byte strings. Subtypes are serialized
  15953. as tagged values.
  15954. - MessagePack
  15955. - If a subtype is given and the binary array contains exactly 1, 2, 4, 8,
  15956. or 16 elements, the fixext family (fixext1, fixext2, fixext4, fixext8)
  15957. is used. For other sizes, the ext family (ext8, ext16, ext32) is used.
  15958. The subtype is then added as singed 8-bit integer.
  15959. - If no subtype is given, the bin family (bin8, bin16, bin32) is used.
  15960. - BSON
  15961. - If a subtype is given, it is used and added as unsigned 8-bit integer.
  15962. - If no subtype is given, the generic binary subtype 0x00 is used.
  15963. @sa see @ref binary -- create a binary array
  15964. @since version 3.8.0
  15965. */
  15966. using binary_t = nlohmann::byte_container_with_subtype<BinaryType>;
  15967. /// @}
  15968. private:
  15969. /// helper for exception-safe object creation
  15970. template<typename T, typename... Args>
  15971. JSON_HEDLEY_RETURNS_NON_NULL
  15972. static T* create(Args&& ... args)
  15973. {
  15974. AllocatorType<T> alloc;
  15975. using AllocatorTraits = std::allocator_traits<AllocatorType<T>>;
  15976. auto deleter = [&](T * obj)
  15977. {
  15978. AllocatorTraits::deallocate(alloc, obj, 1);
  15979. };
  15980. std::unique_ptr<T, decltype(deleter)> obj(AllocatorTraits::allocate(alloc, 1), deleter);
  15981. AllocatorTraits::construct(alloc, obj.get(), std::forward<Args>(args)...);
  15982. JSON_ASSERT(obj != nullptr);
  15983. return obj.release();
  15984. }
  15985. ////////////////////////
  15986. // JSON value storage //
  15987. ////////////////////////
  15988. JSON_PRIVATE_UNLESS_TESTED:
  15989. /*!
  15990. @brief a JSON value
  15991. The actual storage for a JSON value of the @ref basic_json class. This
  15992. union combines the different storage types for the JSON value types
  15993. defined in @ref value_t.
  15994. JSON type | value_t type | used type
  15995. --------- | --------------- | ------------------------
  15996. object | object | pointer to @ref object_t
  15997. array | array | pointer to @ref array_t
  15998. string | string | pointer to @ref string_t
  15999. boolean | boolean | @ref boolean_t
  16000. number | number_integer | @ref number_integer_t
  16001. number | number_unsigned | @ref number_unsigned_t
  16002. number | number_float | @ref number_float_t
  16003. binary | binary | pointer to @ref binary_t
  16004. null | null | *no value is stored*
  16005. @note Variable-length types (objects, arrays, and strings) are stored as
  16006. pointers. The size of the union should not exceed 64 bits if the default
  16007. value types are used.
  16008. @since version 1.0.0
  16009. */
  16010. union json_value
  16011. {
  16012. /// object (stored with pointer to save storage)
  16013. object_t* object;
  16014. /// array (stored with pointer to save storage)
  16015. array_t* array;
  16016. /// string (stored with pointer to save storage)
  16017. string_t* string;
  16018. /// binary (stored with pointer to save storage)
  16019. binary_t* binary;
  16020. /// boolean
  16021. boolean_t boolean;
  16022. /// number (integer)
  16023. number_integer_t number_integer;
  16024. /// number (unsigned integer)
  16025. number_unsigned_t number_unsigned;
  16026. /// number (floating-point)
  16027. number_float_t number_float;
  16028. /// default constructor (for null values)
  16029. json_value() = default;
  16030. /// constructor for booleans
  16031. json_value(boolean_t v) noexcept : boolean(v) {}
  16032. /// constructor for numbers (integer)
  16033. json_value(number_integer_t v) noexcept : number_integer(v) {}
  16034. /// constructor for numbers (unsigned)
  16035. json_value(number_unsigned_t v) noexcept : number_unsigned(v) {}
  16036. /// constructor for numbers (floating-point)
  16037. json_value(number_float_t v) noexcept : number_float(v) {}
  16038. /// constructor for empty values of a given type
  16039. json_value(value_t t)
  16040. {
  16041. switch (t)
  16042. {
  16043. case value_t::object:
  16044. {
  16045. object = create<object_t>();
  16046. break;
  16047. }
  16048. case value_t::array:
  16049. {
  16050. array = create<array_t>();
  16051. break;
  16052. }
  16053. case value_t::string:
  16054. {
  16055. string = create<string_t>("");
  16056. break;
  16057. }
  16058. case value_t::binary:
  16059. {
  16060. binary = create<binary_t>();
  16061. break;
  16062. }
  16063. case value_t::boolean:
  16064. {
  16065. boolean = boolean_t(false);
  16066. break;
  16067. }
  16068. case value_t::number_integer:
  16069. {
  16070. number_integer = number_integer_t(0);
  16071. break;
  16072. }
  16073. case value_t::number_unsigned:
  16074. {
  16075. number_unsigned = number_unsigned_t(0);
  16076. break;
  16077. }
  16078. case value_t::number_float:
  16079. {
  16080. number_float = number_float_t(0.0);
  16081. break;
  16082. }
  16083. case value_t::null:
  16084. {
  16085. object = nullptr; // silence warning, see #821
  16086. break;
  16087. }
  16088. case value_t::discarded:
  16089. default:
  16090. {
  16091. object = nullptr; // silence warning, see #821
  16092. if (JSON_HEDLEY_UNLIKELY(t == value_t::null))
  16093. {
  16094. JSON_THROW(other_error::create(500, "961c151d2e87f2686a955a9be24d316f1362bf21 3.10.4", basic_json())); // LCOV_EXCL_LINE
  16095. }
  16096. break;
  16097. }
  16098. }
  16099. }
  16100. /// constructor for strings
  16101. json_value(const string_t& value)
  16102. {
  16103. string = create<string_t>(value);
  16104. }
  16105. /// constructor for rvalue strings
  16106. json_value(string_t&& value)
  16107. {
  16108. string = create<string_t>(std::move(value));
  16109. }
  16110. /// constructor for objects
  16111. json_value(const object_t& value)
  16112. {
  16113. object = create<object_t>(value);
  16114. }
  16115. /// constructor for rvalue objects
  16116. json_value(object_t&& value)
  16117. {
  16118. object = create<object_t>(std::move(value));
  16119. }
  16120. /// constructor for arrays
  16121. json_value(const array_t& value)
  16122. {
  16123. array = create<array_t>(value);
  16124. }
  16125. /// constructor for rvalue arrays
  16126. json_value(array_t&& value)
  16127. {
  16128. array = create<array_t>(std::move(value));
  16129. }
  16130. /// constructor for binary arrays
  16131. json_value(const typename binary_t::container_type& value)
  16132. {
  16133. binary = create<binary_t>(value);
  16134. }
  16135. /// constructor for rvalue binary arrays
  16136. json_value(typename binary_t::container_type&& value)
  16137. {
  16138. binary = create<binary_t>(std::move(value));
  16139. }
  16140. /// constructor for binary arrays (internal type)
  16141. json_value(const binary_t& value)
  16142. {
  16143. binary = create<binary_t>(value);
  16144. }
  16145. /// constructor for rvalue binary arrays (internal type)
  16146. json_value(binary_t&& value)
  16147. {
  16148. binary = create<binary_t>(std::move(value));
  16149. }
  16150. void destroy(value_t t)
  16151. {
  16152. if (t == value_t::array || t == value_t::object)
  16153. {
  16154. // flatten the current json_value to a heap-allocated stack
  16155. std::vector<basic_json> stack;
  16156. // move the top-level items to stack
  16157. if (t == value_t::array)
  16158. {
  16159. stack.reserve(array->size());
  16160. std::move(array->begin(), array->end(), std::back_inserter(stack));
  16161. }
  16162. else
  16163. {
  16164. stack.reserve(object->size());
  16165. for (auto&& it : *object)
  16166. {
  16167. stack.push_back(std::move(it.second));
  16168. }
  16169. }
  16170. while (!stack.empty())
  16171. {
  16172. // move the last item to local variable to be processed
  16173. basic_json current_item(std::move(stack.back()));
  16174. stack.pop_back();
  16175. // if current_item is array/object, move
  16176. // its children to the stack to be processed later
  16177. if (current_item.is_array())
  16178. {
  16179. std::move(current_item.m_value.array->begin(), current_item.m_value.array->end(), std::back_inserter(stack));
  16180. current_item.m_value.array->clear();
  16181. }
  16182. else if (current_item.is_object())
  16183. {
  16184. for (auto&& it : *current_item.m_value.object)
  16185. {
  16186. stack.push_back(std::move(it.second));
  16187. }
  16188. current_item.m_value.object->clear();
  16189. }
  16190. // it's now safe that current_item get destructed
  16191. // since it doesn't have any children
  16192. }
  16193. }
  16194. switch (t)
  16195. {
  16196. case value_t::object:
  16197. {
  16198. AllocatorType<object_t> alloc;
  16199. std::allocator_traits<decltype(alloc)>::destroy(alloc, object);
  16200. std::allocator_traits<decltype(alloc)>::deallocate(alloc, object, 1);
  16201. break;
  16202. }
  16203. case value_t::array:
  16204. {
  16205. AllocatorType<array_t> alloc;
  16206. std::allocator_traits<decltype(alloc)>::destroy(alloc, array);
  16207. std::allocator_traits<decltype(alloc)>::deallocate(alloc, array, 1);
  16208. break;
  16209. }
  16210. case value_t::string:
  16211. {
  16212. AllocatorType<string_t> alloc;
  16213. std::allocator_traits<decltype(alloc)>::destroy(alloc, string);
  16214. std::allocator_traits<decltype(alloc)>::deallocate(alloc, string, 1);
  16215. break;
  16216. }
  16217. case value_t::binary:
  16218. {
  16219. AllocatorType<binary_t> alloc;
  16220. std::allocator_traits<decltype(alloc)>::destroy(alloc, binary);
  16221. std::allocator_traits<decltype(alloc)>::deallocate(alloc, binary, 1);
  16222. break;
  16223. }
  16224. case value_t::null:
  16225. case value_t::boolean:
  16226. case value_t::number_integer:
  16227. case value_t::number_unsigned:
  16228. case value_t::number_float:
  16229. case value_t::discarded:
  16230. default:
  16231. {
  16232. break;
  16233. }
  16234. }
  16235. }
  16236. };
  16237. private:
  16238. /*!
  16239. @brief checks the class invariants
  16240. This function asserts the class invariants. It needs to be called at the
  16241. end of every constructor to make sure that created objects respect the
  16242. invariant. Furthermore, it has to be called each time the type of a JSON
  16243. value is changed, because the invariant expresses a relationship between
  16244. @a m_type and @a m_value.
  16245. Furthermore, the parent relation is checked for arrays and objects: If
  16246. @a check_parents true and the value is an array or object, then the
  16247. container's elements must have the current value as parent.
  16248. @param[in] check_parents whether the parent relation should be checked.
  16249. The value is true by default and should only be set to false
  16250. during destruction of objects when the invariant does not
  16251. need to hold.
  16252. */
  16253. void assert_invariant(bool check_parents = true) const noexcept
  16254. {
  16255. JSON_ASSERT(m_type != value_t::object || m_value.object != nullptr);
  16256. JSON_ASSERT(m_type != value_t::array || m_value.array != nullptr);
  16257. JSON_ASSERT(m_type != value_t::string || m_value.string != nullptr);
  16258. JSON_ASSERT(m_type != value_t::binary || m_value.binary != nullptr);
  16259. #if JSON_DIAGNOSTICS
  16260. JSON_TRY
  16261. {
  16262. // cppcheck-suppress assertWithSideEffect
  16263. JSON_ASSERT(!check_parents || !is_structured() || std::all_of(begin(), end(), [this](const basic_json & j)
  16264. {
  16265. return j.m_parent == this;
  16266. }));
  16267. }
  16268. JSON_CATCH(...) {} // LCOV_EXCL_LINE
  16269. #endif
  16270. static_cast<void>(check_parents);
  16271. }
  16272. void set_parents()
  16273. {
  16274. #if JSON_DIAGNOSTICS
  16275. switch (m_type)
  16276. {
  16277. case value_t::array:
  16278. {
  16279. for (auto& element : *m_value.array)
  16280. {
  16281. element.m_parent = this;
  16282. }
  16283. break;
  16284. }
  16285. case value_t::object:
  16286. {
  16287. for (auto& element : *m_value.object)
  16288. {
  16289. element.second.m_parent = this;
  16290. }
  16291. break;
  16292. }
  16293. case value_t::null:
  16294. case value_t::string:
  16295. case value_t::boolean:
  16296. case value_t::number_integer:
  16297. case value_t::number_unsigned:
  16298. case value_t::number_float:
  16299. case value_t::binary:
  16300. case value_t::discarded:
  16301. default:
  16302. break;
  16303. }
  16304. #endif
  16305. }
  16306. iterator set_parents(iterator it, typename iterator::difference_type count)
  16307. {
  16308. #if JSON_DIAGNOSTICS
  16309. for (typename iterator::difference_type i = 0; i < count; ++i)
  16310. {
  16311. (it + i)->m_parent = this;
  16312. }
  16313. #else
  16314. static_cast<void>(count);
  16315. #endif
  16316. return it;
  16317. }
  16318. reference set_parent(reference j, std::size_t old_capacity = std::size_t(-1))
  16319. {
  16320. #if JSON_DIAGNOSTICS
  16321. if (old_capacity != std::size_t(-1))
  16322. {
  16323. // see https://github.com/nlohmann/json/issues/2838
  16324. JSON_ASSERT(type() == value_t::array);
  16325. if (JSON_HEDLEY_UNLIKELY(m_value.array->capacity() != old_capacity))
  16326. {
  16327. // capacity has changed: update all parents
  16328. set_parents();
  16329. return j;
  16330. }
  16331. }
  16332. // ordered_json uses a vector internally, so pointers could have
  16333. // been invalidated; see https://github.com/nlohmann/json/issues/2962
  16334. #ifdef JSON_HEDLEY_MSVC_VERSION
  16335. #pragma warning(push )
  16336. #pragma warning(disable : 4127) // ignore warning to replace if with if constexpr
  16337. #endif
  16338. if (detail::is_ordered_map<object_t>::value)
  16339. {
  16340. set_parents();
  16341. return j;
  16342. }
  16343. #ifdef JSON_HEDLEY_MSVC_VERSION
  16344. #pragma warning( pop )
  16345. #endif
  16346. j.m_parent = this;
  16347. #else
  16348. static_cast<void>(j);
  16349. static_cast<void>(old_capacity);
  16350. #endif
  16351. return j;
  16352. }
  16353. public:
  16354. //////////////////////////
  16355. // JSON parser callback //
  16356. //////////////////////////
  16357. /*!
  16358. @brief parser event types
  16359. The parser callback distinguishes the following events:
  16360. - `object_start`: the parser read `{` and started to process a JSON object
  16361. - `key`: the parser read a key of a value in an object
  16362. - `object_end`: the parser read `}` and finished processing a JSON object
  16363. - `array_start`: the parser read `[` and started to process a JSON array
  16364. - `array_end`: the parser read `]` and finished processing a JSON array
  16365. - `value`: the parser finished reading a JSON value
  16366. @image html callback_events.png "Example when certain parse events are triggered"
  16367. @sa see @ref parser_callback_t for more information and examples
  16368. */
  16369. using parse_event_t = detail::parse_event_t;
  16370. /*!
  16371. @brief per-element parser callback type
  16372. With a parser callback function, the result of parsing a JSON text can be
  16373. influenced. When passed to @ref parse, it is called on certain events
  16374. (passed as @ref parse_event_t via parameter @a event) with a set recursion
  16375. depth @a depth and context JSON value @a parsed. The return value of the
  16376. callback function is a boolean indicating whether the element that emitted
  16377. the callback shall be kept or not.
  16378. We distinguish six scenarios (determined by the event type) in which the
  16379. callback function can be called. The following table describes the values
  16380. of the parameters @a depth, @a event, and @a parsed.
  16381. parameter @a event | description | parameter @a depth | parameter @a parsed
  16382. ------------------ | ----------- | ------------------ | -------------------
  16383. 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
  16384. 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
  16385. 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
  16386. 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
  16387. 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
  16388. parse_event_t::value | the parser finished reading a JSON value | depth of the value | the parsed JSON value
  16389. @image html callback_events.png "Example when certain parse events are triggered"
  16390. Discarding a value (i.e., returning `false`) has different effects
  16391. depending on the context in which function was called:
  16392. - Discarded values in structured types are skipped. That is, the parser
  16393. will behave as if the discarded value was never read.
  16394. - In case a value outside a structured type is skipped, it is replaced
  16395. with `null`. This case happens if the top-level element is skipped.
  16396. @param[in] depth the depth of the recursion during parsing
  16397. @param[in] event an event of type parse_event_t indicating the context in
  16398. the callback function has been called
  16399. @param[in,out] parsed the current intermediate parse result; note that
  16400. writing to this value has no effect for parse_event_t::key events
  16401. @return Whether the JSON value which called the function during parsing
  16402. should be kept (`true`) or not (`false`). In the latter case, it is either
  16403. skipped completely or replaced by an empty discarded object.
  16404. @sa see @ref parse for examples
  16405. @since version 1.0.0
  16406. */
  16407. using parser_callback_t = detail::parser_callback_t<basic_json>;
  16408. //////////////////
  16409. // constructors //
  16410. //////////////////
  16411. /// @name constructors and destructors
  16412. /// Constructors of class @ref basic_json, copy/move constructor, copy
  16413. /// assignment, static functions creating objects, and the destructor.
  16414. /// @{
  16415. /*!
  16416. @brief create an empty value with a given type
  16417. Create an empty JSON value with a given type. The value will be default
  16418. initialized with an empty value which depends on the type:
  16419. Value type | initial value
  16420. ----------- | -------------
  16421. null | `null`
  16422. boolean | `false`
  16423. string | `""`
  16424. number | `0`
  16425. object | `{}`
  16426. array | `[]`
  16427. binary | empty array
  16428. @param[in] v the type of the value to create
  16429. @complexity Constant.
  16430. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  16431. changes to any JSON value.
  16432. @liveexample{The following code shows the constructor for different @ref
  16433. value_t values,basic_json__value_t}
  16434. @sa see @ref clear() -- restores the postcondition of this constructor
  16435. @since version 1.0.0
  16436. */
  16437. basic_json(const value_t v)
  16438. : m_type(v), m_value(v)
  16439. {
  16440. assert_invariant();
  16441. }
  16442. /*!
  16443. @brief create a null object
  16444. Create a `null` JSON value. It either takes a null pointer as parameter
  16445. (explicitly creating `null`) or no parameter (implicitly creating `null`).
  16446. The passed null pointer itself is not read -- it is only used to choose
  16447. the right constructor.
  16448. @complexity Constant.
  16449. @exceptionsafety No-throw guarantee: this constructor never throws
  16450. exceptions.
  16451. @liveexample{The following code shows the constructor with and without a
  16452. null pointer parameter.,basic_json__nullptr_t}
  16453. @since version 1.0.0
  16454. */
  16455. basic_json(std::nullptr_t = nullptr) noexcept
  16456. : basic_json(value_t::null)
  16457. {
  16458. assert_invariant();
  16459. }
  16460. /*!
  16461. @brief create a JSON value
  16462. This is a "catch all" constructor for all compatible JSON types; that is,
  16463. types for which a `to_json()` method exists. The constructor forwards the
  16464. parameter @a val to that method (to `json_serializer<U>::to_json` method
  16465. with `U = uncvref_t<CompatibleType>`, to be exact).
  16466. Template type @a CompatibleType includes, but is not limited to, the
  16467. following types:
  16468. - **arrays**: @ref array_t and all kinds of compatible containers such as
  16469. `std::vector`, `std::deque`, `std::list`, `std::forward_list`,
  16470. `std::array`, `std::valarray`, `std::set`, `std::unordered_set`,
  16471. `std::multiset`, and `std::unordered_multiset` with a `value_type` from
  16472. which a @ref basic_json value can be constructed.
  16473. - **objects**: @ref object_t and all kinds of compatible associative
  16474. containers such as `std::map`, `std::unordered_map`, `std::multimap`,
  16475. and `std::unordered_multimap` with a `key_type` compatible to
  16476. @ref string_t and a `value_type` from which a @ref basic_json value can
  16477. be constructed.
  16478. - **strings**: @ref string_t, string literals, and all compatible string
  16479. containers can be used.
  16480. - **numbers**: @ref number_integer_t, @ref number_unsigned_t,
  16481. @ref number_float_t, and all convertible number types such as `int`,
  16482. `size_t`, `int64_t`, `float` or `double` can be used.
  16483. - **boolean**: @ref boolean_t / `bool` can be used.
  16484. - **binary**: @ref binary_t / `std::vector<std::uint8_t>` may be used,
  16485. unfortunately because string literals cannot be distinguished from binary
  16486. character arrays by the C++ type system, all types compatible with `const
  16487. char*` will be directed to the string constructor instead. This is both
  16488. for backwards compatibility, and due to the fact that a binary type is not
  16489. a standard JSON type.
  16490. See the examples below.
  16491. @tparam CompatibleType a type such that:
  16492. - @a CompatibleType is not derived from `std::istream`,
  16493. - @a CompatibleType is not @ref basic_json (to avoid hijacking copy/move
  16494. constructors),
  16495. - @a CompatibleType is not a different @ref basic_json type (i.e. with different template arguments)
  16496. - @a CompatibleType is not a @ref basic_json nested type (e.g.,
  16497. @ref json_pointer, @ref iterator, etc ...)
  16498. - `json_serializer<U>` has a `to_json(basic_json_t&, CompatibleType&&)` method
  16499. @tparam U = `uncvref_t<CompatibleType>`
  16500. @param[in] val the value to be forwarded to the respective constructor
  16501. @complexity Usually linear in the size of the passed @a val, also
  16502. depending on the implementation of the called `to_json()`
  16503. method.
  16504. @exceptionsafety Depends on the called constructor. For types directly
  16505. supported by the library (i.e., all types for which no `to_json()` function
  16506. was provided), strong guarantee holds: if an exception is thrown, there are
  16507. no changes to any JSON value.
  16508. @liveexample{The following code shows the constructor with several
  16509. compatible types.,basic_json__CompatibleType}
  16510. @since version 2.1.0
  16511. */
  16512. template < typename CompatibleType,
  16513. typename U = detail::uncvref_t<CompatibleType>,
  16514. detail::enable_if_t <
  16515. !detail::is_basic_json<U>::value && detail::is_compatible_type<basic_json_t, U>::value, int > = 0 >
  16516. basic_json(CompatibleType && val) noexcept(noexcept( // NOLINT(bugprone-forwarding-reference-overload,bugprone-exception-escape)
  16517. JSONSerializer<U>::to_json(std::declval<basic_json_t&>(),
  16518. std::forward<CompatibleType>(val))))
  16519. {
  16520. JSONSerializer<U>::to_json(*this, std::forward<CompatibleType>(val));
  16521. set_parents();
  16522. assert_invariant();
  16523. }
  16524. /*!
  16525. @brief create a JSON value from an existing one
  16526. This is a constructor for existing @ref basic_json types.
  16527. It does not hijack copy/move constructors, since the parameter has different
  16528. template arguments than the current ones.
  16529. The constructor tries to convert the internal @ref m_value of the parameter.
  16530. @tparam BasicJsonType a type such that:
  16531. - @a BasicJsonType is a @ref basic_json type.
  16532. - @a BasicJsonType has different template arguments than @ref basic_json_t.
  16533. @param[in] val the @ref basic_json value to be converted.
  16534. @complexity Usually linear in the size of the passed @a val, also
  16535. depending on the implementation of the called `to_json()`
  16536. method.
  16537. @exceptionsafety Depends on the called constructor. For types directly
  16538. supported by the library (i.e., all types for which no `to_json()` function
  16539. was provided), strong guarantee holds: if an exception is thrown, there are
  16540. no changes to any JSON value.
  16541. @since version 3.2.0
  16542. */
  16543. template < typename BasicJsonType,
  16544. detail::enable_if_t <
  16545. detail::is_basic_json<BasicJsonType>::value&& !std::is_same<basic_json, BasicJsonType>::value, int > = 0 >
  16546. basic_json(const BasicJsonType& val)
  16547. {
  16548. using other_boolean_t = typename BasicJsonType::boolean_t;
  16549. using other_number_float_t = typename BasicJsonType::number_float_t;
  16550. using other_number_integer_t = typename BasicJsonType::number_integer_t;
  16551. using other_number_unsigned_t = typename BasicJsonType::number_unsigned_t;
  16552. using other_string_t = typename BasicJsonType::string_t;
  16553. using other_object_t = typename BasicJsonType::object_t;
  16554. using other_array_t = typename BasicJsonType::array_t;
  16555. using other_binary_t = typename BasicJsonType::binary_t;
  16556. switch (val.type())
  16557. {
  16558. case value_t::boolean:
  16559. JSONSerializer<other_boolean_t>::to_json(*this, val.template get<other_boolean_t>());
  16560. break;
  16561. case value_t::number_float:
  16562. JSONSerializer<other_number_float_t>::to_json(*this, val.template get<other_number_float_t>());
  16563. break;
  16564. case value_t::number_integer:
  16565. JSONSerializer<other_number_integer_t>::to_json(*this, val.template get<other_number_integer_t>());
  16566. break;
  16567. case value_t::number_unsigned:
  16568. JSONSerializer<other_number_unsigned_t>::to_json(*this, val.template get<other_number_unsigned_t>());
  16569. break;
  16570. case value_t::string:
  16571. JSONSerializer<other_string_t>::to_json(*this, val.template get_ref<const other_string_t&>());
  16572. break;
  16573. case value_t::object:
  16574. JSONSerializer<other_object_t>::to_json(*this, val.template get_ref<const other_object_t&>());
  16575. break;
  16576. case value_t::array:
  16577. JSONSerializer<other_array_t>::to_json(*this, val.template get_ref<const other_array_t&>());
  16578. break;
  16579. case value_t::binary:
  16580. JSONSerializer<other_binary_t>::to_json(*this, val.template get_ref<const other_binary_t&>());
  16581. break;
  16582. case value_t::null:
  16583. *this = nullptr;
  16584. break;
  16585. case value_t::discarded:
  16586. m_type = value_t::discarded;
  16587. break;
  16588. default: // LCOV_EXCL_LINE
  16589. JSON_ASSERT(false); // NOLINT(cert-dcl03-c,hicpp-static-assert,misc-static-assert) LCOV_EXCL_LINE
  16590. }
  16591. set_parents();
  16592. assert_invariant();
  16593. }
  16594. /*!
  16595. @brief create a container (array or object) from an initializer list
  16596. Creates a JSON value of type array or object from the passed initializer
  16597. list @a init. In case @a type_deduction is `true` (default), the type of
  16598. the JSON value to be created is deducted from the initializer list @a init
  16599. according to the following rules:
  16600. 1. If the list is empty, an empty JSON object value `{}` is created.
  16601. 2. If the list consists of pairs whose first element is a string, a JSON
  16602. object value is created where the first elements of the pairs are
  16603. treated as keys and the second elements are as values.
  16604. 3. In all other cases, an array is created.
  16605. The rules aim to create the best fit between a C++ initializer list and
  16606. JSON values. The rationale is as follows:
  16607. 1. The empty initializer list is written as `{}` which is exactly an empty
  16608. JSON object.
  16609. 2. C++ has no way of describing mapped types other than to list a list of
  16610. pairs. As JSON requires that keys must be of type string, rule 2 is the
  16611. weakest constraint one can pose on initializer lists to interpret them
  16612. as an object.
  16613. 3. In all other cases, the initializer list could not be interpreted as
  16614. JSON object type, so interpreting it as JSON array type is safe.
  16615. With the rules described above, the following JSON values cannot be
  16616. expressed by an initializer list:
  16617. - the empty array (`[]`): use @ref array(initializer_list_t)
  16618. with an empty initializer list in this case
  16619. - arrays whose elements satisfy rule 2: use @ref
  16620. array(initializer_list_t) with the same initializer list
  16621. in this case
  16622. @note When used without parentheses around an empty initializer list, @ref
  16623. basic_json() is called instead of this function, yielding the JSON null
  16624. value.
  16625. @param[in] init initializer list with JSON values
  16626. @param[in] type_deduction internal parameter; when set to `true`, the type
  16627. of the JSON value is deducted from the initializer list @a init; when set
  16628. to `false`, the type provided via @a manual_type is forced. This mode is
  16629. used by the functions @ref array(initializer_list_t) and
  16630. @ref object(initializer_list_t).
  16631. @param[in] manual_type internal parameter; when @a type_deduction is set
  16632. to `false`, the created JSON value will use the provided type (only @ref
  16633. value_t::array and @ref value_t::object are valid); when @a type_deduction
  16634. is set to `true`, this parameter has no effect
  16635. @throw type_error.301 if @a type_deduction is `false`, @a manual_type is
  16636. `value_t::object`, but @a init contains an element which is not a pair
  16637. whose first element is a string. In this case, the constructor could not
  16638. create an object. If @a type_deduction would have be `true`, an array
  16639. would have been created. See @ref object(initializer_list_t)
  16640. for an example.
  16641. @complexity Linear in the size of the initializer list @a init.
  16642. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  16643. changes to any JSON value.
  16644. @liveexample{The example below shows how JSON values are created from
  16645. initializer lists.,basic_json__list_init_t}
  16646. @sa see @ref array(initializer_list_t) -- create a JSON array
  16647. value from an initializer list
  16648. @sa see @ref object(initializer_list_t) -- create a JSON object
  16649. value from an initializer list
  16650. @since version 1.0.0
  16651. */
  16652. basic_json(initializer_list_t init,
  16653. bool type_deduction = true,
  16654. value_t manual_type = value_t::array)
  16655. {
  16656. // check if each element is an array with two elements whose first
  16657. // element is a string
  16658. bool is_an_object = std::all_of(init.begin(), init.end(),
  16659. [](const detail::json_ref<basic_json>& element_ref)
  16660. {
  16661. return element_ref->is_array() && element_ref->size() == 2 && (*element_ref)[0].is_string();
  16662. });
  16663. // adjust type if type deduction is not wanted
  16664. if (!type_deduction)
  16665. {
  16666. // if array is wanted, do not create an object though possible
  16667. if (manual_type == value_t::array)
  16668. {
  16669. is_an_object = false;
  16670. }
  16671. // if object is wanted but impossible, throw an exception
  16672. if (JSON_HEDLEY_UNLIKELY(manual_type == value_t::object && !is_an_object))
  16673. {
  16674. JSON_THROW(type_error::create(301, "cannot create object from initializer list", basic_json()));
  16675. }
  16676. }
  16677. if (is_an_object)
  16678. {
  16679. // the initializer list is a list of pairs -> create object
  16680. m_type = value_t::object;
  16681. m_value = value_t::object;
  16682. for (auto& element_ref : init)
  16683. {
  16684. auto element = element_ref.moved_or_copied();
  16685. m_value.object->emplace(
  16686. std::move(*((*element.m_value.array)[0].m_value.string)),
  16687. std::move((*element.m_value.array)[1]));
  16688. }
  16689. }
  16690. else
  16691. {
  16692. // the initializer list describes an array -> create array
  16693. m_type = value_t::array;
  16694. m_value.array = create<array_t>(init.begin(), init.end());
  16695. }
  16696. set_parents();
  16697. assert_invariant();
  16698. }
  16699. /*!
  16700. @brief explicitly create a binary array (without subtype)
  16701. Creates a JSON binary array value from a given binary container. Binary
  16702. values are part of various binary formats, such as CBOR, MessagePack, and
  16703. BSON. This constructor is used to create a value for serialization to those
  16704. formats.
  16705. @note Note, this function exists because of the difficulty in correctly
  16706. specifying the correct template overload in the standard value ctor, as both
  16707. JSON arrays and JSON binary arrays are backed with some form of a
  16708. `std::vector`. Because JSON binary arrays are a non-standard extension it
  16709. was decided that it would be best to prevent automatic initialization of a
  16710. binary array type, for backwards compatibility and so it does not happen on
  16711. accident.
  16712. @param[in] init container containing bytes to use as binary type
  16713. @return JSON binary array value
  16714. @complexity Linear in the size of @a init.
  16715. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  16716. changes to any JSON value.
  16717. @since version 3.8.0
  16718. */
  16719. JSON_HEDLEY_WARN_UNUSED_RESULT
  16720. static basic_json binary(const typename binary_t::container_type& init)
  16721. {
  16722. auto res = basic_json();
  16723. res.m_type = value_t::binary;
  16724. res.m_value = init;
  16725. return res;
  16726. }
  16727. /*!
  16728. @brief explicitly create a binary array (with subtype)
  16729. Creates a JSON binary array value from a given binary container. Binary
  16730. values are part of various binary formats, such as CBOR, MessagePack, and
  16731. BSON. This constructor is used to create a value for serialization to those
  16732. formats.
  16733. @note Note, this function exists because of the difficulty in correctly
  16734. specifying the correct template overload in the standard value ctor, as both
  16735. JSON arrays and JSON binary arrays are backed with some form of a
  16736. `std::vector`. Because JSON binary arrays are a non-standard extension it
  16737. was decided that it would be best to prevent automatic initialization of a
  16738. binary array type, for backwards compatibility and so it does not happen on
  16739. accident.
  16740. @param[in] init container containing bytes to use as binary type
  16741. @param[in] subtype subtype to use in MessagePack and BSON
  16742. @return JSON binary array value
  16743. @complexity Linear in the size of @a init.
  16744. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  16745. changes to any JSON value.
  16746. @since version 3.8.0
  16747. */
  16748. JSON_HEDLEY_WARN_UNUSED_RESULT
  16749. static basic_json binary(const typename binary_t::container_type& init, typename binary_t::subtype_type subtype)
  16750. {
  16751. auto res = basic_json();
  16752. res.m_type = value_t::binary;
  16753. res.m_value = binary_t(init, subtype);
  16754. return res;
  16755. }
  16756. /// @copydoc binary(const typename binary_t::container_type&)
  16757. JSON_HEDLEY_WARN_UNUSED_RESULT
  16758. static basic_json binary(typename binary_t::container_type&& init)
  16759. {
  16760. auto res = basic_json();
  16761. res.m_type = value_t::binary;
  16762. res.m_value = std::move(init);
  16763. return res;
  16764. }
  16765. /// @copydoc binary(const typename binary_t::container_type&, typename binary_t::subtype_type)
  16766. JSON_HEDLEY_WARN_UNUSED_RESULT
  16767. static basic_json binary(typename binary_t::container_type&& init, typename binary_t::subtype_type subtype)
  16768. {
  16769. auto res = basic_json();
  16770. res.m_type = value_t::binary;
  16771. res.m_value = binary_t(std::move(init), subtype);
  16772. return res;
  16773. }
  16774. /*!
  16775. @brief explicitly create an array from an initializer list
  16776. Creates a JSON array value from a given initializer list. That is, given a
  16777. list of values `a, b, c`, creates the JSON value `[a, b, c]`. If the
  16778. initializer list is empty, the empty array `[]` is created.
  16779. @note This function is only needed to express two edge cases that cannot
  16780. be realized with the initializer list constructor (@ref
  16781. basic_json(initializer_list_t, bool, value_t)). These cases
  16782. are:
  16783. 1. creating an array whose elements are all pairs whose first element is a
  16784. string -- in this case, the initializer list constructor would create an
  16785. object, taking the first elements as keys
  16786. 2. creating an empty array -- passing the empty initializer list to the
  16787. initializer list constructor yields an empty object
  16788. @param[in] init initializer list with JSON values to create an array from
  16789. (optional)
  16790. @return JSON array value
  16791. @complexity Linear in the size of @a init.
  16792. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  16793. changes to any JSON value.
  16794. @liveexample{The following code shows an example for the `array`
  16795. function.,array}
  16796. @sa see @ref basic_json(initializer_list_t, bool, value_t) --
  16797. create a JSON value from an initializer list
  16798. @sa see @ref object(initializer_list_t) -- create a JSON object
  16799. value from an initializer list
  16800. @since version 1.0.0
  16801. */
  16802. JSON_HEDLEY_WARN_UNUSED_RESULT
  16803. static basic_json array(initializer_list_t init = {})
  16804. {
  16805. return basic_json(init, false, value_t::array);
  16806. }
  16807. /*!
  16808. @brief explicitly create an object from an initializer list
  16809. Creates a JSON object value from a given initializer list. The initializer
  16810. lists elements must be pairs, and their first elements must be strings. If
  16811. the initializer list is empty, the empty object `{}` is created.
  16812. @note This function is only added for symmetry reasons. In contrast to the
  16813. related function @ref array(initializer_list_t), there are
  16814. no cases which can only be expressed by this function. That is, any
  16815. initializer list @a init can also be passed to the initializer list
  16816. constructor @ref basic_json(initializer_list_t, bool, value_t).
  16817. @param[in] init initializer list to create an object from (optional)
  16818. @return JSON object value
  16819. @throw type_error.301 if @a init is not a list of pairs whose first
  16820. elements are strings. In this case, no object can be created. When such a
  16821. value is passed to @ref basic_json(initializer_list_t, bool, value_t),
  16822. an array would have been created from the passed initializer list @a init.
  16823. See example below.
  16824. @complexity Linear in the size of @a init.
  16825. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  16826. changes to any JSON value.
  16827. @liveexample{The following code shows an example for the `object`
  16828. function.,object}
  16829. @sa see @ref basic_json(initializer_list_t, bool, value_t) --
  16830. create a JSON value from an initializer list
  16831. @sa see @ref array(initializer_list_t) -- create a JSON array
  16832. value from an initializer list
  16833. @since version 1.0.0
  16834. */
  16835. JSON_HEDLEY_WARN_UNUSED_RESULT
  16836. static basic_json object(initializer_list_t init = {})
  16837. {
  16838. return basic_json(init, false, value_t::object);
  16839. }
  16840. /*!
  16841. @brief construct an array with count copies of given value
  16842. Constructs a JSON array value by creating @a cnt copies of a passed value.
  16843. In case @a cnt is `0`, an empty array is created.
  16844. @param[in] cnt the number of JSON copies of @a val to create
  16845. @param[in] val the JSON value to copy
  16846. @post `std::distance(begin(),end()) == cnt` holds.
  16847. @complexity Linear in @a cnt.
  16848. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  16849. changes to any JSON value.
  16850. @liveexample{The following code shows examples for the @ref
  16851. basic_json(size_type\, const basic_json&)
  16852. constructor.,basic_json__size_type_basic_json}
  16853. @since version 1.0.0
  16854. */
  16855. basic_json(size_type cnt, const basic_json& val)
  16856. : m_type(value_t::array)
  16857. {
  16858. m_value.array = create<array_t>(cnt, val);
  16859. set_parents();
  16860. assert_invariant();
  16861. }
  16862. /*!
  16863. @brief construct a JSON container given an iterator range
  16864. Constructs the JSON value with the contents of the range `[first, last)`.
  16865. The semantics depends on the different types a JSON value can have:
  16866. - In case of a null type, invalid_iterator.206 is thrown.
  16867. - In case of other primitive types (number, boolean, or string), @a first
  16868. must be `begin()` and @a last must be `end()`. In this case, the value is
  16869. copied. Otherwise, invalid_iterator.204 is thrown.
  16870. - In case of structured types (array, object), the constructor behaves as
  16871. similar versions for `std::vector` or `std::map`; that is, a JSON array
  16872. or object is constructed from the values in the range.
  16873. @tparam InputIT an input iterator type (@ref iterator or @ref
  16874. const_iterator)
  16875. @param[in] first begin of the range to copy from (included)
  16876. @param[in] last end of the range to copy from (excluded)
  16877. @pre Iterators @a first and @a last must be initialized. **This
  16878. precondition is enforced with an assertion (see warning).** If
  16879. assertions are switched off, a violation of this precondition yields
  16880. undefined behavior.
  16881. @pre Range `[first, last)` is valid. Usually, this precondition cannot be
  16882. checked efficiently. Only certain edge cases are detected; see the
  16883. description of the exceptions below. A violation of this precondition
  16884. yields undefined behavior.
  16885. @warning A precondition is enforced with a runtime assertion that will
  16886. result in calling `std::abort` if this precondition is not met.
  16887. Assertions can be disabled by defining `NDEBUG` at compile time.
  16888. See https://en.cppreference.com/w/cpp/error/assert for more
  16889. information.
  16890. @throw invalid_iterator.201 if iterators @a first and @a last are not
  16891. compatible (i.e., do not belong to the same JSON value). In this case,
  16892. the range `[first, last)` is undefined.
  16893. @throw invalid_iterator.204 if iterators @a first and @a last belong to a
  16894. primitive type (number, boolean, or string), but @a first does not point
  16895. to the first element any more. In this case, the range `[first, last)` is
  16896. undefined. See example code below.
  16897. @throw invalid_iterator.206 if iterators @a first and @a last belong to a
  16898. null value. In this case, the range `[first, last)` is undefined.
  16899. @complexity Linear in distance between @a first and @a last.
  16900. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  16901. changes to any JSON value.
  16902. @liveexample{The example below shows several ways to create JSON values by
  16903. specifying a subrange with iterators.,basic_json__InputIt_InputIt}
  16904. @since version 1.0.0
  16905. */
  16906. template < class InputIT, typename std::enable_if <
  16907. std::is_same<InputIT, typename basic_json_t::iterator>::value ||
  16908. std::is_same<InputIT, typename basic_json_t::const_iterator>::value, int >::type = 0 >
  16909. basic_json(InputIT first, InputIT last)
  16910. {
  16911. JSON_ASSERT(first.m_object != nullptr);
  16912. JSON_ASSERT(last.m_object != nullptr);
  16913. // make sure iterator fits the current value
  16914. if (JSON_HEDLEY_UNLIKELY(first.m_object != last.m_object))
  16915. {
  16916. JSON_THROW(invalid_iterator::create(201, "iterators are not compatible", basic_json()));
  16917. }
  16918. // copy type from first iterator
  16919. m_type = first.m_object->m_type;
  16920. // check if iterator range is complete for primitive values
  16921. switch (m_type)
  16922. {
  16923. case value_t::boolean:
  16924. case value_t::number_float:
  16925. case value_t::number_integer:
  16926. case value_t::number_unsigned:
  16927. case value_t::string:
  16928. {
  16929. if (JSON_HEDLEY_UNLIKELY(!first.m_it.primitive_iterator.is_begin()
  16930. || !last.m_it.primitive_iterator.is_end()))
  16931. {
  16932. JSON_THROW(invalid_iterator::create(204, "iterators out of range", *first.m_object));
  16933. }
  16934. break;
  16935. }
  16936. case value_t::null:
  16937. case value_t::object:
  16938. case value_t::array:
  16939. case value_t::binary:
  16940. case value_t::discarded:
  16941. default:
  16942. break;
  16943. }
  16944. switch (m_type)
  16945. {
  16946. case value_t::number_integer:
  16947. {
  16948. m_value.number_integer = first.m_object->m_value.number_integer;
  16949. break;
  16950. }
  16951. case value_t::number_unsigned:
  16952. {
  16953. m_value.number_unsigned = first.m_object->m_value.number_unsigned;
  16954. break;
  16955. }
  16956. case value_t::number_float:
  16957. {
  16958. m_value.number_float = first.m_object->m_value.number_float;
  16959. break;
  16960. }
  16961. case value_t::boolean:
  16962. {
  16963. m_value.boolean = first.m_object->m_value.boolean;
  16964. break;
  16965. }
  16966. case value_t::string:
  16967. {
  16968. m_value = *first.m_object->m_value.string;
  16969. break;
  16970. }
  16971. case value_t::object:
  16972. {
  16973. m_value.object = create<object_t>(first.m_it.object_iterator,
  16974. last.m_it.object_iterator);
  16975. break;
  16976. }
  16977. case value_t::array:
  16978. {
  16979. m_value.array = create<array_t>(first.m_it.array_iterator,
  16980. last.m_it.array_iterator);
  16981. break;
  16982. }
  16983. case value_t::binary:
  16984. {
  16985. m_value = *first.m_object->m_value.binary;
  16986. break;
  16987. }
  16988. case value_t::null:
  16989. case value_t::discarded:
  16990. default:
  16991. JSON_THROW(invalid_iterator::create(206, "cannot construct with iterators from " + std::string(first.m_object->type_name()), *first.m_object));
  16992. }
  16993. set_parents();
  16994. assert_invariant();
  16995. }
  16996. ///////////////////////////////////////
  16997. // other constructors and destructor //
  16998. ///////////////////////////////////////
  16999. template<typename JsonRef,
  17000. detail::enable_if_t<detail::conjunction<detail::is_json_ref<JsonRef>,
  17001. std::is_same<typename JsonRef::value_type, basic_json>>::value, int> = 0 >
  17002. basic_json(const JsonRef& ref) : basic_json(ref.moved_or_copied()) {}
  17003. /*!
  17004. @brief copy constructor
  17005. Creates a copy of a given JSON value.
  17006. @param[in] other the JSON value to copy
  17007. @post `*this == other`
  17008. @complexity Linear in the size of @a other.
  17009. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  17010. changes to any JSON value.
  17011. @requirement This function helps `basic_json` satisfying the
  17012. [Container](https://en.cppreference.com/w/cpp/named_req/Container)
  17013. requirements:
  17014. - The complexity is linear.
  17015. - As postcondition, it holds: `other == basic_json(other)`.
  17016. @liveexample{The following code shows an example for the copy
  17017. constructor.,basic_json__basic_json}
  17018. @since version 1.0.0
  17019. */
  17020. basic_json(const basic_json& other)
  17021. : m_type(other.m_type)
  17022. {
  17023. // check of passed value is valid
  17024. other.assert_invariant();
  17025. switch (m_type)
  17026. {
  17027. case value_t::object:
  17028. {
  17029. m_value = *other.m_value.object;
  17030. break;
  17031. }
  17032. case value_t::array:
  17033. {
  17034. m_value = *other.m_value.array;
  17035. break;
  17036. }
  17037. case value_t::string:
  17038. {
  17039. m_value = *other.m_value.string;
  17040. break;
  17041. }
  17042. case value_t::boolean:
  17043. {
  17044. m_value = other.m_value.boolean;
  17045. break;
  17046. }
  17047. case value_t::number_integer:
  17048. {
  17049. m_value = other.m_value.number_integer;
  17050. break;
  17051. }
  17052. case value_t::number_unsigned:
  17053. {
  17054. m_value = other.m_value.number_unsigned;
  17055. break;
  17056. }
  17057. case value_t::number_float:
  17058. {
  17059. m_value = other.m_value.number_float;
  17060. break;
  17061. }
  17062. case value_t::binary:
  17063. {
  17064. m_value = *other.m_value.binary;
  17065. break;
  17066. }
  17067. case value_t::null:
  17068. case value_t::discarded:
  17069. default:
  17070. break;
  17071. }
  17072. set_parents();
  17073. assert_invariant();
  17074. }
  17075. /*!
  17076. @brief move constructor
  17077. Move constructor. Constructs a JSON value with the contents of the given
  17078. value @a other using move semantics. It "steals" the resources from @a
  17079. other and leaves it as JSON null value.
  17080. @param[in,out] other value to move to this object
  17081. @post `*this` has the same value as @a other before the call.
  17082. @post @a other is a JSON null value.
  17083. @complexity Constant.
  17084. @exceptionsafety No-throw guarantee: this constructor never throws
  17085. exceptions.
  17086. @requirement This function helps `basic_json` satisfying the
  17087. [MoveConstructible](https://en.cppreference.com/w/cpp/named_req/MoveConstructible)
  17088. requirements.
  17089. @liveexample{The code below shows the move constructor explicitly called
  17090. via std::move.,basic_json__moveconstructor}
  17091. @since version 1.0.0
  17092. */
  17093. basic_json(basic_json&& other) noexcept
  17094. : m_type(std::move(other.m_type)),
  17095. m_value(std::move(other.m_value))
  17096. {
  17097. // check that passed value is valid
  17098. other.assert_invariant(false);
  17099. // invalidate payload
  17100. other.m_type = value_t::null;
  17101. other.m_value = {};
  17102. set_parents();
  17103. assert_invariant();
  17104. }
  17105. /*!
  17106. @brief copy assignment
  17107. Copy assignment operator. Copies a JSON value via the "copy and swap"
  17108. strategy: It is expressed in terms of the copy constructor, destructor,
  17109. and the `swap()` member function.
  17110. @param[in] other value to copy from
  17111. @complexity Linear.
  17112. @requirement This function helps `basic_json` satisfying the
  17113. [Container](https://en.cppreference.com/w/cpp/named_req/Container)
  17114. requirements:
  17115. - The complexity is linear.
  17116. @liveexample{The code below shows and example for the copy assignment. It
  17117. creates a copy of value `a` which is then swapped with `b`. Finally\, the
  17118. copy of `a` (which is the null value after the swap) is
  17119. destroyed.,basic_json__copyassignment}
  17120. @since version 1.0.0
  17121. */
  17122. basic_json& operator=(basic_json other) noexcept (
  17123. std::is_nothrow_move_constructible<value_t>::value&&
  17124. std::is_nothrow_move_assignable<value_t>::value&&
  17125. std::is_nothrow_move_constructible<json_value>::value&&
  17126. std::is_nothrow_move_assignable<json_value>::value
  17127. )
  17128. {
  17129. // check that passed value is valid
  17130. other.assert_invariant();
  17131. using std::swap;
  17132. swap(m_type, other.m_type);
  17133. swap(m_value, other.m_value);
  17134. set_parents();
  17135. assert_invariant();
  17136. return *this;
  17137. }
  17138. /*!
  17139. @brief destructor
  17140. Destroys the JSON value and frees all allocated memory.
  17141. @complexity Linear.
  17142. @requirement This function helps `basic_json` satisfying the
  17143. [Container](https://en.cppreference.com/w/cpp/named_req/Container)
  17144. requirements:
  17145. - The complexity is linear.
  17146. - All stored elements are destroyed and all memory is freed.
  17147. @since version 1.0.0
  17148. */
  17149. ~basic_json() noexcept
  17150. {
  17151. assert_invariant(false);
  17152. m_value.destroy(m_type);
  17153. }
  17154. /// @}
  17155. public:
  17156. ///////////////////////
  17157. // object inspection //
  17158. ///////////////////////
  17159. /// @name object inspection
  17160. /// Functions to inspect the type of a JSON value.
  17161. /// @{
  17162. /*!
  17163. @brief serialization
  17164. Serialization function for JSON values. The function tries to mimic
  17165. Python's `json.dumps()` function, and currently supports its @a indent
  17166. and @a ensure_ascii parameters.
  17167. @param[in] indent If indent is nonnegative, then array elements and object
  17168. members will be pretty-printed with that indent level. An indent level of
  17169. `0` will only insert newlines. `-1` (the default) selects the most compact
  17170. representation.
  17171. @param[in] indent_char The character to use for indentation if @a indent is
  17172. greater than `0`. The default is ` ` (space).
  17173. @param[in] ensure_ascii If @a ensure_ascii is true, all non-ASCII characters
  17174. in the output are escaped with `\uXXXX` sequences, and the result consists
  17175. of ASCII characters only.
  17176. @param[in] error_handler how to react on decoding errors; there are three
  17177. possible values: `strict` (throws and exception in case a decoding error
  17178. occurs; default), `replace` (replace invalid UTF-8 sequences with U+FFFD),
  17179. and `ignore` (ignore invalid UTF-8 sequences during serialization; all
  17180. bytes are copied to the output unchanged).
  17181. @return string containing the serialization of the JSON value
  17182. @throw type_error.316 if a string stored inside the JSON value is not
  17183. UTF-8 encoded and @a error_handler is set to strict
  17184. @note Binary values are serialized as object containing two keys:
  17185. - "bytes": an array of bytes as integers
  17186. - "subtype": the subtype as integer or "null" if the binary has no subtype
  17187. @complexity Linear.
  17188. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  17189. changes in the JSON value.
  17190. @liveexample{The following example shows the effect of different @a indent\,
  17191. @a indent_char\, and @a ensure_ascii parameters to the result of the
  17192. serialization.,dump}
  17193. @see https://docs.python.org/2/library/json.html#json.dump
  17194. @since version 1.0.0; indentation character @a indent_char, option
  17195. @a ensure_ascii and exceptions added in version 3.0.0; error
  17196. handlers added in version 3.4.0; serialization of binary values added
  17197. in version 3.8.0.
  17198. */
  17199. string_t dump(const int indent = -1,
  17200. const char indent_char = ' ',
  17201. const bool ensure_ascii = false,
  17202. const error_handler_t error_handler = error_handler_t::strict) const
  17203. {
  17204. string_t result;
  17205. serializer s(detail::output_adapter<char, string_t>(result), indent_char, error_handler);
  17206. if (indent >= 0)
  17207. {
  17208. s.dump(*this, true, ensure_ascii, static_cast<unsigned int>(indent));
  17209. }
  17210. else
  17211. {
  17212. s.dump(*this, false, ensure_ascii, 0);
  17213. }
  17214. return result;
  17215. }
  17216. /*!
  17217. @brief return the type of the JSON value (explicit)
  17218. Return the type of the JSON value as a value from the @ref value_t
  17219. enumeration.
  17220. @return the type of the JSON value
  17221. Value type | return value
  17222. ------------------------- | -------------------------
  17223. null | value_t::null
  17224. boolean | value_t::boolean
  17225. string | value_t::string
  17226. number (integer) | value_t::number_integer
  17227. number (unsigned integer) | value_t::number_unsigned
  17228. number (floating-point) | value_t::number_float
  17229. object | value_t::object
  17230. array | value_t::array
  17231. binary | value_t::binary
  17232. discarded | value_t::discarded
  17233. @complexity Constant.
  17234. @exceptionsafety No-throw guarantee: this member function never throws
  17235. exceptions.
  17236. @liveexample{The following code exemplifies `type()` for all JSON
  17237. types.,type}
  17238. @sa see @ref operator value_t() -- return the type of the JSON value (implicit)
  17239. @sa see @ref type_name() -- return the type as string
  17240. @since version 1.0.0
  17241. */
  17242. constexpr value_t type() const noexcept
  17243. {
  17244. return m_type;
  17245. }
  17246. /*!
  17247. @brief return whether type is primitive
  17248. This function returns true if and only if the JSON type is primitive
  17249. (string, number, boolean, or null).
  17250. @return `true` if type is primitive (string, number, boolean, or null),
  17251. `false` otherwise.
  17252. @complexity Constant.
  17253. @exceptionsafety No-throw guarantee: this member function never throws
  17254. exceptions.
  17255. @liveexample{The following code exemplifies `is_primitive()` for all JSON
  17256. types.,is_primitive}
  17257. @sa see @ref is_structured() -- returns whether JSON value is structured
  17258. @sa see @ref is_null() -- returns whether JSON value is `null`
  17259. @sa see @ref is_string() -- returns whether JSON value is a string
  17260. @sa see @ref is_boolean() -- returns whether JSON value is a boolean
  17261. @sa see @ref is_number() -- returns whether JSON value is a number
  17262. @sa see @ref is_binary() -- returns whether JSON value is a binary array
  17263. @since version 1.0.0
  17264. */
  17265. constexpr bool is_primitive() const noexcept
  17266. {
  17267. return is_null() || is_string() || is_boolean() || is_number() || is_binary();
  17268. }
  17269. /*!
  17270. @brief return whether type is structured
  17271. This function returns true if and only if the JSON type is structured
  17272. (array or object).
  17273. @return `true` if type is structured (array or object), `false` otherwise.
  17274. @complexity Constant.
  17275. @exceptionsafety No-throw guarantee: this member function never throws
  17276. exceptions.
  17277. @liveexample{The following code exemplifies `is_structured()` for all JSON
  17278. types.,is_structured}
  17279. @sa see @ref is_primitive() -- returns whether value is primitive
  17280. @sa see @ref is_array() -- returns whether value is an array
  17281. @sa see @ref is_object() -- returns whether value is an object
  17282. @since version 1.0.0
  17283. */
  17284. constexpr bool is_structured() const noexcept
  17285. {
  17286. return is_array() || is_object();
  17287. }
  17288. /*!
  17289. @brief return whether value is null
  17290. This function returns true if and only if the JSON value is null.
  17291. @return `true` if type is null, `false` otherwise.
  17292. @complexity Constant.
  17293. @exceptionsafety No-throw guarantee: this member function never throws
  17294. exceptions.
  17295. @liveexample{The following code exemplifies `is_null()` for all JSON
  17296. types.,is_null}
  17297. @since version 1.0.0
  17298. */
  17299. constexpr bool is_null() const noexcept
  17300. {
  17301. return m_type == value_t::null;
  17302. }
  17303. /*!
  17304. @brief return whether value is a boolean
  17305. This function returns true if and only if the JSON value is a boolean.
  17306. @return `true` if type is boolean, `false` otherwise.
  17307. @complexity Constant.
  17308. @exceptionsafety No-throw guarantee: this member function never throws
  17309. exceptions.
  17310. @liveexample{The following code exemplifies `is_boolean()` for all JSON
  17311. types.,is_boolean}
  17312. @since version 1.0.0
  17313. */
  17314. constexpr bool is_boolean() const noexcept
  17315. {
  17316. return m_type == value_t::boolean;
  17317. }
  17318. /*!
  17319. @brief return whether value is a number
  17320. This function returns true if and only if the JSON value is a number. This
  17321. includes both integer (signed and unsigned) and floating-point values.
  17322. @return `true` if type is number (regardless whether integer, unsigned
  17323. integer or floating-type), `false` otherwise.
  17324. @complexity Constant.
  17325. @exceptionsafety No-throw guarantee: this member function never throws
  17326. exceptions.
  17327. @liveexample{The following code exemplifies `is_number()` for all JSON
  17328. types.,is_number}
  17329. @sa see @ref is_number_integer() -- check if value is an integer or unsigned
  17330. integer number
  17331. @sa see @ref is_number_unsigned() -- check if value is an unsigned integer
  17332. number
  17333. @sa see @ref is_number_float() -- check if value is a floating-point number
  17334. @since version 1.0.0
  17335. */
  17336. constexpr bool is_number() const noexcept
  17337. {
  17338. return is_number_integer() || is_number_float();
  17339. }
  17340. /*!
  17341. @brief return whether value is an integer number
  17342. This function returns true if and only if the JSON value is a signed or
  17343. unsigned integer number. This excludes floating-point values.
  17344. @return `true` if type is an integer or unsigned integer number, `false`
  17345. otherwise.
  17346. @complexity Constant.
  17347. @exceptionsafety No-throw guarantee: this member function never throws
  17348. exceptions.
  17349. @liveexample{The following code exemplifies `is_number_integer()` for all
  17350. JSON types.,is_number_integer}
  17351. @sa see @ref is_number() -- check if value is a number
  17352. @sa see @ref is_number_unsigned() -- check if value is an unsigned integer
  17353. number
  17354. @sa see @ref is_number_float() -- check if value is a floating-point number
  17355. @since version 1.0.0
  17356. */
  17357. constexpr bool is_number_integer() const noexcept
  17358. {
  17359. return m_type == value_t::number_integer || m_type == value_t::number_unsigned;
  17360. }
  17361. /*!
  17362. @brief return whether value is an unsigned integer number
  17363. This function returns true if and only if the JSON value is an unsigned
  17364. integer number. This excludes floating-point and signed integer values.
  17365. @return `true` if type is an unsigned integer number, `false` otherwise.
  17366. @complexity Constant.
  17367. @exceptionsafety No-throw guarantee: this member function never throws
  17368. exceptions.
  17369. @liveexample{The following code exemplifies `is_number_unsigned()` for all
  17370. JSON types.,is_number_unsigned}
  17371. @sa see @ref is_number() -- check if value is a number
  17372. @sa see @ref is_number_integer() -- check if value is an integer or unsigned
  17373. integer number
  17374. @sa see @ref is_number_float() -- check if value is a floating-point number
  17375. @since version 2.0.0
  17376. */
  17377. constexpr bool is_number_unsigned() const noexcept
  17378. {
  17379. return m_type == value_t::number_unsigned;
  17380. }
  17381. /*!
  17382. @brief return whether value is a floating-point number
  17383. This function returns true if and only if the JSON value is a
  17384. floating-point number. This excludes signed and unsigned integer values.
  17385. @return `true` if type is a floating-point number, `false` otherwise.
  17386. @complexity Constant.
  17387. @exceptionsafety No-throw guarantee: this member function never throws
  17388. exceptions.
  17389. @liveexample{The following code exemplifies `is_number_float()` for all
  17390. JSON types.,is_number_float}
  17391. @sa see @ref is_number() -- check if value is number
  17392. @sa see @ref is_number_integer() -- check if value is an integer number
  17393. @sa see @ref is_number_unsigned() -- check if value is an unsigned integer
  17394. number
  17395. @since version 1.0.0
  17396. */
  17397. constexpr bool is_number_float() const noexcept
  17398. {
  17399. return m_type == value_t::number_float;
  17400. }
  17401. /*!
  17402. @brief return whether value is an object
  17403. This function returns true if and only if the JSON value is an object.
  17404. @return `true` if type is object, `false` otherwise.
  17405. @complexity Constant.
  17406. @exceptionsafety No-throw guarantee: this member function never throws
  17407. exceptions.
  17408. @liveexample{The following code exemplifies `is_object()` for all JSON
  17409. types.,is_object}
  17410. @since version 1.0.0
  17411. */
  17412. constexpr bool is_object() const noexcept
  17413. {
  17414. return m_type == value_t::object;
  17415. }
  17416. /*!
  17417. @brief return whether value is an array
  17418. This function returns true if and only if the JSON value is an array.
  17419. @return `true` if type is array, `false` otherwise.
  17420. @complexity Constant.
  17421. @exceptionsafety No-throw guarantee: this member function never throws
  17422. exceptions.
  17423. @liveexample{The following code exemplifies `is_array()` for all JSON
  17424. types.,is_array}
  17425. @since version 1.0.0
  17426. */
  17427. constexpr bool is_array() const noexcept
  17428. {
  17429. return m_type == value_t::array;
  17430. }
  17431. /*!
  17432. @brief return whether value is a string
  17433. This function returns true if and only if the JSON value is a string.
  17434. @return `true` if type is string, `false` otherwise.
  17435. @complexity Constant.
  17436. @exceptionsafety No-throw guarantee: this member function never throws
  17437. exceptions.
  17438. @liveexample{The following code exemplifies `is_string()` for all JSON
  17439. types.,is_string}
  17440. @since version 1.0.0
  17441. */
  17442. constexpr bool is_string() const noexcept
  17443. {
  17444. return m_type == value_t::string;
  17445. }
  17446. /*!
  17447. @brief return whether value is a binary array
  17448. This function returns true if and only if the JSON value is a binary array.
  17449. @return `true` if type is binary array, `false` otherwise.
  17450. @complexity Constant.
  17451. @exceptionsafety No-throw guarantee: this member function never throws
  17452. exceptions.
  17453. @liveexample{The following code exemplifies `is_binary()` for all JSON
  17454. types.,is_binary}
  17455. @since version 3.8.0
  17456. */
  17457. constexpr bool is_binary() const noexcept
  17458. {
  17459. return m_type == value_t::binary;
  17460. }
  17461. /*!
  17462. @brief return whether value is discarded
  17463. This function returns true if and only if the JSON value was discarded
  17464. during parsing with a callback function (see @ref parser_callback_t).
  17465. @note This function will always be `false` for JSON values after parsing.
  17466. That is, discarded values can only occur during parsing, but will be
  17467. removed when inside a structured value or replaced by null in other cases.
  17468. @return `true` if type is discarded, `false` otherwise.
  17469. @complexity Constant.
  17470. @exceptionsafety No-throw guarantee: this member function never throws
  17471. exceptions.
  17472. @liveexample{The following code exemplifies `is_discarded()` for all JSON
  17473. types.,is_discarded}
  17474. @since version 1.0.0
  17475. */
  17476. constexpr bool is_discarded() const noexcept
  17477. {
  17478. return m_type == value_t::discarded;
  17479. }
  17480. /*!
  17481. @brief return the type of the JSON value (implicit)
  17482. Implicitly return the type of the JSON value as a value from the @ref
  17483. value_t enumeration.
  17484. @return the type of the JSON value
  17485. @complexity Constant.
  17486. @exceptionsafety No-throw guarantee: this member function never throws
  17487. exceptions.
  17488. @liveexample{The following code exemplifies the @ref value_t operator for
  17489. all JSON types.,operator__value_t}
  17490. @sa see @ref type() -- return the type of the JSON value (explicit)
  17491. @sa see @ref type_name() -- return the type as string
  17492. @since version 1.0.0
  17493. */
  17494. constexpr operator value_t() const noexcept
  17495. {
  17496. return m_type;
  17497. }
  17498. /// @}
  17499. private:
  17500. //////////////////
  17501. // value access //
  17502. //////////////////
  17503. /// get a boolean (explicit)
  17504. boolean_t get_impl(boolean_t* /*unused*/) const
  17505. {
  17506. if (JSON_HEDLEY_LIKELY(is_boolean()))
  17507. {
  17508. return m_value.boolean;
  17509. }
  17510. JSON_THROW(type_error::create(302, "type must be boolean, but is " + std::string(type_name()), *this));
  17511. }
  17512. /// get a pointer to the value (object)
  17513. object_t* get_impl_ptr(object_t* /*unused*/) noexcept
  17514. {
  17515. return is_object() ? m_value.object : nullptr;
  17516. }
  17517. /// get a pointer to the value (object)
  17518. constexpr const object_t* get_impl_ptr(const object_t* /*unused*/) const noexcept
  17519. {
  17520. return is_object() ? m_value.object : nullptr;
  17521. }
  17522. /// get a pointer to the value (array)
  17523. array_t* get_impl_ptr(array_t* /*unused*/) noexcept
  17524. {
  17525. return is_array() ? m_value.array : nullptr;
  17526. }
  17527. /// get a pointer to the value (array)
  17528. constexpr const array_t* get_impl_ptr(const array_t* /*unused*/) const noexcept
  17529. {
  17530. return is_array() ? m_value.array : nullptr;
  17531. }
  17532. /// get a pointer to the value (string)
  17533. string_t* get_impl_ptr(string_t* /*unused*/) noexcept
  17534. {
  17535. return is_string() ? m_value.string : nullptr;
  17536. }
  17537. /// get a pointer to the value (string)
  17538. constexpr const string_t* get_impl_ptr(const string_t* /*unused*/) const noexcept
  17539. {
  17540. return is_string() ? m_value.string : nullptr;
  17541. }
  17542. /// get a pointer to the value (boolean)
  17543. boolean_t* get_impl_ptr(boolean_t* /*unused*/) noexcept
  17544. {
  17545. return is_boolean() ? &m_value.boolean : nullptr;
  17546. }
  17547. /// get a pointer to the value (boolean)
  17548. constexpr const boolean_t* get_impl_ptr(const boolean_t* /*unused*/) const noexcept
  17549. {
  17550. return is_boolean() ? &m_value.boolean : nullptr;
  17551. }
  17552. /// get a pointer to the value (integer number)
  17553. number_integer_t* get_impl_ptr(number_integer_t* /*unused*/) noexcept
  17554. {
  17555. return is_number_integer() ? &m_value.number_integer : nullptr;
  17556. }
  17557. /// get a pointer to the value (integer number)
  17558. constexpr const number_integer_t* get_impl_ptr(const number_integer_t* /*unused*/) const noexcept
  17559. {
  17560. return is_number_integer() ? &m_value.number_integer : nullptr;
  17561. }
  17562. /// get a pointer to the value (unsigned number)
  17563. number_unsigned_t* get_impl_ptr(number_unsigned_t* /*unused*/) noexcept
  17564. {
  17565. return is_number_unsigned() ? &m_value.number_unsigned : nullptr;
  17566. }
  17567. /// get a pointer to the value (unsigned number)
  17568. constexpr const number_unsigned_t* get_impl_ptr(const number_unsigned_t* /*unused*/) const noexcept
  17569. {
  17570. return is_number_unsigned() ? &m_value.number_unsigned : nullptr;
  17571. }
  17572. /// get a pointer to the value (floating-point number)
  17573. number_float_t* get_impl_ptr(number_float_t* /*unused*/) noexcept
  17574. {
  17575. return is_number_float() ? &m_value.number_float : nullptr;
  17576. }
  17577. /// get a pointer to the value (floating-point number)
  17578. constexpr const number_float_t* get_impl_ptr(const number_float_t* /*unused*/) const noexcept
  17579. {
  17580. return is_number_float() ? &m_value.number_float : nullptr;
  17581. }
  17582. /// get a pointer to the value (binary)
  17583. binary_t* get_impl_ptr(binary_t* /*unused*/) noexcept
  17584. {
  17585. return is_binary() ? m_value.binary : nullptr;
  17586. }
  17587. /// get a pointer to the value (binary)
  17588. constexpr const binary_t* get_impl_ptr(const binary_t* /*unused*/) const noexcept
  17589. {
  17590. return is_binary() ? m_value.binary : nullptr;
  17591. }
  17592. /*!
  17593. @brief helper function to implement get_ref()
  17594. This function helps to implement get_ref() without code duplication for
  17595. const and non-const overloads
  17596. @tparam ThisType will be deduced as `basic_json` or `const basic_json`
  17597. @throw type_error.303 if ReferenceType does not match underlying value
  17598. type of the current JSON
  17599. */
  17600. template<typename ReferenceType, typename ThisType>
  17601. static ReferenceType get_ref_impl(ThisType& obj)
  17602. {
  17603. // delegate the call to get_ptr<>()
  17604. auto* ptr = obj.template get_ptr<typename std::add_pointer<ReferenceType>::type>();
  17605. if (JSON_HEDLEY_LIKELY(ptr != nullptr))
  17606. {
  17607. return *ptr;
  17608. }
  17609. JSON_THROW(type_error::create(303, "incompatible ReferenceType for get_ref, actual type is " + std::string(obj.type_name()), obj));
  17610. }
  17611. public:
  17612. /// @name value access
  17613. /// Direct access to the stored value of a JSON value.
  17614. /// @{
  17615. /*!
  17616. @brief get a pointer value (implicit)
  17617. Implicit pointer access to the internally stored JSON value. No copies are
  17618. made.
  17619. @warning Writing data to the pointee of the result yields an undefined
  17620. state.
  17621. @tparam PointerType pointer type; must be a pointer to @ref array_t, @ref
  17622. object_t, @ref string_t, @ref boolean_t, @ref number_integer_t,
  17623. @ref number_unsigned_t, or @ref number_float_t. Enforced by a static
  17624. assertion.
  17625. @return pointer to the internally stored JSON value if the requested
  17626. pointer type @a PointerType fits to the JSON value; `nullptr` otherwise
  17627. @complexity Constant.
  17628. @liveexample{The example below shows how pointers to internal values of a
  17629. JSON value can be requested. Note that no type conversions are made and a
  17630. `nullptr` is returned if the value and the requested pointer type does not
  17631. match.,get_ptr}
  17632. @since version 1.0.0
  17633. */
  17634. template<typename PointerType, typename std::enable_if<
  17635. std::is_pointer<PointerType>::value, int>::type = 0>
  17636. auto get_ptr() noexcept -> decltype(std::declval<basic_json_t&>().get_impl_ptr(std::declval<PointerType>()))
  17637. {
  17638. // delegate the call to get_impl_ptr<>()
  17639. return get_impl_ptr(static_cast<PointerType>(nullptr));
  17640. }
  17641. /*!
  17642. @brief get a pointer value (implicit)
  17643. @copydoc get_ptr()
  17644. */
  17645. template < typename PointerType, typename std::enable_if <
  17646. std::is_pointer<PointerType>::value&&
  17647. std::is_const<typename std::remove_pointer<PointerType>::type>::value, int >::type = 0 >
  17648. constexpr auto get_ptr() const noexcept -> decltype(std::declval<const basic_json_t&>().get_impl_ptr(std::declval<PointerType>()))
  17649. {
  17650. // delegate the call to get_impl_ptr<>() const
  17651. return get_impl_ptr(static_cast<PointerType>(nullptr));
  17652. }
  17653. private:
  17654. /*!
  17655. @brief get a value (explicit)
  17656. Explicit type conversion between the JSON value and a compatible value
  17657. which is [CopyConstructible](https://en.cppreference.com/w/cpp/named_req/CopyConstructible)
  17658. and [DefaultConstructible](https://en.cppreference.com/w/cpp/named_req/DefaultConstructible).
  17659. The value is converted by calling the @ref json_serializer<ValueType>
  17660. `from_json()` method.
  17661. The function is equivalent to executing
  17662. @code {.cpp}
  17663. ValueType ret;
  17664. JSONSerializer<ValueType>::from_json(*this, ret);
  17665. return ret;
  17666. @endcode
  17667. This overloads is chosen if:
  17668. - @a ValueType is not @ref basic_json,
  17669. - @ref json_serializer<ValueType> has a `from_json()` method of the form
  17670. `void from_json(const basic_json&, ValueType&)`, and
  17671. - @ref json_serializer<ValueType> does not have a `from_json()` method of
  17672. the form `ValueType from_json(const basic_json&)`
  17673. @tparam ValueType the returned value type
  17674. @return copy of the JSON value, converted to @a ValueType
  17675. @throw what @ref json_serializer<ValueType> `from_json()` method throws
  17676. @liveexample{The example below shows several conversions from JSON values
  17677. to other types. There a few things to note: (1) Floating-point numbers can
  17678. be converted to integers\, (2) A JSON array can be converted to a standard
  17679. `std::vector<short>`\, (3) A JSON object can be converted to C++
  17680. associative containers such as `std::unordered_map<std::string\,
  17681. json>`.,get__ValueType_const}
  17682. @since version 2.1.0
  17683. */
  17684. template < typename ValueType,
  17685. detail::enable_if_t <
  17686. detail::is_default_constructible<ValueType>::value&&
  17687. detail::has_from_json<basic_json_t, ValueType>::value,
  17688. int > = 0 >
  17689. ValueType get_impl(detail::priority_tag<0> /*unused*/) const noexcept(noexcept(
  17690. JSONSerializer<ValueType>::from_json(std::declval<const basic_json_t&>(), std::declval<ValueType&>())))
  17691. {
  17692. auto ret = ValueType();
  17693. JSONSerializer<ValueType>::from_json(*this, ret);
  17694. return ret;
  17695. }
  17696. /*!
  17697. @brief get a value (explicit); special case
  17698. Explicit type conversion between the JSON value and a compatible value
  17699. which is **not** [CopyConstructible](https://en.cppreference.com/w/cpp/named_req/CopyConstructible)
  17700. and **not** [DefaultConstructible](https://en.cppreference.com/w/cpp/named_req/DefaultConstructible).
  17701. The value is converted by calling the @ref json_serializer<ValueType>
  17702. `from_json()` method.
  17703. The function is equivalent to executing
  17704. @code {.cpp}
  17705. return JSONSerializer<ValueType>::from_json(*this);
  17706. @endcode
  17707. This overloads is chosen if:
  17708. - @a ValueType is not @ref basic_json and
  17709. - @ref json_serializer<ValueType> has a `from_json()` method of the form
  17710. `ValueType from_json(const basic_json&)`
  17711. @note If @ref json_serializer<ValueType> has both overloads of
  17712. `from_json()`, this one is chosen.
  17713. @tparam ValueType the returned value type
  17714. @return copy of the JSON value, converted to @a ValueType
  17715. @throw what @ref json_serializer<ValueType> `from_json()` method throws
  17716. @since version 2.1.0
  17717. */
  17718. template < typename ValueType,
  17719. detail::enable_if_t <
  17720. detail::has_non_default_from_json<basic_json_t, ValueType>::value,
  17721. int > = 0 >
  17722. ValueType get_impl(detail::priority_tag<1> /*unused*/) const noexcept(noexcept(
  17723. JSONSerializer<ValueType>::from_json(std::declval<const basic_json_t&>())))
  17724. {
  17725. return JSONSerializer<ValueType>::from_json(*this);
  17726. }
  17727. /*!
  17728. @brief get special-case overload
  17729. This overloads converts the current @ref basic_json in a different
  17730. @ref basic_json type
  17731. @tparam BasicJsonType == @ref basic_json
  17732. @return a copy of *this, converted into @a BasicJsonType
  17733. @complexity Depending on the implementation of the called `from_json()`
  17734. method.
  17735. @since version 3.2.0
  17736. */
  17737. template < typename BasicJsonType,
  17738. detail::enable_if_t <
  17739. detail::is_basic_json<BasicJsonType>::value,
  17740. int > = 0 >
  17741. BasicJsonType get_impl(detail::priority_tag<2> /*unused*/) const
  17742. {
  17743. return *this;
  17744. }
  17745. /*!
  17746. @brief get special-case overload
  17747. This overloads avoids a lot of template boilerplate, it can be seen as the
  17748. identity method
  17749. @tparam BasicJsonType == @ref basic_json
  17750. @return a copy of *this
  17751. @complexity Constant.
  17752. @since version 2.1.0
  17753. */
  17754. template<typename BasicJsonType,
  17755. detail::enable_if_t<
  17756. std::is_same<BasicJsonType, basic_json_t>::value,
  17757. int> = 0>
  17758. basic_json get_impl(detail::priority_tag<3> /*unused*/) const
  17759. {
  17760. return *this;
  17761. }
  17762. /*!
  17763. @brief get a pointer value (explicit)
  17764. @copydoc get()
  17765. */
  17766. template<typename PointerType,
  17767. detail::enable_if_t<
  17768. std::is_pointer<PointerType>::value,
  17769. int> = 0>
  17770. constexpr auto get_impl(detail::priority_tag<4> /*unused*/) const noexcept
  17771. -> decltype(std::declval<const basic_json_t&>().template get_ptr<PointerType>())
  17772. {
  17773. // delegate the call to get_ptr
  17774. return get_ptr<PointerType>();
  17775. }
  17776. public:
  17777. /*!
  17778. @brief get a (pointer) value (explicit)
  17779. Performs explicit type conversion between the JSON value and a compatible value if required.
  17780. - If the requested type is a pointer to the internally stored JSON value that pointer is returned.
  17781. No copies are made.
  17782. - If the requested type is the current @ref basic_json, or a different @ref basic_json convertible
  17783. from the current @ref basic_json.
  17784. - Otherwise the value is converted by calling the @ref json_serializer<ValueType> `from_json()`
  17785. method.
  17786. @tparam ValueTypeCV the provided value type
  17787. @tparam ValueType the returned value type
  17788. @return copy of the JSON value, converted to @tparam ValueType if necessary
  17789. @throw what @ref json_serializer<ValueType> `from_json()` method throws if conversion is required
  17790. @since version 2.1.0
  17791. */
  17792. template < typename ValueTypeCV, typename ValueType = detail::uncvref_t<ValueTypeCV>>
  17793. #if defined(JSON_HAS_CPP_14)
  17794. constexpr
  17795. #endif
  17796. auto get() const noexcept(
  17797. noexcept(std::declval<const basic_json_t&>().template get_impl<ValueType>(detail::priority_tag<4> {})))
  17798. -> decltype(std::declval<const basic_json_t&>().template get_impl<ValueType>(detail::priority_tag<4> {}))
  17799. {
  17800. // we cannot static_assert on ValueTypeCV being non-const, because
  17801. // there is support for get<const basic_json_t>(), which is why we
  17802. // still need the uncvref
  17803. static_assert(!std::is_reference<ValueTypeCV>::value,
  17804. "get() cannot be used with reference types, you might want to use get_ref()");
  17805. return get_impl<ValueType>(detail::priority_tag<4> {});
  17806. }
  17807. /*!
  17808. @brief get a pointer value (explicit)
  17809. Explicit pointer access to the internally stored JSON value. No copies are
  17810. made.
  17811. @warning The pointer becomes invalid if the underlying JSON object
  17812. changes.
  17813. @tparam PointerType pointer type; must be a pointer to @ref array_t, @ref
  17814. object_t, @ref string_t, @ref boolean_t, @ref number_integer_t,
  17815. @ref number_unsigned_t, or @ref number_float_t.
  17816. @return pointer to the internally stored JSON value if the requested
  17817. pointer type @a PointerType fits to the JSON value; `nullptr` otherwise
  17818. @complexity Constant.
  17819. @liveexample{The example below shows how pointers to internal values of a
  17820. JSON value can be requested. Note that no type conversions are made and a
  17821. `nullptr` is returned if the value and the requested pointer type does not
  17822. match.,get__PointerType}
  17823. @sa see @ref get_ptr() for explicit pointer-member access
  17824. @since version 1.0.0
  17825. */
  17826. template<typename PointerType, typename std::enable_if<
  17827. std::is_pointer<PointerType>::value, int>::type = 0>
  17828. auto get() noexcept -> decltype(std::declval<basic_json_t&>().template get_ptr<PointerType>())
  17829. {
  17830. // delegate the call to get_ptr
  17831. return get_ptr<PointerType>();
  17832. }
  17833. /*!
  17834. @brief get a value (explicit)
  17835. Explicit type conversion between the JSON value and a compatible value.
  17836. The value is filled into the input parameter by calling the @ref json_serializer<ValueType>
  17837. `from_json()` method.
  17838. The function is equivalent to executing
  17839. @code {.cpp}
  17840. ValueType v;
  17841. JSONSerializer<ValueType>::from_json(*this, v);
  17842. @endcode
  17843. This overloads is chosen if:
  17844. - @a ValueType is not @ref basic_json,
  17845. - @ref json_serializer<ValueType> has a `from_json()` method of the form
  17846. `void from_json(const basic_json&, ValueType&)`, and
  17847. @tparam ValueType the input parameter type.
  17848. @return the input parameter, allowing chaining calls.
  17849. @throw what @ref json_serializer<ValueType> `from_json()` method throws
  17850. @liveexample{The example below shows several conversions from JSON values
  17851. to other types. There a few things to note: (1) Floating-point numbers can
  17852. be converted to integers\, (2) A JSON array can be converted to a standard
  17853. `std::vector<short>`\, (3) A JSON object can be converted to C++
  17854. associative containers such as `std::unordered_map<std::string\,
  17855. json>`.,get_to}
  17856. @since version 3.3.0
  17857. */
  17858. template < typename ValueType,
  17859. detail::enable_if_t <
  17860. !detail::is_basic_json<ValueType>::value&&
  17861. detail::has_from_json<basic_json_t, ValueType>::value,
  17862. int > = 0 >
  17863. ValueType & get_to(ValueType& v) const noexcept(noexcept(
  17864. JSONSerializer<ValueType>::from_json(std::declval<const basic_json_t&>(), v)))
  17865. {
  17866. JSONSerializer<ValueType>::from_json(*this, v);
  17867. return v;
  17868. }
  17869. // specialization to allow to call get_to with a basic_json value
  17870. // see https://github.com/nlohmann/json/issues/2175
  17871. template<typename ValueType,
  17872. detail::enable_if_t <
  17873. detail::is_basic_json<ValueType>::value,
  17874. int> = 0>
  17875. ValueType & get_to(ValueType& v) const
  17876. {
  17877. v = *this;
  17878. return v;
  17879. }
  17880. template <
  17881. typename T, std::size_t N,
  17882. typename Array = T (&)[N], // NOLINT(cppcoreguidelines-avoid-c-arrays,hicpp-avoid-c-arrays,modernize-avoid-c-arrays)
  17883. detail::enable_if_t <
  17884. detail::has_from_json<basic_json_t, Array>::value, int > = 0 >
  17885. Array get_to(T (&v)[N]) const // NOLINT(cppcoreguidelines-avoid-c-arrays,hicpp-avoid-c-arrays,modernize-avoid-c-arrays)
  17886. noexcept(noexcept(JSONSerializer<Array>::from_json(
  17887. std::declval<const basic_json_t&>(), v)))
  17888. {
  17889. JSONSerializer<Array>::from_json(*this, v);
  17890. return v;
  17891. }
  17892. /*!
  17893. @brief get a reference value (implicit)
  17894. Implicit reference access to the internally stored JSON value. No copies
  17895. are made.
  17896. @warning Writing data to the referee of the result yields an undefined
  17897. state.
  17898. @tparam ReferenceType reference type; must be a reference to @ref array_t,
  17899. @ref object_t, @ref string_t, @ref boolean_t, @ref number_integer_t, or
  17900. @ref number_float_t. Enforced by static assertion.
  17901. @return reference to the internally stored JSON value if the requested
  17902. reference type @a ReferenceType fits to the JSON value; throws
  17903. type_error.303 otherwise
  17904. @throw type_error.303 in case passed type @a ReferenceType is incompatible
  17905. with the stored JSON value; see example below
  17906. @complexity Constant.
  17907. @liveexample{The example shows several calls to `get_ref()`.,get_ref}
  17908. @since version 1.1.0
  17909. */
  17910. template<typename ReferenceType, typename std::enable_if<
  17911. std::is_reference<ReferenceType>::value, int>::type = 0>
  17912. ReferenceType get_ref()
  17913. {
  17914. // delegate call to get_ref_impl
  17915. return get_ref_impl<ReferenceType>(*this);
  17916. }
  17917. /*!
  17918. @brief get a reference value (implicit)
  17919. @copydoc get_ref()
  17920. */
  17921. template < typename ReferenceType, typename std::enable_if <
  17922. std::is_reference<ReferenceType>::value&&
  17923. std::is_const<typename std::remove_reference<ReferenceType>::type>::value, int >::type = 0 >
  17924. ReferenceType get_ref() const
  17925. {
  17926. // delegate call to get_ref_impl
  17927. return get_ref_impl<ReferenceType>(*this);
  17928. }
  17929. /*!
  17930. @brief get a value (implicit)
  17931. Implicit type conversion between the JSON value and a compatible value.
  17932. The call is realized by calling @ref get() const.
  17933. @tparam ValueType non-pointer type compatible to the JSON value, for
  17934. instance `int` for JSON integer numbers, `bool` for JSON booleans, or
  17935. `std::vector` types for JSON arrays. The character type of @ref string_t
  17936. as well as an initializer list of this type is excluded to avoid
  17937. ambiguities as these types implicitly convert to `std::string`.
  17938. @return copy of the JSON value, converted to type @a ValueType
  17939. @throw type_error.302 in case passed type @a ValueType is incompatible
  17940. to the JSON value type (e.g., the JSON value is of type boolean, but a
  17941. string is requested); see example below
  17942. @complexity Linear in the size of the JSON value.
  17943. @liveexample{The example below shows several conversions from JSON values
  17944. to other types. There a few things to note: (1) Floating-point numbers can
  17945. be converted to integers\, (2) A JSON array can be converted to a standard
  17946. `std::vector<short>`\, (3) A JSON object can be converted to C++
  17947. associative containers such as `std::unordered_map<std::string\,
  17948. json>`.,operator__ValueType}
  17949. @since version 1.0.0
  17950. */
  17951. template < typename ValueType, typename std::enable_if <
  17952. detail::conjunction <
  17953. detail::negation<std::is_pointer<ValueType>>,
  17954. detail::negation<std::is_same<ValueType, detail::json_ref<basic_json>>>,
  17955. detail::negation<std::is_same<ValueType, typename string_t::value_type>>,
  17956. detail::negation<detail::is_basic_json<ValueType>>,
  17957. detail::negation<std::is_same<ValueType, std::initializer_list<typename string_t::value_type>>>,
  17958. #if defined(JSON_HAS_CPP_17) && (defined(__GNUC__) || (defined(_MSC_VER) && _MSC_VER >= 1910 && _MSC_VER <= 1914))
  17959. detail::negation<std::is_same<ValueType, std::string_view>>,
  17960. #endif
  17961. detail::is_detected_lazy<detail::get_template_function, const basic_json_t&, ValueType>
  17962. >::value, int >::type = 0 >
  17963. JSON_EXPLICIT operator ValueType() const
  17964. {
  17965. // delegate the call to get<>() const
  17966. return get<ValueType>();
  17967. }
  17968. /*!
  17969. @return reference to the binary value
  17970. @throw type_error.302 if the value is not binary
  17971. @sa see @ref is_binary() to check if the value is binary
  17972. @since version 3.8.0
  17973. */
  17974. binary_t& get_binary()
  17975. {
  17976. if (!is_binary())
  17977. {
  17978. JSON_THROW(type_error::create(302, "type must be binary, but is " + std::string(type_name()), *this));
  17979. }
  17980. return *get_ptr<binary_t*>();
  17981. }
  17982. /// @copydoc get_binary()
  17983. const binary_t& get_binary() const
  17984. {
  17985. if (!is_binary())
  17986. {
  17987. JSON_THROW(type_error::create(302, "type must be binary, but is " + std::string(type_name()), *this));
  17988. }
  17989. return *get_ptr<const binary_t*>();
  17990. }
  17991. /// @}
  17992. ////////////////////
  17993. // element access //
  17994. ////////////////////
  17995. /// @name element access
  17996. /// Access to the JSON value.
  17997. /// @{
  17998. /*!
  17999. @brief access specified array element with bounds checking
  18000. Returns a reference to the element at specified location @a idx, with
  18001. bounds checking.
  18002. @param[in] idx index of the element to access
  18003. @return reference to the element at index @a idx
  18004. @throw type_error.304 if the JSON value is not an array; in this case,
  18005. calling `at` with an index makes no sense. See example below.
  18006. @throw out_of_range.401 if the index @a idx is out of range of the array;
  18007. that is, `idx >= size()`. See example below.
  18008. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  18009. changes in the JSON value.
  18010. @complexity Constant.
  18011. @since version 1.0.0
  18012. @liveexample{The example below shows how array elements can be read and
  18013. written using `at()`. It also demonstrates the different exceptions that
  18014. can be thrown.,at__size_type}
  18015. */
  18016. reference at(size_type idx)
  18017. {
  18018. // at only works for arrays
  18019. if (JSON_HEDLEY_LIKELY(is_array()))
  18020. {
  18021. JSON_TRY
  18022. {
  18023. return set_parent(m_value.array->at(idx));
  18024. }
  18025. JSON_CATCH (std::out_of_range&)
  18026. {
  18027. // create better exception explanation
  18028. JSON_THROW(out_of_range::create(401, "array index " + std::to_string(idx) + " is out of range", *this));
  18029. }
  18030. }
  18031. else
  18032. {
  18033. JSON_THROW(type_error::create(304, "cannot use at() with " + std::string(type_name()), *this));
  18034. }
  18035. }
  18036. /*!
  18037. @brief access specified array element with bounds checking
  18038. Returns a const reference to the element at specified location @a idx,
  18039. with bounds checking.
  18040. @param[in] idx index of the element to access
  18041. @return const reference to the element at index @a idx
  18042. @throw type_error.304 if the JSON value is not an array; in this case,
  18043. calling `at` with an index makes no sense. See example below.
  18044. @throw out_of_range.401 if the index @a idx is out of range of the array;
  18045. that is, `idx >= size()`. See example below.
  18046. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  18047. changes in the JSON value.
  18048. @complexity Constant.
  18049. @since version 1.0.0
  18050. @liveexample{The example below shows how array elements can be read using
  18051. `at()`. It also demonstrates the different exceptions that can be thrown.,
  18052. at__size_type_const}
  18053. */
  18054. const_reference at(size_type idx) const
  18055. {
  18056. // at only works for arrays
  18057. if (JSON_HEDLEY_LIKELY(is_array()))
  18058. {
  18059. JSON_TRY
  18060. {
  18061. return m_value.array->at(idx);
  18062. }
  18063. JSON_CATCH (std::out_of_range&)
  18064. {
  18065. // create better exception explanation
  18066. JSON_THROW(out_of_range::create(401, "array index " + std::to_string(idx) + " is out of range", *this));
  18067. }
  18068. }
  18069. else
  18070. {
  18071. JSON_THROW(type_error::create(304, "cannot use at() with " + std::string(type_name()), *this));
  18072. }
  18073. }
  18074. /*!
  18075. @brief access specified object element with bounds checking
  18076. Returns a reference to the element at with specified key @a key, with
  18077. bounds checking.
  18078. @param[in] key key of the element to access
  18079. @return reference to the element at key @a key
  18080. @throw type_error.304 if the JSON value is not an object; in this case,
  18081. calling `at` with a key makes no sense. See example below.
  18082. @throw out_of_range.403 if the key @a key is is not stored in the object;
  18083. that is, `find(key) == end()`. See example below.
  18084. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  18085. changes in the JSON value.
  18086. @complexity Logarithmic in the size of the container.
  18087. @sa see @ref operator[](const typename object_t::key_type&) for unchecked
  18088. access by reference
  18089. @sa see @ref value() for access by value with a default value
  18090. @since version 1.0.0
  18091. @liveexample{The example below shows how object elements can be read and
  18092. written using `at()`. It also demonstrates the different exceptions that
  18093. can be thrown.,at__object_t_key_type}
  18094. */
  18095. reference at(const typename object_t::key_type& key)
  18096. {
  18097. // at only works for objects
  18098. if (JSON_HEDLEY_LIKELY(is_object()))
  18099. {
  18100. JSON_TRY
  18101. {
  18102. return set_parent(m_value.object->at(key));
  18103. }
  18104. JSON_CATCH (std::out_of_range&)
  18105. {
  18106. // create better exception explanation
  18107. JSON_THROW(out_of_range::create(403, "key '" + key + "' not found", *this));
  18108. }
  18109. }
  18110. else
  18111. {
  18112. JSON_THROW(type_error::create(304, "cannot use at() with " + std::string(type_name()), *this));
  18113. }
  18114. }
  18115. /*!
  18116. @brief access specified object element with bounds checking
  18117. Returns a const reference to the element at with specified key @a key,
  18118. with bounds checking.
  18119. @param[in] key key of the element to access
  18120. @return const reference to the element at key @a key
  18121. @throw type_error.304 if the JSON value is not an object; in this case,
  18122. calling `at` with a key makes no sense. See example below.
  18123. @throw out_of_range.403 if the key @a key is is not stored in the object;
  18124. that is, `find(key) == end()`. See example below.
  18125. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  18126. changes in the JSON value.
  18127. @complexity Logarithmic in the size of the container.
  18128. @sa see @ref operator[](const typename object_t::key_type&) for unchecked
  18129. access by reference
  18130. @sa see @ref value() for access by value with a default value
  18131. @since version 1.0.0
  18132. @liveexample{The example below shows how object elements can be read using
  18133. `at()`. It also demonstrates the different exceptions that can be thrown.,
  18134. at__object_t_key_type_const}
  18135. */
  18136. const_reference at(const typename object_t::key_type& key) const
  18137. {
  18138. // at only works for objects
  18139. if (JSON_HEDLEY_LIKELY(is_object()))
  18140. {
  18141. JSON_TRY
  18142. {
  18143. return m_value.object->at(key);
  18144. }
  18145. JSON_CATCH (std::out_of_range&)
  18146. {
  18147. // create better exception explanation
  18148. JSON_THROW(out_of_range::create(403, "key '" + key + "' not found", *this));
  18149. }
  18150. }
  18151. else
  18152. {
  18153. JSON_THROW(type_error::create(304, "cannot use at() with " + std::string(type_name()), *this));
  18154. }
  18155. }
  18156. /*!
  18157. @brief access specified array element
  18158. Returns a reference to the element at specified location @a idx.
  18159. @note If @a idx is beyond the range of the array (i.e., `idx >= size()`),
  18160. then the array is silently filled up with `null` values to make `idx` a
  18161. valid reference to the last stored element.
  18162. @param[in] idx index of the element to access
  18163. @return reference to the element at index @a idx
  18164. @throw type_error.305 if the JSON value is not an array or null; in that
  18165. cases, using the [] operator with an index makes no sense.
  18166. @complexity Constant if @a idx is in the range of the array. Otherwise
  18167. linear in `idx - size()`.
  18168. @liveexample{The example below shows how array elements can be read and
  18169. written using `[]` operator. Note the addition of `null`
  18170. values.,operatorarray__size_type}
  18171. @since version 1.0.0
  18172. */
  18173. reference operator[](size_type idx)
  18174. {
  18175. // implicitly convert null value to an empty array
  18176. if (is_null())
  18177. {
  18178. m_type = value_t::array;
  18179. m_value.array = create<array_t>();
  18180. assert_invariant();
  18181. }
  18182. // operator[] only works for arrays
  18183. if (JSON_HEDLEY_LIKELY(is_array()))
  18184. {
  18185. // fill up array with null values if given idx is outside range
  18186. if (idx >= m_value.array->size())
  18187. {
  18188. #if JSON_DIAGNOSTICS
  18189. // remember array size & capacity before resizing
  18190. const auto old_size = m_value.array->size();
  18191. const auto old_capacity = m_value.array->capacity();
  18192. #endif
  18193. m_value.array->resize(idx + 1);
  18194. #if JSON_DIAGNOSTICS
  18195. if (JSON_HEDLEY_UNLIKELY(m_value.array->capacity() != old_capacity))
  18196. {
  18197. // capacity has changed: update all parents
  18198. set_parents();
  18199. }
  18200. else
  18201. {
  18202. // set parent for values added above
  18203. set_parents(begin() + static_cast<typename iterator::difference_type>(old_size), static_cast<typename iterator::difference_type>(idx + 1 - old_size));
  18204. }
  18205. #endif
  18206. assert_invariant();
  18207. }
  18208. return m_value.array->operator[](idx);
  18209. }
  18210. JSON_THROW(type_error::create(305, "cannot use operator[] with a numeric argument with " + std::string(type_name()), *this));
  18211. }
  18212. /*!
  18213. @brief access specified array element
  18214. Returns a const reference to the element at specified location @a idx.
  18215. @param[in] idx index of the element to access
  18216. @return const reference to the element at index @a idx
  18217. @throw type_error.305 if the JSON value is not an array; in that case,
  18218. using the [] operator with an index makes no sense.
  18219. @complexity Constant.
  18220. @liveexample{The example below shows how array elements can be read using
  18221. the `[]` operator.,operatorarray__size_type_const}
  18222. @since version 1.0.0
  18223. */
  18224. const_reference operator[](size_type idx) const
  18225. {
  18226. // const operator[] only works for arrays
  18227. if (JSON_HEDLEY_LIKELY(is_array()))
  18228. {
  18229. return m_value.array->operator[](idx);
  18230. }
  18231. JSON_THROW(type_error::create(305, "cannot use operator[] with a numeric argument with " + std::string(type_name()), *this));
  18232. }
  18233. /*!
  18234. @brief access specified object element
  18235. Returns a reference to the element at with specified key @a key.
  18236. @note If @a key is not found in the object, then it is silently added to
  18237. the object and filled with a `null` value to make `key` a valid reference.
  18238. In case the value was `null` before, it is converted to an object.
  18239. @param[in] key key of the element to access
  18240. @return reference to the element at key @a key
  18241. @throw type_error.305 if the JSON value is not an object or null; in that
  18242. cases, using the [] operator with a key makes no sense.
  18243. @complexity Logarithmic in the size of the container.
  18244. @liveexample{The example below shows how object elements can be read and
  18245. written using the `[]` operator.,operatorarray__key_type}
  18246. @sa see @ref at(const typename object_t::key_type&) for access by reference
  18247. with range checking
  18248. @sa see @ref value() for access by value with a default value
  18249. @since version 1.0.0
  18250. */
  18251. reference operator[](const typename object_t::key_type& key)
  18252. {
  18253. // implicitly convert null value to an empty object
  18254. if (is_null())
  18255. {
  18256. m_type = value_t::object;
  18257. m_value.object = create<object_t>();
  18258. assert_invariant();
  18259. }
  18260. // operator[] only works for objects
  18261. if (JSON_HEDLEY_LIKELY(is_object()))
  18262. {
  18263. return set_parent(m_value.object->operator[](key));
  18264. }
  18265. JSON_THROW(type_error::create(305, "cannot use operator[] with a string argument with " + std::string(type_name()), *this));
  18266. }
  18267. /*!
  18268. @brief read-only access specified object element
  18269. Returns a const reference to the element at with specified key @a key. No
  18270. bounds checking is performed.
  18271. @warning If the element with key @a key does not exist, the behavior is
  18272. undefined.
  18273. @param[in] key key of the element to access
  18274. @return const reference to the element at key @a key
  18275. @pre The element with key @a key must exist. **This precondition is
  18276. enforced with an assertion.**
  18277. @throw type_error.305 if the JSON value is not an object; in that case,
  18278. using the [] operator with a key makes no sense.
  18279. @complexity Logarithmic in the size of the container.
  18280. @liveexample{The example below shows how object elements can be read using
  18281. the `[]` operator.,operatorarray__key_type_const}
  18282. @sa see @ref at(const typename object_t::key_type&) for access by reference
  18283. with range checking
  18284. @sa see @ref value() for access by value with a default value
  18285. @since version 1.0.0
  18286. */
  18287. const_reference operator[](const typename object_t::key_type& key) const
  18288. {
  18289. // const operator[] only works for objects
  18290. if (JSON_HEDLEY_LIKELY(is_object()))
  18291. {
  18292. JSON_ASSERT(m_value.object->find(key) != m_value.object->end());
  18293. return m_value.object->find(key)->second;
  18294. }
  18295. JSON_THROW(type_error::create(305, "cannot use operator[] with a string argument with " + std::string(type_name()), *this));
  18296. }
  18297. /*!
  18298. @brief access specified object element
  18299. Returns a reference to the element at with specified key @a key.
  18300. @note If @a key is not found in the object, then it is silently added to
  18301. the object and filled with a `null` value to make `key` a valid reference.
  18302. In case the value was `null` before, it is converted to an object.
  18303. @param[in] key key of the element to access
  18304. @return reference to the element at key @a key
  18305. @throw type_error.305 if the JSON value is not an object or null; in that
  18306. cases, using the [] operator with a key makes no sense.
  18307. @complexity Logarithmic in the size of the container.
  18308. @liveexample{The example below shows how object elements can be read and
  18309. written using the `[]` operator.,operatorarray__key_type}
  18310. @sa see @ref at(const typename object_t::key_type&) for access by reference
  18311. with range checking
  18312. @sa see @ref value() for access by value with a default value
  18313. @since version 1.1.0
  18314. */
  18315. template<typename T>
  18316. JSON_HEDLEY_NON_NULL(2)
  18317. reference operator[](T* key)
  18318. {
  18319. // implicitly convert null to object
  18320. if (is_null())
  18321. {
  18322. m_type = value_t::object;
  18323. m_value = value_t::object;
  18324. assert_invariant();
  18325. }
  18326. // at only works for objects
  18327. if (JSON_HEDLEY_LIKELY(is_object()))
  18328. {
  18329. return set_parent(m_value.object->operator[](key));
  18330. }
  18331. JSON_THROW(type_error::create(305, "cannot use operator[] with a string argument with " + std::string(type_name()), *this));
  18332. }
  18333. /*!
  18334. @brief read-only access specified object element
  18335. Returns a const reference to the element at with specified key @a key. No
  18336. bounds checking is performed.
  18337. @warning If the element with key @a key does not exist, the behavior is
  18338. undefined.
  18339. @param[in] key key of the element to access
  18340. @return const reference to the element at key @a key
  18341. @pre The element with key @a key must exist. **This precondition is
  18342. enforced with an assertion.**
  18343. @throw type_error.305 if the JSON value is not an object; in that case,
  18344. using the [] operator with a key makes no sense.
  18345. @complexity Logarithmic in the size of the container.
  18346. @liveexample{The example below shows how object elements can be read using
  18347. the `[]` operator.,operatorarray__key_type_const}
  18348. @sa see @ref at(const typename object_t::key_type&) for access by reference
  18349. with range checking
  18350. @sa see @ref value() for access by value with a default value
  18351. @since version 1.1.0
  18352. */
  18353. template<typename T>
  18354. JSON_HEDLEY_NON_NULL(2)
  18355. const_reference operator[](T* key) const
  18356. {
  18357. // at only works for objects
  18358. if (JSON_HEDLEY_LIKELY(is_object()))
  18359. {
  18360. JSON_ASSERT(m_value.object->find(key) != m_value.object->end());
  18361. return m_value.object->find(key)->second;
  18362. }
  18363. JSON_THROW(type_error::create(305, "cannot use operator[] with a string argument with " + std::string(type_name()), *this));
  18364. }
  18365. /*!
  18366. @brief access specified object element with default value
  18367. Returns either a copy of an object's element at the specified key @a key
  18368. or a given default value if no element with key @a key exists.
  18369. The function is basically equivalent to executing
  18370. @code {.cpp}
  18371. try {
  18372. return at(key);
  18373. } catch(out_of_range) {
  18374. return default_value;
  18375. }
  18376. @endcode
  18377. @note Unlike @ref at(const typename object_t::key_type&), this function
  18378. does not throw if the given key @a key was not found.
  18379. @note Unlike @ref operator[](const typename object_t::key_type& key), this
  18380. function does not implicitly add an element to the position defined by @a
  18381. key. This function is furthermore also applicable to const objects.
  18382. @param[in] key key of the element to access
  18383. @param[in] default_value the value to return if @a key is not found
  18384. @tparam ValueType type compatible to JSON values, for instance `int` for
  18385. JSON integer numbers, `bool` for JSON booleans, or `std::vector` types for
  18386. JSON arrays. Note the type of the expected value at @a key and the default
  18387. value @a default_value must be compatible.
  18388. @return copy of the element at key @a key or @a default_value if @a key
  18389. is not found
  18390. @throw type_error.302 if @a default_value does not match the type of the
  18391. value at @a key
  18392. @throw type_error.306 if the JSON value is not an object; in that case,
  18393. using `value()` with a key makes no sense.
  18394. @complexity Logarithmic in the size of the container.
  18395. @liveexample{The example below shows how object elements can be queried
  18396. with a default value.,basic_json__value}
  18397. @sa see @ref at(const typename object_t::key_type&) for access by reference
  18398. with range checking
  18399. @sa see @ref operator[](const typename object_t::key_type&) for unchecked
  18400. access by reference
  18401. @since version 1.0.0
  18402. */
  18403. // using std::is_convertible in a std::enable_if will fail when using explicit conversions
  18404. template < class ValueType, typename std::enable_if <
  18405. detail::is_getable<basic_json_t, ValueType>::value
  18406. && !std::is_same<value_t, ValueType>::value, int >::type = 0 >
  18407. ValueType value(const typename object_t::key_type& key, const ValueType& default_value) const
  18408. {
  18409. // at only works for objects
  18410. if (JSON_HEDLEY_LIKELY(is_object()))
  18411. {
  18412. // if key is found, return value and given default value otherwise
  18413. const auto it = find(key);
  18414. if (it != end())
  18415. {
  18416. return it->template get<ValueType>();
  18417. }
  18418. return default_value;
  18419. }
  18420. JSON_THROW(type_error::create(306, "cannot use value() with " + std::string(type_name()), *this));
  18421. }
  18422. /*!
  18423. @brief overload for a default value of type const char*
  18424. @copydoc basic_json::value(const typename object_t::key_type&, const ValueType&) const
  18425. */
  18426. string_t value(const typename object_t::key_type& key, const char* default_value) const
  18427. {
  18428. return value(key, string_t(default_value));
  18429. }
  18430. /*!
  18431. @brief access specified object element via JSON Pointer with default value
  18432. Returns either a copy of an object's element at the specified key @a key
  18433. or a given default value if no element with key @a key exists.
  18434. The function is basically equivalent to executing
  18435. @code {.cpp}
  18436. try {
  18437. return at(ptr);
  18438. } catch(out_of_range) {
  18439. return default_value;
  18440. }
  18441. @endcode
  18442. @note Unlike @ref at(const json_pointer&), this function does not throw
  18443. if the given key @a key was not found.
  18444. @param[in] ptr a JSON pointer to the element to access
  18445. @param[in] default_value the value to return if @a ptr found no value
  18446. @tparam ValueType type compatible to JSON values, for instance `int` for
  18447. JSON integer numbers, `bool` for JSON booleans, or `std::vector` types for
  18448. JSON arrays. Note the type of the expected value at @a key and the default
  18449. value @a default_value must be compatible.
  18450. @return copy of the element at key @a key or @a default_value if @a key
  18451. is not found
  18452. @throw type_error.302 if @a default_value does not match the type of the
  18453. value at @a ptr
  18454. @throw type_error.306 if the JSON value is not an object; in that case,
  18455. using `value()` with a key makes no sense.
  18456. @complexity Logarithmic in the size of the container.
  18457. @liveexample{The example below shows how object elements can be queried
  18458. with a default value.,basic_json__value_ptr}
  18459. @sa see @ref operator[](const json_pointer&) for unchecked access by reference
  18460. @since version 2.0.2
  18461. */
  18462. template<class ValueType, typename std::enable_if<
  18463. detail::is_getable<basic_json_t, ValueType>::value, int>::type = 0>
  18464. ValueType value(const json_pointer& ptr, const ValueType& default_value) const
  18465. {
  18466. // at only works for objects
  18467. if (JSON_HEDLEY_LIKELY(is_object()))
  18468. {
  18469. // if pointer resolves a value, return it or use default value
  18470. JSON_TRY
  18471. {
  18472. return ptr.get_checked(this).template get<ValueType>();
  18473. }
  18474. JSON_INTERNAL_CATCH (out_of_range&)
  18475. {
  18476. return default_value;
  18477. }
  18478. }
  18479. JSON_THROW(type_error::create(306, "cannot use value() with " + std::string(type_name()), *this));
  18480. }
  18481. /*!
  18482. @brief overload for a default value of type const char*
  18483. @copydoc basic_json::value(const json_pointer&, ValueType) const
  18484. */
  18485. JSON_HEDLEY_NON_NULL(3)
  18486. string_t value(const json_pointer& ptr, const char* default_value) const
  18487. {
  18488. return value(ptr, string_t(default_value));
  18489. }
  18490. /*!
  18491. @brief access the first element
  18492. Returns a reference to the first element in the container. For a JSON
  18493. container `c`, the expression `c.front()` is equivalent to `*c.begin()`.
  18494. @return In case of a structured type (array or object), a reference to the
  18495. first element is returned. In case of number, string, boolean, or binary
  18496. values, a reference to the value is returned.
  18497. @complexity Constant.
  18498. @pre The JSON value must not be `null` (would throw `std::out_of_range`)
  18499. or an empty array or object (undefined behavior, **guarded by
  18500. assertions**).
  18501. @post The JSON value remains unchanged.
  18502. @throw invalid_iterator.214 when called on `null` value
  18503. @liveexample{The following code shows an example for `front()`.,front}
  18504. @sa see @ref back() -- access the last element
  18505. @since version 1.0.0
  18506. */
  18507. reference front()
  18508. {
  18509. return *begin();
  18510. }
  18511. /*!
  18512. @copydoc basic_json::front()
  18513. */
  18514. const_reference front() const
  18515. {
  18516. return *cbegin();
  18517. }
  18518. /*!
  18519. @brief access the last element
  18520. Returns a reference to the last element in the container. For a JSON
  18521. container `c`, the expression `c.back()` is equivalent to
  18522. @code {.cpp}
  18523. auto tmp = c.end();
  18524. --tmp;
  18525. return *tmp;
  18526. @endcode
  18527. @return In case of a structured type (array or object), a reference to the
  18528. last element is returned. In case of number, string, boolean, or binary
  18529. values, a reference to the value is returned.
  18530. @complexity Constant.
  18531. @pre The JSON value must not be `null` (would throw `std::out_of_range`)
  18532. or an empty array or object (undefined behavior, **guarded by
  18533. assertions**).
  18534. @post The JSON value remains unchanged.
  18535. @throw invalid_iterator.214 when called on a `null` value. See example
  18536. below.
  18537. @liveexample{The following code shows an example for `back()`.,back}
  18538. @sa see @ref front() -- access the first element
  18539. @since version 1.0.0
  18540. */
  18541. reference back()
  18542. {
  18543. auto tmp = end();
  18544. --tmp;
  18545. return *tmp;
  18546. }
  18547. /*!
  18548. @copydoc basic_json::back()
  18549. */
  18550. const_reference back() const
  18551. {
  18552. auto tmp = cend();
  18553. --tmp;
  18554. return *tmp;
  18555. }
  18556. /*!
  18557. @brief remove element given an iterator
  18558. Removes the element specified by iterator @a pos. The iterator @a pos must
  18559. be valid and dereferenceable. Thus the `end()` iterator (which is valid,
  18560. but is not dereferenceable) cannot be used as a value for @a pos.
  18561. If called on a primitive type other than `null`, the resulting JSON value
  18562. will be `null`.
  18563. @param[in] pos iterator to the element to remove
  18564. @return Iterator following the last removed element. If the iterator @a
  18565. pos refers to the last element, the `end()` iterator is returned.
  18566. @tparam IteratorType an @ref iterator or @ref const_iterator
  18567. @post Invalidates iterators and references at or after the point of the
  18568. erase, including the `end()` iterator.
  18569. @throw type_error.307 if called on a `null` value; example: `"cannot use
  18570. erase() with null"`
  18571. @throw invalid_iterator.202 if called on an iterator which does not belong
  18572. to the current JSON value; example: `"iterator does not fit current
  18573. value"`
  18574. @throw invalid_iterator.205 if called on a primitive type with invalid
  18575. iterator (i.e., any iterator which is not `begin()`); example: `"iterator
  18576. out of range"`
  18577. @complexity The complexity depends on the type:
  18578. - objects: amortized constant
  18579. - arrays: linear in distance between @a pos and the end of the container
  18580. - strings and binary: linear in the length of the member
  18581. - other types: constant
  18582. @liveexample{The example shows the result of `erase()` for different JSON
  18583. types.,erase__IteratorType}
  18584. @sa see @ref erase(IteratorType, IteratorType) -- removes the elements in
  18585. the given range
  18586. @sa see @ref erase(const typename object_t::key_type&) -- removes the element
  18587. from an object at the given key
  18588. @sa see @ref erase(const size_type) -- removes the element from an array at
  18589. the given index
  18590. @since version 1.0.0
  18591. */
  18592. template < class IteratorType, typename std::enable_if <
  18593. std::is_same<IteratorType, typename basic_json_t::iterator>::value ||
  18594. std::is_same<IteratorType, typename basic_json_t::const_iterator>::value, int >::type
  18595. = 0 >
  18596. IteratorType erase(IteratorType pos)
  18597. {
  18598. // make sure iterator fits the current value
  18599. if (JSON_HEDLEY_UNLIKELY(this != pos.m_object))
  18600. {
  18601. JSON_THROW(invalid_iterator::create(202, "iterator does not fit current value", *this));
  18602. }
  18603. IteratorType result = end();
  18604. switch (m_type)
  18605. {
  18606. case value_t::boolean:
  18607. case value_t::number_float:
  18608. case value_t::number_integer:
  18609. case value_t::number_unsigned:
  18610. case value_t::string:
  18611. case value_t::binary:
  18612. {
  18613. if (JSON_HEDLEY_UNLIKELY(!pos.m_it.primitive_iterator.is_begin()))
  18614. {
  18615. JSON_THROW(invalid_iterator::create(205, "iterator out of range", *this));
  18616. }
  18617. if (is_string())
  18618. {
  18619. AllocatorType<string_t> alloc;
  18620. std::allocator_traits<decltype(alloc)>::destroy(alloc, m_value.string);
  18621. std::allocator_traits<decltype(alloc)>::deallocate(alloc, m_value.string, 1);
  18622. m_value.string = nullptr;
  18623. }
  18624. else if (is_binary())
  18625. {
  18626. AllocatorType<binary_t> alloc;
  18627. std::allocator_traits<decltype(alloc)>::destroy(alloc, m_value.binary);
  18628. std::allocator_traits<decltype(alloc)>::deallocate(alloc, m_value.binary, 1);
  18629. m_value.binary = nullptr;
  18630. }
  18631. m_type = value_t::null;
  18632. assert_invariant();
  18633. break;
  18634. }
  18635. case value_t::object:
  18636. {
  18637. result.m_it.object_iterator = m_value.object->erase(pos.m_it.object_iterator);
  18638. break;
  18639. }
  18640. case value_t::array:
  18641. {
  18642. result.m_it.array_iterator = m_value.array->erase(pos.m_it.array_iterator);
  18643. break;
  18644. }
  18645. case value_t::null:
  18646. case value_t::discarded:
  18647. default:
  18648. JSON_THROW(type_error::create(307, "cannot use erase() with " + std::string(type_name()), *this));
  18649. }
  18650. return result;
  18651. }
  18652. /*!
  18653. @brief remove elements given an iterator range
  18654. Removes the element specified by the range `[first; last)`. The iterator
  18655. @a first does not need to be dereferenceable if `first == last`: erasing
  18656. an empty range is a no-op.
  18657. If called on a primitive type other than `null`, the resulting JSON value
  18658. will be `null`.
  18659. @param[in] first iterator to the beginning of the range to remove
  18660. @param[in] last iterator past the end of the range to remove
  18661. @return Iterator following the last removed element. If the iterator @a
  18662. second refers to the last element, the `end()` iterator is returned.
  18663. @tparam IteratorType an @ref iterator or @ref const_iterator
  18664. @post Invalidates iterators and references at or after the point of the
  18665. erase, including the `end()` iterator.
  18666. @throw type_error.307 if called on a `null` value; example: `"cannot use
  18667. erase() with null"`
  18668. @throw invalid_iterator.203 if called on iterators which does not belong
  18669. to the current JSON value; example: `"iterators do not fit current value"`
  18670. @throw invalid_iterator.204 if called on a primitive type with invalid
  18671. iterators (i.e., if `first != begin()` and `last != end()`); example:
  18672. `"iterators out of range"`
  18673. @complexity The complexity depends on the type:
  18674. - objects: `log(size()) + std::distance(first, last)`
  18675. - arrays: linear in the distance between @a first and @a last, plus linear
  18676. in the distance between @a last and end of the container
  18677. - strings and binary: linear in the length of the member
  18678. - other types: constant
  18679. @liveexample{The example shows the result of `erase()` for different JSON
  18680. types.,erase__IteratorType_IteratorType}
  18681. @sa see @ref erase(IteratorType) -- removes the element at a given position
  18682. @sa see @ref erase(const typename object_t::key_type&) -- removes the element
  18683. from an object at the given key
  18684. @sa see @ref erase(const size_type) -- removes the element from an array at
  18685. the given index
  18686. @since version 1.0.0
  18687. */
  18688. template < class IteratorType, typename std::enable_if <
  18689. std::is_same<IteratorType, typename basic_json_t::iterator>::value ||
  18690. std::is_same<IteratorType, typename basic_json_t::const_iterator>::value, int >::type
  18691. = 0 >
  18692. IteratorType erase(IteratorType first, IteratorType last)
  18693. {
  18694. // make sure iterator fits the current value
  18695. if (JSON_HEDLEY_UNLIKELY(this != first.m_object || this != last.m_object))
  18696. {
  18697. JSON_THROW(invalid_iterator::create(203, "iterators do not fit current value", *this));
  18698. }
  18699. IteratorType result = end();
  18700. switch (m_type)
  18701. {
  18702. case value_t::boolean:
  18703. case value_t::number_float:
  18704. case value_t::number_integer:
  18705. case value_t::number_unsigned:
  18706. case value_t::string:
  18707. case value_t::binary:
  18708. {
  18709. if (JSON_HEDLEY_LIKELY(!first.m_it.primitive_iterator.is_begin()
  18710. || !last.m_it.primitive_iterator.is_end()))
  18711. {
  18712. JSON_THROW(invalid_iterator::create(204, "iterators out of range", *this));
  18713. }
  18714. if (is_string())
  18715. {
  18716. AllocatorType<string_t> alloc;
  18717. std::allocator_traits<decltype(alloc)>::destroy(alloc, m_value.string);
  18718. std::allocator_traits<decltype(alloc)>::deallocate(alloc, m_value.string, 1);
  18719. m_value.string = nullptr;
  18720. }
  18721. else if (is_binary())
  18722. {
  18723. AllocatorType<binary_t> alloc;
  18724. std::allocator_traits<decltype(alloc)>::destroy(alloc, m_value.binary);
  18725. std::allocator_traits<decltype(alloc)>::deallocate(alloc, m_value.binary, 1);
  18726. m_value.binary = nullptr;
  18727. }
  18728. m_type = value_t::null;
  18729. assert_invariant();
  18730. break;
  18731. }
  18732. case value_t::object:
  18733. {
  18734. result.m_it.object_iterator = m_value.object->erase(first.m_it.object_iterator,
  18735. last.m_it.object_iterator);
  18736. break;
  18737. }
  18738. case value_t::array:
  18739. {
  18740. result.m_it.array_iterator = m_value.array->erase(first.m_it.array_iterator,
  18741. last.m_it.array_iterator);
  18742. break;
  18743. }
  18744. case value_t::null:
  18745. case value_t::discarded:
  18746. default:
  18747. JSON_THROW(type_error::create(307, "cannot use erase() with " + std::string(type_name()), *this));
  18748. }
  18749. return result;
  18750. }
  18751. /*!
  18752. @brief remove element from a JSON object given a key
  18753. Removes elements from a JSON object with the key value @a key.
  18754. @param[in] key value of the elements to remove
  18755. @return Number of elements removed. If @a ObjectType is the default
  18756. `std::map` type, the return value will always be `0` (@a key was not
  18757. found) or `1` (@a key was found).
  18758. @post References and iterators to the erased elements are invalidated.
  18759. Other references and iterators are not affected.
  18760. @throw type_error.307 when called on a type other than JSON object;
  18761. example: `"cannot use erase() with null"`
  18762. @complexity `log(size()) + count(key)`
  18763. @liveexample{The example shows the effect of `erase()`.,erase__key_type}
  18764. @sa see @ref erase(IteratorType) -- removes the element at a given position
  18765. @sa see @ref erase(IteratorType, IteratorType) -- removes the elements in
  18766. the given range
  18767. @sa see @ref erase(const size_type) -- removes the element from an array at
  18768. the given index
  18769. @since version 1.0.0
  18770. */
  18771. size_type erase(const typename object_t::key_type& key)
  18772. {
  18773. // this erase only works for objects
  18774. if (JSON_HEDLEY_LIKELY(is_object()))
  18775. {
  18776. return m_value.object->erase(key);
  18777. }
  18778. JSON_THROW(type_error::create(307, "cannot use erase() with " + std::string(type_name()), *this));
  18779. }
  18780. /*!
  18781. @brief remove element from a JSON array given an index
  18782. Removes element from a JSON array at the index @a idx.
  18783. @param[in] idx index of the element to remove
  18784. @throw type_error.307 when called on a type other than JSON object;
  18785. example: `"cannot use erase() with null"`
  18786. @throw out_of_range.401 when `idx >= size()`; example: `"array index 17
  18787. is out of range"`
  18788. @complexity Linear in distance between @a idx and the end of the container.
  18789. @liveexample{The example shows the effect of `erase()`.,erase__size_type}
  18790. @sa see @ref erase(IteratorType) -- removes the element at a given position
  18791. @sa see @ref erase(IteratorType, IteratorType) -- removes the elements in
  18792. the given range
  18793. @sa see @ref erase(const typename object_t::key_type&) -- removes the element
  18794. from an object at the given key
  18795. @since version 1.0.0
  18796. */
  18797. void erase(const size_type idx)
  18798. {
  18799. // this erase only works for arrays
  18800. if (JSON_HEDLEY_LIKELY(is_array()))
  18801. {
  18802. if (JSON_HEDLEY_UNLIKELY(idx >= size()))
  18803. {
  18804. JSON_THROW(out_of_range::create(401, "array index " + std::to_string(idx) + " is out of range", *this));
  18805. }
  18806. m_value.array->erase(m_value.array->begin() + static_cast<difference_type>(idx));
  18807. }
  18808. else
  18809. {
  18810. JSON_THROW(type_error::create(307, "cannot use erase() with " + std::string(type_name()), *this));
  18811. }
  18812. }
  18813. /// @}
  18814. ////////////
  18815. // lookup //
  18816. ////////////
  18817. /// @name lookup
  18818. /// @{
  18819. /*!
  18820. @brief find an element in a JSON object
  18821. Finds an element in a JSON object with key equivalent to @a key. If the
  18822. element is not found or the JSON value is not an object, end() is
  18823. returned.
  18824. @note This method always returns @ref end() when executed on a JSON type
  18825. that is not an object.
  18826. @param[in] key key value of the element to search for.
  18827. @return Iterator to an element with key equivalent to @a key. If no such
  18828. element is found or the JSON value is not an object, past-the-end (see
  18829. @ref end()) iterator is returned.
  18830. @complexity Logarithmic in the size of the JSON object.
  18831. @liveexample{The example shows how `find()` is used.,find__key_type}
  18832. @sa see @ref contains(KeyT&&) const -- checks whether a key exists
  18833. @since version 1.0.0
  18834. */
  18835. template<typename KeyT>
  18836. iterator find(KeyT&& key)
  18837. {
  18838. auto result = end();
  18839. if (is_object())
  18840. {
  18841. result.m_it.object_iterator = m_value.object->find(std::forward<KeyT>(key));
  18842. }
  18843. return result;
  18844. }
  18845. /*!
  18846. @brief find an element in a JSON object
  18847. @copydoc find(KeyT&&)
  18848. */
  18849. template<typename KeyT>
  18850. const_iterator find(KeyT&& key) const
  18851. {
  18852. auto result = cend();
  18853. if (is_object())
  18854. {
  18855. result.m_it.object_iterator = m_value.object->find(std::forward<KeyT>(key));
  18856. }
  18857. return result;
  18858. }
  18859. /*!
  18860. @brief returns the number of occurrences of a key in a JSON object
  18861. Returns the number of elements with key @a key. If ObjectType is the
  18862. default `std::map` type, the return value will always be `0` (@a key was
  18863. not found) or `1` (@a key was found).
  18864. @note This method always returns `0` when executed on a JSON type that is
  18865. not an object.
  18866. @param[in] key key value of the element to count
  18867. @return Number of elements with key @a key. If the JSON value is not an
  18868. object, the return value will be `0`.
  18869. @complexity Logarithmic in the size of the JSON object.
  18870. @liveexample{The example shows how `count()` is used.,count}
  18871. @since version 1.0.0
  18872. */
  18873. template<typename KeyT>
  18874. size_type count(KeyT&& key) const
  18875. {
  18876. // return 0 for all nonobject types
  18877. return is_object() ? m_value.object->count(std::forward<KeyT>(key)) : 0;
  18878. }
  18879. /*!
  18880. @brief check the existence of an element in a JSON object
  18881. Check whether an element exists in a JSON object with key equivalent to
  18882. @a key. If the element is not found or the JSON value is not an object,
  18883. false is returned.
  18884. @note This method always returns false when executed on a JSON type
  18885. that is not an object.
  18886. @param[in] key key value to check its existence.
  18887. @return true if an element with specified @a key exists. If no such
  18888. element with such key is found or the JSON value is not an object,
  18889. false is returned.
  18890. @complexity Logarithmic in the size of the JSON object.
  18891. @liveexample{The following code shows an example for `contains()`.,contains}
  18892. @sa see @ref find(KeyT&&) -- returns an iterator to an object element
  18893. @sa see @ref contains(const json_pointer&) const -- checks the existence for a JSON pointer
  18894. @since version 3.6.0
  18895. */
  18896. template < typename KeyT, typename std::enable_if <
  18897. !std::is_same<typename std::decay<KeyT>::type, json_pointer>::value, int >::type = 0 >
  18898. bool contains(KeyT && key) const
  18899. {
  18900. return is_object() && m_value.object->find(std::forward<KeyT>(key)) != m_value.object->end();
  18901. }
  18902. /*!
  18903. @brief check the existence of an element in a JSON object given a JSON pointer
  18904. Check whether the given JSON pointer @a ptr can be resolved in the current
  18905. JSON value.
  18906. @note This method can be executed on any JSON value type.
  18907. @param[in] ptr JSON pointer to check its existence.
  18908. @return true if the JSON pointer can be resolved to a stored value, false
  18909. otherwise.
  18910. @post If `j.contains(ptr)` returns true, it is safe to call `j[ptr]`.
  18911. @throw parse_error.106 if an array index begins with '0'
  18912. @throw parse_error.109 if an array index was not a number
  18913. @complexity Logarithmic in the size of the JSON object.
  18914. @liveexample{The following code shows an example for `contains()`.,contains_json_pointer}
  18915. @sa see @ref contains(KeyT &&) const -- checks the existence of a key
  18916. @since version 3.7.0
  18917. */
  18918. bool contains(const json_pointer& ptr) const
  18919. {
  18920. return ptr.contains(this);
  18921. }
  18922. /// @}
  18923. ///////////////
  18924. // iterators //
  18925. ///////////////
  18926. /// @name iterators
  18927. /// @{
  18928. /*!
  18929. @brief returns an iterator to the first element
  18930. Returns an iterator to the first element.
  18931. @image html range-begin-end.svg "Illustration from cppreference.com"
  18932. @return iterator to the first element
  18933. @complexity Constant.
  18934. @requirement This function helps `basic_json` satisfying the
  18935. [Container](https://en.cppreference.com/w/cpp/named_req/Container)
  18936. requirements:
  18937. - The complexity is constant.
  18938. @liveexample{The following code shows an example for `begin()`.,begin}
  18939. @sa see @ref cbegin() -- returns a const iterator to the beginning
  18940. @sa see @ref end() -- returns an iterator to the end
  18941. @sa see @ref cend() -- returns a const iterator to the end
  18942. @since version 1.0.0
  18943. */
  18944. iterator begin() noexcept
  18945. {
  18946. iterator result(this);
  18947. result.set_begin();
  18948. return result;
  18949. }
  18950. /*!
  18951. @copydoc basic_json::cbegin()
  18952. */
  18953. const_iterator begin() const noexcept
  18954. {
  18955. return cbegin();
  18956. }
  18957. /*!
  18958. @brief returns a const iterator to the first element
  18959. Returns a const iterator to the first element.
  18960. @image html range-begin-end.svg "Illustration from cppreference.com"
  18961. @return const iterator to the first element
  18962. @complexity Constant.
  18963. @requirement This function helps `basic_json` satisfying the
  18964. [Container](https://en.cppreference.com/w/cpp/named_req/Container)
  18965. requirements:
  18966. - The complexity is constant.
  18967. - Has the semantics of `const_cast<const basic_json&>(*this).begin()`.
  18968. @liveexample{The following code shows an example for `cbegin()`.,cbegin}
  18969. @sa see @ref begin() -- returns an iterator to the beginning
  18970. @sa see @ref end() -- returns an iterator to the end
  18971. @sa see @ref cend() -- returns a const iterator to the end
  18972. @since version 1.0.0
  18973. */
  18974. const_iterator cbegin() const noexcept
  18975. {
  18976. const_iterator result(this);
  18977. result.set_begin();
  18978. return result;
  18979. }
  18980. /*!
  18981. @brief returns an iterator to one past the last element
  18982. Returns an iterator to one past the last element.
  18983. @image html range-begin-end.svg "Illustration from cppreference.com"
  18984. @return iterator one past the last element
  18985. @complexity Constant.
  18986. @requirement This function helps `basic_json` satisfying the
  18987. [Container](https://en.cppreference.com/w/cpp/named_req/Container)
  18988. requirements:
  18989. - The complexity is constant.
  18990. @liveexample{The following code shows an example for `end()`.,end}
  18991. @sa see @ref cend() -- returns a const iterator to the end
  18992. @sa see @ref begin() -- returns an iterator to the beginning
  18993. @sa see @ref cbegin() -- returns a const iterator to the beginning
  18994. @since version 1.0.0
  18995. */
  18996. iterator end() noexcept
  18997. {
  18998. iterator result(this);
  18999. result.set_end();
  19000. return result;
  19001. }
  19002. /*!
  19003. @copydoc basic_json::cend()
  19004. */
  19005. const_iterator end() const noexcept
  19006. {
  19007. return cend();
  19008. }
  19009. /*!
  19010. @brief returns a const iterator to one past the last element
  19011. Returns a const iterator to one past the last element.
  19012. @image html range-begin-end.svg "Illustration from cppreference.com"
  19013. @return const iterator one past the last element
  19014. @complexity Constant.
  19015. @requirement This function helps `basic_json` satisfying the
  19016. [Container](https://en.cppreference.com/w/cpp/named_req/Container)
  19017. requirements:
  19018. - The complexity is constant.
  19019. - Has the semantics of `const_cast<const basic_json&>(*this).end()`.
  19020. @liveexample{The following code shows an example for `cend()`.,cend}
  19021. @sa see @ref end() -- returns an iterator to the end
  19022. @sa see @ref begin() -- returns an iterator to the beginning
  19023. @sa see @ref cbegin() -- returns a const iterator to the beginning
  19024. @since version 1.0.0
  19025. */
  19026. const_iterator cend() const noexcept
  19027. {
  19028. const_iterator result(this);
  19029. result.set_end();
  19030. return result;
  19031. }
  19032. /*!
  19033. @brief returns an iterator to the reverse-beginning
  19034. Returns an iterator to the reverse-beginning; that is, the last element.
  19035. @image html range-rbegin-rend.svg "Illustration from cppreference.com"
  19036. @complexity Constant.
  19037. @requirement This function helps `basic_json` satisfying the
  19038. [ReversibleContainer](https://en.cppreference.com/w/cpp/named_req/ReversibleContainer)
  19039. requirements:
  19040. - The complexity is constant.
  19041. - Has the semantics of `reverse_iterator(end())`.
  19042. @liveexample{The following code shows an example for `rbegin()`.,rbegin}
  19043. @sa see @ref crbegin() -- returns a const reverse iterator to the beginning
  19044. @sa see @ref rend() -- returns a reverse iterator to the end
  19045. @sa see @ref crend() -- returns a const reverse iterator to the end
  19046. @since version 1.0.0
  19047. */
  19048. reverse_iterator rbegin() noexcept
  19049. {
  19050. return reverse_iterator(end());
  19051. }
  19052. /*!
  19053. @copydoc basic_json::crbegin()
  19054. */
  19055. const_reverse_iterator rbegin() const noexcept
  19056. {
  19057. return crbegin();
  19058. }
  19059. /*!
  19060. @brief returns an iterator to the reverse-end
  19061. Returns an iterator to the reverse-end; that is, one before the first
  19062. element.
  19063. @image html range-rbegin-rend.svg "Illustration from cppreference.com"
  19064. @complexity Constant.
  19065. @requirement This function helps `basic_json` satisfying the
  19066. [ReversibleContainer](https://en.cppreference.com/w/cpp/named_req/ReversibleContainer)
  19067. requirements:
  19068. - The complexity is constant.
  19069. - Has the semantics of `reverse_iterator(begin())`.
  19070. @liveexample{The following code shows an example for `rend()`.,rend}
  19071. @sa see @ref crend() -- returns a const reverse iterator to the end
  19072. @sa see @ref rbegin() -- returns a reverse iterator to the beginning
  19073. @sa see @ref crbegin() -- returns a const reverse iterator to the beginning
  19074. @since version 1.0.0
  19075. */
  19076. reverse_iterator rend() noexcept
  19077. {
  19078. return reverse_iterator(begin());
  19079. }
  19080. /*!
  19081. @copydoc basic_json::crend()
  19082. */
  19083. const_reverse_iterator rend() const noexcept
  19084. {
  19085. return crend();
  19086. }
  19087. /*!
  19088. @brief returns a const reverse iterator to the last element
  19089. Returns a const iterator to the reverse-beginning; that is, the last
  19090. element.
  19091. @image html range-rbegin-rend.svg "Illustration from cppreference.com"
  19092. @complexity Constant.
  19093. @requirement This function helps `basic_json` satisfying the
  19094. [ReversibleContainer](https://en.cppreference.com/w/cpp/named_req/ReversibleContainer)
  19095. requirements:
  19096. - The complexity is constant.
  19097. - Has the semantics of `const_cast<const basic_json&>(*this).rbegin()`.
  19098. @liveexample{The following code shows an example for `crbegin()`.,crbegin}
  19099. @sa see @ref rbegin() -- returns a reverse iterator to the beginning
  19100. @sa see @ref rend() -- returns a reverse iterator to the end
  19101. @sa see @ref crend() -- returns a const reverse iterator to the end
  19102. @since version 1.0.0
  19103. */
  19104. const_reverse_iterator crbegin() const noexcept
  19105. {
  19106. return const_reverse_iterator(cend());
  19107. }
  19108. /*!
  19109. @brief returns a const reverse iterator to one before the first
  19110. Returns a const reverse iterator to the reverse-end; that is, one before
  19111. the first element.
  19112. @image html range-rbegin-rend.svg "Illustration from cppreference.com"
  19113. @complexity Constant.
  19114. @requirement This function helps `basic_json` satisfying the
  19115. [ReversibleContainer](https://en.cppreference.com/w/cpp/named_req/ReversibleContainer)
  19116. requirements:
  19117. - The complexity is constant.
  19118. - Has the semantics of `const_cast<const basic_json&>(*this).rend()`.
  19119. @liveexample{The following code shows an example for `crend()`.,crend}
  19120. @sa see @ref rend() -- returns a reverse iterator to the end
  19121. @sa see @ref rbegin() -- returns a reverse iterator to the beginning
  19122. @sa see @ref crbegin() -- returns a const reverse iterator to the beginning
  19123. @since version 1.0.0
  19124. */
  19125. const_reverse_iterator crend() const noexcept
  19126. {
  19127. return const_reverse_iterator(cbegin());
  19128. }
  19129. public:
  19130. /*!
  19131. @brief wrapper to access iterator member functions in range-based for
  19132. This function allows to access @ref iterator::key() and @ref
  19133. iterator::value() during range-based for loops. In these loops, a
  19134. reference to the JSON values is returned, so there is no access to the
  19135. underlying iterator.
  19136. For loop without iterator_wrapper:
  19137. @code{cpp}
  19138. for (auto it = j_object.begin(); it != j_object.end(); ++it)
  19139. {
  19140. std::cout << "key: " << it.key() << ", value:" << it.value() << '\n';
  19141. }
  19142. @endcode
  19143. Range-based for loop without iterator proxy:
  19144. @code{cpp}
  19145. for (auto it : j_object)
  19146. {
  19147. // "it" is of type json::reference and has no key() member
  19148. std::cout << "value: " << it << '\n';
  19149. }
  19150. @endcode
  19151. Range-based for loop with iterator proxy:
  19152. @code{cpp}
  19153. for (auto it : json::iterator_wrapper(j_object))
  19154. {
  19155. std::cout << "key: " << it.key() << ", value:" << it.value() << '\n';
  19156. }
  19157. @endcode
  19158. @note When iterating over an array, `key()` will return the index of the
  19159. element as string (see example).
  19160. @param[in] ref reference to a JSON value
  19161. @return iteration proxy object wrapping @a ref with an interface to use in
  19162. range-based for loops
  19163. @liveexample{The following code shows how the wrapper is used,iterator_wrapper}
  19164. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  19165. changes in the JSON value.
  19166. @complexity Constant.
  19167. @note The name of this function is not yet final and may change in the
  19168. future.
  19169. @deprecated This stream operator is deprecated and will be removed in
  19170. future 4.0.0 of the library. Please use @ref items() instead;
  19171. that is, replace `json::iterator_wrapper(j)` with `j.items()`.
  19172. */
  19173. JSON_HEDLEY_DEPRECATED_FOR(3.1.0, items())
  19174. static iteration_proxy<iterator> iterator_wrapper(reference ref) noexcept
  19175. {
  19176. return ref.items();
  19177. }
  19178. /*!
  19179. @copydoc iterator_wrapper(reference)
  19180. */
  19181. JSON_HEDLEY_DEPRECATED_FOR(3.1.0, items())
  19182. static iteration_proxy<const_iterator> iterator_wrapper(const_reference ref) noexcept
  19183. {
  19184. return ref.items();
  19185. }
  19186. /*!
  19187. @brief helper to access iterator member functions in range-based for
  19188. This function allows to access @ref iterator::key() and @ref
  19189. iterator::value() during range-based for loops. In these loops, a
  19190. reference to the JSON values is returned, so there is no access to the
  19191. underlying iterator.
  19192. For loop without `items()` function:
  19193. @code{cpp}
  19194. for (auto it = j_object.begin(); it != j_object.end(); ++it)
  19195. {
  19196. std::cout << "key: " << it.key() << ", value:" << it.value() << '\n';
  19197. }
  19198. @endcode
  19199. Range-based for loop without `items()` function:
  19200. @code{cpp}
  19201. for (auto it : j_object)
  19202. {
  19203. // "it" is of type json::reference and has no key() member
  19204. std::cout << "value: " << it << '\n';
  19205. }
  19206. @endcode
  19207. Range-based for loop with `items()` function:
  19208. @code{cpp}
  19209. for (auto& el : j_object.items())
  19210. {
  19211. std::cout << "key: " << el.key() << ", value:" << el.value() << '\n';
  19212. }
  19213. @endcode
  19214. The `items()` function also allows to use
  19215. [structured bindings](https://en.cppreference.com/w/cpp/language/structured_binding)
  19216. (C++17):
  19217. @code{cpp}
  19218. for (auto& [key, val] : j_object.items())
  19219. {
  19220. std::cout << "key: " << key << ", value:" << val << '\n';
  19221. }
  19222. @endcode
  19223. @note When iterating over an array, `key()` will return the index of the
  19224. element as string (see example). For primitive types (e.g., numbers),
  19225. `key()` returns an empty string.
  19226. @warning Using `items()` on temporary objects is dangerous. Make sure the
  19227. object's lifetime exeeds the iteration. See
  19228. <https://github.com/nlohmann/json/issues/2040> for more
  19229. information.
  19230. @return iteration proxy object wrapping @a ref with an interface to use in
  19231. range-based for loops
  19232. @liveexample{The following code shows how the function is used.,items}
  19233. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  19234. changes in the JSON value.
  19235. @complexity Constant.
  19236. @since version 3.1.0, structured bindings support since 3.5.0.
  19237. */
  19238. iteration_proxy<iterator> items() noexcept
  19239. {
  19240. return iteration_proxy<iterator>(*this);
  19241. }
  19242. /*!
  19243. @copydoc items()
  19244. */
  19245. iteration_proxy<const_iterator> items() const noexcept
  19246. {
  19247. return iteration_proxy<const_iterator>(*this);
  19248. }
  19249. /// @}
  19250. //////////////
  19251. // capacity //
  19252. //////////////
  19253. /// @name capacity
  19254. /// @{
  19255. /*!
  19256. @brief checks whether the container is empty.
  19257. Checks if a JSON value has no elements (i.e. whether its @ref size is `0`).
  19258. @return The return value depends on the different types and is
  19259. defined as follows:
  19260. Value type | return value
  19261. ----------- | -------------
  19262. null | `true`
  19263. boolean | `false`
  19264. string | `false`
  19265. number | `false`
  19266. binary | `false`
  19267. object | result of function `object_t::empty()`
  19268. array | result of function `array_t::empty()`
  19269. @liveexample{The following code uses `empty()` to check if a JSON
  19270. object contains any elements.,empty}
  19271. @complexity Constant, as long as @ref array_t and @ref object_t satisfy
  19272. the Container concept; that is, their `empty()` functions have constant
  19273. complexity.
  19274. @iterators No changes.
  19275. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  19276. @note This function does not return whether a string stored as JSON value
  19277. is empty - it returns whether the JSON container itself is empty which is
  19278. false in the case of a string.
  19279. @requirement This function helps `basic_json` satisfying the
  19280. [Container](https://en.cppreference.com/w/cpp/named_req/Container)
  19281. requirements:
  19282. - The complexity is constant.
  19283. - Has the semantics of `begin() == end()`.
  19284. @sa see @ref size() -- returns the number of elements
  19285. @since version 1.0.0
  19286. */
  19287. bool empty() const noexcept
  19288. {
  19289. switch (m_type)
  19290. {
  19291. case value_t::null:
  19292. {
  19293. // null values are empty
  19294. return true;
  19295. }
  19296. case value_t::array:
  19297. {
  19298. // delegate call to array_t::empty()
  19299. return m_value.array->empty();
  19300. }
  19301. case value_t::object:
  19302. {
  19303. // delegate call to object_t::empty()
  19304. return m_value.object->empty();
  19305. }
  19306. case value_t::string:
  19307. case value_t::boolean:
  19308. case value_t::number_integer:
  19309. case value_t::number_unsigned:
  19310. case value_t::number_float:
  19311. case value_t::binary:
  19312. case value_t::discarded:
  19313. default:
  19314. {
  19315. // all other types are nonempty
  19316. return false;
  19317. }
  19318. }
  19319. }
  19320. /*!
  19321. @brief returns the number of elements
  19322. Returns the number of elements in a JSON value.
  19323. @return The return value depends on the different types and is
  19324. defined as follows:
  19325. Value type | return value
  19326. ----------- | -------------
  19327. null | `0`
  19328. boolean | `1`
  19329. string | `1`
  19330. number | `1`
  19331. binary | `1`
  19332. object | result of function object_t::size()
  19333. array | result of function array_t::size()
  19334. @liveexample{The following code calls `size()` on the different value
  19335. types.,size}
  19336. @complexity Constant, as long as @ref array_t and @ref object_t satisfy
  19337. the Container concept; that is, their size() functions have constant
  19338. complexity.
  19339. @iterators No changes.
  19340. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  19341. @note This function does not return the length of a string stored as JSON
  19342. value - it returns the number of elements in the JSON value which is 1 in
  19343. the case of a string.
  19344. @requirement This function helps `basic_json` satisfying the
  19345. [Container](https://en.cppreference.com/w/cpp/named_req/Container)
  19346. requirements:
  19347. - The complexity is constant.
  19348. - Has the semantics of `std::distance(begin(), end())`.
  19349. @sa see @ref empty() -- checks whether the container is empty
  19350. @sa see @ref max_size() -- returns the maximal number of elements
  19351. @since version 1.0.0
  19352. */
  19353. size_type size() const noexcept
  19354. {
  19355. switch (m_type)
  19356. {
  19357. case value_t::null:
  19358. {
  19359. // null values are empty
  19360. return 0;
  19361. }
  19362. case value_t::array:
  19363. {
  19364. // delegate call to array_t::size()
  19365. return m_value.array->size();
  19366. }
  19367. case value_t::object:
  19368. {
  19369. // delegate call to object_t::size()
  19370. return m_value.object->size();
  19371. }
  19372. case value_t::string:
  19373. case value_t::boolean:
  19374. case value_t::number_integer:
  19375. case value_t::number_unsigned:
  19376. case value_t::number_float:
  19377. case value_t::binary:
  19378. case value_t::discarded:
  19379. default:
  19380. {
  19381. // all other types have size 1
  19382. return 1;
  19383. }
  19384. }
  19385. }
  19386. /*!
  19387. @brief returns the maximum possible number of elements
  19388. Returns the maximum number of elements a JSON value is able to hold due to
  19389. system or library implementation limitations, i.e. `std::distance(begin(),
  19390. end())` for the JSON value.
  19391. @return The return value depends on the different types and is
  19392. defined as follows:
  19393. Value type | return value
  19394. ----------- | -------------
  19395. null | `0` (same as `size()`)
  19396. boolean | `1` (same as `size()`)
  19397. string | `1` (same as `size()`)
  19398. number | `1` (same as `size()`)
  19399. binary | `1` (same as `size()`)
  19400. object | result of function `object_t::max_size()`
  19401. array | result of function `array_t::max_size()`
  19402. @liveexample{The following code calls `max_size()` on the different value
  19403. types. Note the output is implementation specific.,max_size}
  19404. @complexity Constant, as long as @ref array_t and @ref object_t satisfy
  19405. the Container concept; that is, their `max_size()` functions have constant
  19406. complexity.
  19407. @iterators No changes.
  19408. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  19409. @requirement This function helps `basic_json` satisfying the
  19410. [Container](https://en.cppreference.com/w/cpp/named_req/Container)
  19411. requirements:
  19412. - The complexity is constant.
  19413. - Has the semantics of returning `b.size()` where `b` is the largest
  19414. possible JSON value.
  19415. @sa see @ref size() -- returns the number of elements
  19416. @since version 1.0.0
  19417. */
  19418. size_type max_size() const noexcept
  19419. {
  19420. switch (m_type)
  19421. {
  19422. case value_t::array:
  19423. {
  19424. // delegate call to array_t::max_size()
  19425. return m_value.array->max_size();
  19426. }
  19427. case value_t::object:
  19428. {
  19429. // delegate call to object_t::max_size()
  19430. return m_value.object->max_size();
  19431. }
  19432. case value_t::null:
  19433. case value_t::string:
  19434. case value_t::boolean:
  19435. case value_t::number_integer:
  19436. case value_t::number_unsigned:
  19437. case value_t::number_float:
  19438. case value_t::binary:
  19439. case value_t::discarded:
  19440. default:
  19441. {
  19442. // all other types have max_size() == size()
  19443. return size();
  19444. }
  19445. }
  19446. }
  19447. /// @}
  19448. ///////////////
  19449. // modifiers //
  19450. ///////////////
  19451. /// @name modifiers
  19452. /// @{
  19453. /*!
  19454. @brief clears the contents
  19455. Clears the content of a JSON value and resets it to the default value as
  19456. if @ref basic_json(value_t) would have been called with the current value
  19457. type from @ref type():
  19458. Value type | initial value
  19459. ----------- | -------------
  19460. null | `null`
  19461. boolean | `false`
  19462. string | `""`
  19463. number | `0`
  19464. binary | An empty byte vector
  19465. object | `{}`
  19466. array | `[]`
  19467. @post Has the same effect as calling
  19468. @code {.cpp}
  19469. *this = basic_json(type());
  19470. @endcode
  19471. @liveexample{The example below shows the effect of `clear()` to different
  19472. JSON types.,clear}
  19473. @complexity Linear in the size of the JSON value.
  19474. @iterators All iterators, pointers and references related to this container
  19475. are invalidated.
  19476. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  19477. @sa see @ref basic_json(value_t) -- constructor that creates an object with the
  19478. same value than calling `clear()`
  19479. @since version 1.0.0
  19480. */
  19481. void clear() noexcept
  19482. {
  19483. switch (m_type)
  19484. {
  19485. case value_t::number_integer:
  19486. {
  19487. m_value.number_integer = 0;
  19488. break;
  19489. }
  19490. case value_t::number_unsigned:
  19491. {
  19492. m_value.number_unsigned = 0;
  19493. break;
  19494. }
  19495. case value_t::number_float:
  19496. {
  19497. m_value.number_float = 0.0;
  19498. break;
  19499. }
  19500. case value_t::boolean:
  19501. {
  19502. m_value.boolean = false;
  19503. break;
  19504. }
  19505. case value_t::string:
  19506. {
  19507. m_value.string->clear();
  19508. break;
  19509. }
  19510. case value_t::binary:
  19511. {
  19512. m_value.binary->clear();
  19513. break;
  19514. }
  19515. case value_t::array:
  19516. {
  19517. m_value.array->clear();
  19518. break;
  19519. }
  19520. case value_t::object:
  19521. {
  19522. m_value.object->clear();
  19523. break;
  19524. }
  19525. case value_t::null:
  19526. case value_t::discarded:
  19527. default:
  19528. break;
  19529. }
  19530. }
  19531. /*!
  19532. @brief add an object to an array
  19533. Appends the given element @a val to the end of the JSON value. If the
  19534. function is called on a JSON null value, an empty array is created before
  19535. appending @a val.
  19536. @param[in] val the value to add to the JSON array
  19537. @throw type_error.308 when called on a type other than JSON array or
  19538. null; example: `"cannot use push_back() with number"`
  19539. @complexity Amortized constant.
  19540. @liveexample{The example shows how `push_back()` and `+=` can be used to
  19541. add elements to a JSON array. Note how the `null` value was silently
  19542. converted to a JSON array.,push_back}
  19543. @since version 1.0.0
  19544. */
  19545. void push_back(basic_json&& val)
  19546. {
  19547. // push_back only works for null objects or arrays
  19548. if (JSON_HEDLEY_UNLIKELY(!(is_null() || is_array())))
  19549. {
  19550. JSON_THROW(type_error::create(308, "cannot use push_back() with " + std::string(type_name()), *this));
  19551. }
  19552. // transform null object into an array
  19553. if (is_null())
  19554. {
  19555. m_type = value_t::array;
  19556. m_value = value_t::array;
  19557. assert_invariant();
  19558. }
  19559. // add element to array (move semantics)
  19560. const auto old_capacity = m_value.array->capacity();
  19561. m_value.array->push_back(std::move(val));
  19562. set_parent(m_value.array->back(), old_capacity);
  19563. // if val is moved from, basic_json move constructor marks it null so we do not call the destructor
  19564. }
  19565. /*!
  19566. @brief add an object to an array
  19567. @copydoc push_back(basic_json&&)
  19568. */
  19569. reference operator+=(basic_json&& val)
  19570. {
  19571. push_back(std::move(val));
  19572. return *this;
  19573. }
  19574. /*!
  19575. @brief add an object to an array
  19576. @copydoc push_back(basic_json&&)
  19577. */
  19578. void push_back(const basic_json& val)
  19579. {
  19580. // push_back only works for null objects or arrays
  19581. if (JSON_HEDLEY_UNLIKELY(!(is_null() || is_array())))
  19582. {
  19583. JSON_THROW(type_error::create(308, "cannot use push_back() with " + std::string(type_name()), *this));
  19584. }
  19585. // transform null object into an array
  19586. if (is_null())
  19587. {
  19588. m_type = value_t::array;
  19589. m_value = value_t::array;
  19590. assert_invariant();
  19591. }
  19592. // add element to array
  19593. const auto old_capacity = m_value.array->capacity();
  19594. m_value.array->push_back(val);
  19595. set_parent(m_value.array->back(), old_capacity);
  19596. }
  19597. /*!
  19598. @brief add an object to an array
  19599. @copydoc push_back(basic_json&&)
  19600. */
  19601. reference operator+=(const basic_json& val)
  19602. {
  19603. push_back(val);
  19604. return *this;
  19605. }
  19606. /*!
  19607. @brief add an object to an object
  19608. Inserts the given element @a val to the JSON object. If the function is
  19609. called on a JSON null value, an empty object is created before inserting
  19610. @a val.
  19611. @param[in] val the value to add to the JSON object
  19612. @throw type_error.308 when called on a type other than JSON object or
  19613. null; example: `"cannot use push_back() with number"`
  19614. @complexity Logarithmic in the size of the container, O(log(`size()`)).
  19615. @liveexample{The example shows how `push_back()` and `+=` can be used to
  19616. add elements to a JSON object. Note how the `null` value was silently
  19617. converted to a JSON object.,push_back__object_t__value}
  19618. @since version 1.0.0
  19619. */
  19620. void push_back(const typename object_t::value_type& val)
  19621. {
  19622. // push_back only works for null objects or objects
  19623. if (JSON_HEDLEY_UNLIKELY(!(is_null() || is_object())))
  19624. {
  19625. JSON_THROW(type_error::create(308, "cannot use push_back() with " + std::string(type_name()), *this));
  19626. }
  19627. // transform null object into an object
  19628. if (is_null())
  19629. {
  19630. m_type = value_t::object;
  19631. m_value = value_t::object;
  19632. assert_invariant();
  19633. }
  19634. // add element to object
  19635. auto res = m_value.object->insert(val);
  19636. set_parent(res.first->second);
  19637. }
  19638. /*!
  19639. @brief add an object to an object
  19640. @copydoc push_back(const typename object_t::value_type&)
  19641. */
  19642. reference operator+=(const typename object_t::value_type& val)
  19643. {
  19644. push_back(val);
  19645. return *this;
  19646. }
  19647. /*!
  19648. @brief add an object to an object
  19649. This function allows to use `push_back` with an initializer list. In case
  19650. 1. the current value is an object,
  19651. 2. the initializer list @a init contains only two elements, and
  19652. 3. the first element of @a init is a string,
  19653. @a init is converted into an object element and added using
  19654. @ref push_back(const typename object_t::value_type&). Otherwise, @a init
  19655. is converted to a JSON value and added using @ref push_back(basic_json&&).
  19656. @param[in] init an initializer list
  19657. @complexity Linear in the size of the initializer list @a init.
  19658. @note This function is required to resolve an ambiguous overload error,
  19659. because pairs like `{"key", "value"}` can be both interpreted as
  19660. `object_t::value_type` or `std::initializer_list<basic_json>`, see
  19661. https://github.com/nlohmann/json/issues/235 for more information.
  19662. @liveexample{The example shows how initializer lists are treated as
  19663. objects when possible.,push_back__initializer_list}
  19664. */
  19665. void push_back(initializer_list_t init)
  19666. {
  19667. if (is_object() && init.size() == 2 && (*init.begin())->is_string())
  19668. {
  19669. basic_json&& key = init.begin()->moved_or_copied();
  19670. push_back(typename object_t::value_type(
  19671. std::move(key.get_ref<string_t&>()), (init.begin() + 1)->moved_or_copied()));
  19672. }
  19673. else
  19674. {
  19675. push_back(basic_json(init));
  19676. }
  19677. }
  19678. /*!
  19679. @brief add an object to an object
  19680. @copydoc push_back(initializer_list_t)
  19681. */
  19682. reference operator+=(initializer_list_t init)
  19683. {
  19684. push_back(init);
  19685. return *this;
  19686. }
  19687. /*!
  19688. @brief add an object to an array
  19689. Creates a JSON value from the passed parameters @a args to the end of the
  19690. JSON value. If the function is called on a JSON null value, an empty array
  19691. is created before appending the value created from @a args.
  19692. @param[in] args arguments to forward to a constructor of @ref basic_json
  19693. @tparam Args compatible types to create a @ref basic_json object
  19694. @return reference to the inserted element
  19695. @throw type_error.311 when called on a type other than JSON array or
  19696. null; example: `"cannot use emplace_back() with number"`
  19697. @complexity Amortized constant.
  19698. @liveexample{The example shows how `push_back()` can be used to add
  19699. elements to a JSON array. Note how the `null` value was silently converted
  19700. to a JSON array.,emplace_back}
  19701. @since version 2.0.8, returns reference since 3.7.0
  19702. */
  19703. template<class... Args>
  19704. reference emplace_back(Args&& ... args)
  19705. {
  19706. // emplace_back only works for null objects or arrays
  19707. if (JSON_HEDLEY_UNLIKELY(!(is_null() || is_array())))
  19708. {
  19709. JSON_THROW(type_error::create(311, "cannot use emplace_back() with " + std::string(type_name()), *this));
  19710. }
  19711. // transform null object into an array
  19712. if (is_null())
  19713. {
  19714. m_type = value_t::array;
  19715. m_value = value_t::array;
  19716. assert_invariant();
  19717. }
  19718. // add element to array (perfect forwarding)
  19719. const auto old_capacity = m_value.array->capacity();
  19720. m_value.array->emplace_back(std::forward<Args>(args)...);
  19721. return set_parent(m_value.array->back(), old_capacity);
  19722. }
  19723. /*!
  19724. @brief add an object to an object if key does not exist
  19725. Inserts a new element into a JSON object constructed in-place with the
  19726. given @a args if there is no element with the key in the container. If the
  19727. function is called on a JSON null value, an empty object is created before
  19728. appending the value created from @a args.
  19729. @param[in] args arguments to forward to a constructor of @ref basic_json
  19730. @tparam Args compatible types to create a @ref basic_json object
  19731. @return a pair consisting of an iterator to the inserted element, or the
  19732. already-existing element if no insertion happened, and a bool
  19733. denoting whether the insertion took place.
  19734. @throw type_error.311 when called on a type other than JSON object or
  19735. null; example: `"cannot use emplace() with number"`
  19736. @complexity Logarithmic in the size of the container, O(log(`size()`)).
  19737. @liveexample{The example shows how `emplace()` can be used to add elements
  19738. to a JSON object. Note how the `null` value was silently converted to a
  19739. JSON object. Further note how no value is added if there was already one
  19740. value stored with the same key.,emplace}
  19741. @since version 2.0.8
  19742. */
  19743. template<class... Args>
  19744. std::pair<iterator, bool> emplace(Args&& ... args)
  19745. {
  19746. // emplace only works for null objects or arrays
  19747. if (JSON_HEDLEY_UNLIKELY(!(is_null() || is_object())))
  19748. {
  19749. JSON_THROW(type_error::create(311, "cannot use emplace() with " + std::string(type_name()), *this));
  19750. }
  19751. // transform null object into an object
  19752. if (is_null())
  19753. {
  19754. m_type = value_t::object;
  19755. m_value = value_t::object;
  19756. assert_invariant();
  19757. }
  19758. // add element to array (perfect forwarding)
  19759. auto res = m_value.object->emplace(std::forward<Args>(args)...);
  19760. set_parent(res.first->second);
  19761. // create result iterator and set iterator to the result of emplace
  19762. auto it = begin();
  19763. it.m_it.object_iterator = res.first;
  19764. // return pair of iterator and boolean
  19765. return {it, res.second};
  19766. }
  19767. /// Helper for insertion of an iterator
  19768. /// @note: This uses std::distance to support GCC 4.8,
  19769. /// see https://github.com/nlohmann/json/pull/1257
  19770. template<typename... Args>
  19771. iterator insert_iterator(const_iterator pos, Args&& ... args)
  19772. {
  19773. iterator result(this);
  19774. JSON_ASSERT(m_value.array != nullptr);
  19775. auto insert_pos = std::distance(m_value.array->begin(), pos.m_it.array_iterator);
  19776. m_value.array->insert(pos.m_it.array_iterator, std::forward<Args>(args)...);
  19777. result.m_it.array_iterator = m_value.array->begin() + insert_pos;
  19778. // This could have been written as:
  19779. // result.m_it.array_iterator = m_value.array->insert(pos.m_it.array_iterator, cnt, val);
  19780. // but the return value of insert is missing in GCC 4.8, so it is written this way instead.
  19781. set_parents();
  19782. return result;
  19783. }
  19784. /*!
  19785. @brief inserts element
  19786. Inserts element @a val before iterator @a pos.
  19787. @param[in] pos iterator before which the content will be inserted; may be
  19788. the end() iterator
  19789. @param[in] val element to insert
  19790. @return iterator pointing to the inserted @a val.
  19791. @throw type_error.309 if called on JSON values other than arrays;
  19792. example: `"cannot use insert() with string"`
  19793. @throw invalid_iterator.202 if @a pos is not an iterator of *this;
  19794. example: `"iterator does not fit current value"`
  19795. @complexity Constant plus linear in the distance between @a pos and end of
  19796. the container.
  19797. @liveexample{The example shows how `insert()` is used.,insert}
  19798. @since version 1.0.0
  19799. */
  19800. iterator insert(const_iterator pos, const basic_json& val)
  19801. {
  19802. // insert only works for arrays
  19803. if (JSON_HEDLEY_LIKELY(is_array()))
  19804. {
  19805. // check if iterator pos fits to this JSON value
  19806. if (JSON_HEDLEY_UNLIKELY(pos.m_object != this))
  19807. {
  19808. JSON_THROW(invalid_iterator::create(202, "iterator does not fit current value", *this));
  19809. }
  19810. // insert to array and return iterator
  19811. return insert_iterator(pos, val);
  19812. }
  19813. JSON_THROW(type_error::create(309, "cannot use insert() with " + std::string(type_name()), *this));
  19814. }
  19815. /*!
  19816. @brief inserts element
  19817. @copydoc insert(const_iterator, const basic_json&)
  19818. */
  19819. iterator insert(const_iterator pos, basic_json&& val)
  19820. {
  19821. return insert(pos, val);
  19822. }
  19823. /*!
  19824. @brief inserts elements
  19825. Inserts @a cnt copies of @a val before iterator @a pos.
  19826. @param[in] pos iterator before which the content will be inserted; may be
  19827. the end() iterator
  19828. @param[in] cnt number of copies of @a val to insert
  19829. @param[in] val element to insert
  19830. @return iterator pointing to the first element inserted, or @a pos if
  19831. `cnt==0`
  19832. @throw type_error.309 if called on JSON values other than arrays; example:
  19833. `"cannot use insert() with string"`
  19834. @throw invalid_iterator.202 if @a pos is not an iterator of *this;
  19835. example: `"iterator does not fit current value"`
  19836. @complexity Linear in @a cnt plus linear in the distance between @a pos
  19837. and end of the container.
  19838. @liveexample{The example shows how `insert()` is used.,insert__count}
  19839. @since version 1.0.0
  19840. */
  19841. iterator insert(const_iterator pos, size_type cnt, const basic_json& val)
  19842. {
  19843. // insert only works for arrays
  19844. if (JSON_HEDLEY_LIKELY(is_array()))
  19845. {
  19846. // check if iterator pos fits to this JSON value
  19847. if (JSON_HEDLEY_UNLIKELY(pos.m_object != this))
  19848. {
  19849. JSON_THROW(invalid_iterator::create(202, "iterator does not fit current value", *this));
  19850. }
  19851. // insert to array and return iterator
  19852. return insert_iterator(pos, cnt, val);
  19853. }
  19854. JSON_THROW(type_error::create(309, "cannot use insert() with " + std::string(type_name()), *this));
  19855. }
  19856. /*!
  19857. @brief inserts elements
  19858. Inserts elements from range `[first, last)` before iterator @a pos.
  19859. @param[in] pos iterator before which the content will be inserted; may be
  19860. the end() iterator
  19861. @param[in] first begin of the range of elements to insert
  19862. @param[in] last end of the range of elements to insert
  19863. @throw type_error.309 if called on JSON values other than arrays; example:
  19864. `"cannot use insert() with string"`
  19865. @throw invalid_iterator.202 if @a pos is not an iterator of *this;
  19866. example: `"iterator does not fit current value"`
  19867. @throw invalid_iterator.210 if @a first and @a last do not belong to the
  19868. same JSON value; example: `"iterators do not fit"`
  19869. @throw invalid_iterator.211 if @a first or @a last are iterators into
  19870. container for which insert is called; example: `"passed iterators may not
  19871. belong to container"`
  19872. @return iterator pointing to the first element inserted, or @a pos if
  19873. `first==last`
  19874. @complexity Linear in `std::distance(first, last)` plus linear in the
  19875. distance between @a pos and end of the container.
  19876. @liveexample{The example shows how `insert()` is used.,insert__range}
  19877. @since version 1.0.0
  19878. */
  19879. iterator insert(const_iterator pos, const_iterator first, const_iterator last)
  19880. {
  19881. // insert only works for arrays
  19882. if (JSON_HEDLEY_UNLIKELY(!is_array()))
  19883. {
  19884. JSON_THROW(type_error::create(309, "cannot use insert() with " + std::string(type_name()), *this));
  19885. }
  19886. // check if iterator pos fits to this JSON value
  19887. if (JSON_HEDLEY_UNLIKELY(pos.m_object != this))
  19888. {
  19889. JSON_THROW(invalid_iterator::create(202, "iterator does not fit current value", *this));
  19890. }
  19891. // check if range iterators belong to the same JSON object
  19892. if (JSON_HEDLEY_UNLIKELY(first.m_object != last.m_object))
  19893. {
  19894. JSON_THROW(invalid_iterator::create(210, "iterators do not fit", *this));
  19895. }
  19896. if (JSON_HEDLEY_UNLIKELY(first.m_object == this))
  19897. {
  19898. JSON_THROW(invalid_iterator::create(211, "passed iterators may not belong to container", *this));
  19899. }
  19900. // insert to array and return iterator
  19901. return insert_iterator(pos, first.m_it.array_iterator, last.m_it.array_iterator);
  19902. }
  19903. /*!
  19904. @brief inserts elements
  19905. Inserts elements from initializer list @a ilist before iterator @a pos.
  19906. @param[in] pos iterator before which the content will be inserted; may be
  19907. the end() iterator
  19908. @param[in] ilist initializer list to insert the values from
  19909. @throw type_error.309 if called on JSON values other than arrays; example:
  19910. `"cannot use insert() with string"`
  19911. @throw invalid_iterator.202 if @a pos is not an iterator of *this;
  19912. example: `"iterator does not fit current value"`
  19913. @return iterator pointing to the first element inserted, or @a pos if
  19914. `ilist` is empty
  19915. @complexity Linear in `ilist.size()` plus linear in the distance between
  19916. @a pos and end of the container.
  19917. @liveexample{The example shows how `insert()` is used.,insert__ilist}
  19918. @since version 1.0.0
  19919. */
  19920. iterator insert(const_iterator pos, initializer_list_t ilist)
  19921. {
  19922. // insert only works for arrays
  19923. if (JSON_HEDLEY_UNLIKELY(!is_array()))
  19924. {
  19925. JSON_THROW(type_error::create(309, "cannot use insert() with " + std::string(type_name()), *this));
  19926. }
  19927. // check if iterator pos fits to this JSON value
  19928. if (JSON_HEDLEY_UNLIKELY(pos.m_object != this))
  19929. {
  19930. JSON_THROW(invalid_iterator::create(202, "iterator does not fit current value", *this));
  19931. }
  19932. // insert to array and return iterator
  19933. return insert_iterator(pos, ilist.begin(), ilist.end());
  19934. }
  19935. /*!
  19936. @brief inserts elements
  19937. Inserts elements from range `[first, last)`.
  19938. @param[in] first begin of the range of elements to insert
  19939. @param[in] last end of the range of elements to insert
  19940. @throw type_error.309 if called on JSON values other than objects; example:
  19941. `"cannot use insert() with string"`
  19942. @throw invalid_iterator.202 if iterator @a first or @a last does does not
  19943. point to an object; example: `"iterators first and last must point to
  19944. objects"`
  19945. @throw invalid_iterator.210 if @a first and @a last do not belong to the
  19946. same JSON value; example: `"iterators do not fit"`
  19947. @complexity Logarithmic: `O(N*log(size() + N))`, where `N` is the number
  19948. of elements to insert.
  19949. @liveexample{The example shows how `insert()` is used.,insert__range_object}
  19950. @since version 3.0.0
  19951. */
  19952. void insert(const_iterator first, const_iterator last)
  19953. {
  19954. // insert only works for objects
  19955. if (JSON_HEDLEY_UNLIKELY(!is_object()))
  19956. {
  19957. JSON_THROW(type_error::create(309, "cannot use insert() with " + std::string(type_name()), *this));
  19958. }
  19959. // check if range iterators belong to the same JSON object
  19960. if (JSON_HEDLEY_UNLIKELY(first.m_object != last.m_object))
  19961. {
  19962. JSON_THROW(invalid_iterator::create(210, "iterators do not fit", *this));
  19963. }
  19964. // passed iterators must belong to objects
  19965. if (JSON_HEDLEY_UNLIKELY(!first.m_object->is_object()))
  19966. {
  19967. JSON_THROW(invalid_iterator::create(202, "iterators first and last must point to objects", *this));
  19968. }
  19969. m_value.object->insert(first.m_it.object_iterator, last.m_it.object_iterator);
  19970. }
  19971. /*!
  19972. @brief updates a JSON object from another object, overwriting existing keys
  19973. Inserts all values from JSON object @a j and overwrites existing keys.
  19974. @param[in] j JSON object to read values from
  19975. @throw type_error.312 if called on JSON values other than objects; example:
  19976. `"cannot use update() with string"`
  19977. @complexity O(N*log(size() + N)), where N is the number of elements to
  19978. insert.
  19979. @liveexample{The example shows how `update()` is used.,update}
  19980. @sa https://docs.python.org/3.6/library/stdtypes.html#dict.update
  19981. @since version 3.0.0
  19982. */
  19983. void update(const_reference j)
  19984. {
  19985. // implicitly convert null value to an empty object
  19986. if (is_null())
  19987. {
  19988. m_type = value_t::object;
  19989. m_value.object = create<object_t>();
  19990. assert_invariant();
  19991. }
  19992. if (JSON_HEDLEY_UNLIKELY(!is_object()))
  19993. {
  19994. JSON_THROW(type_error::create(312, "cannot use update() with " + std::string(type_name()), *this));
  19995. }
  19996. if (JSON_HEDLEY_UNLIKELY(!j.is_object()))
  19997. {
  19998. JSON_THROW(type_error::create(312, "cannot use update() with " + std::string(j.type_name()), *this));
  19999. }
  20000. for (auto it = j.cbegin(); it != j.cend(); ++it)
  20001. {
  20002. m_value.object->operator[](it.key()) = it.value();
  20003. #if JSON_DIAGNOSTICS
  20004. m_value.object->operator[](it.key()).m_parent = this;
  20005. #endif
  20006. }
  20007. }
  20008. /*!
  20009. @brief updates a JSON object from another object, overwriting existing keys
  20010. Inserts all values from from range `[first, last)` and overwrites existing
  20011. keys.
  20012. @param[in] first begin of the range of elements to insert
  20013. @param[in] last end of the range of elements to insert
  20014. @throw type_error.312 if called on JSON values other than objects; example:
  20015. `"cannot use update() with string"`
  20016. @throw invalid_iterator.202 if iterator @a first or @a last does does not
  20017. point to an object; example: `"iterators first and last must point to
  20018. objects"`
  20019. @throw invalid_iterator.210 if @a first and @a last do not belong to the
  20020. same JSON value; example: `"iterators do not fit"`
  20021. @complexity O(N*log(size() + N)), where N is the number of elements to
  20022. insert.
  20023. @liveexample{The example shows how `update()` is used__range.,update}
  20024. @sa https://docs.python.org/3.6/library/stdtypes.html#dict.update
  20025. @since version 3.0.0
  20026. */
  20027. void update(const_iterator first, const_iterator last)
  20028. {
  20029. // implicitly convert null value to an empty object
  20030. if (is_null())
  20031. {
  20032. m_type = value_t::object;
  20033. m_value.object = create<object_t>();
  20034. assert_invariant();
  20035. }
  20036. if (JSON_HEDLEY_UNLIKELY(!is_object()))
  20037. {
  20038. JSON_THROW(type_error::create(312, "cannot use update() with " + std::string(type_name()), *this));
  20039. }
  20040. // check if range iterators belong to the same JSON object
  20041. if (JSON_HEDLEY_UNLIKELY(first.m_object != last.m_object))
  20042. {
  20043. JSON_THROW(invalid_iterator::create(210, "iterators do not fit", *this));
  20044. }
  20045. // passed iterators must belong to objects
  20046. if (JSON_HEDLEY_UNLIKELY(!first.m_object->is_object()
  20047. || !last.m_object->is_object()))
  20048. {
  20049. JSON_THROW(invalid_iterator::create(202, "iterators first and last must point to objects", *this));
  20050. }
  20051. for (auto it = first; it != last; ++it)
  20052. {
  20053. m_value.object->operator[](it.key()) = it.value();
  20054. #if JSON_DIAGNOSTICS
  20055. m_value.object->operator[](it.key()).m_parent = this;
  20056. #endif
  20057. }
  20058. }
  20059. /*!
  20060. @brief exchanges the values
  20061. Exchanges the contents of the JSON value with those of @a other. Does not
  20062. invoke any move, copy, or swap operations on individual elements. All
  20063. iterators and references remain valid. The past-the-end iterator is
  20064. invalidated.
  20065. @param[in,out] other JSON value to exchange the contents with
  20066. @complexity Constant.
  20067. @liveexample{The example below shows how JSON values can be swapped with
  20068. `swap()`.,swap__reference}
  20069. @since version 1.0.0
  20070. */
  20071. void swap(reference other) noexcept (
  20072. std::is_nothrow_move_constructible<value_t>::value&&
  20073. std::is_nothrow_move_assignable<value_t>::value&&
  20074. std::is_nothrow_move_constructible<json_value>::value&&
  20075. std::is_nothrow_move_assignable<json_value>::value
  20076. )
  20077. {
  20078. std::swap(m_type, other.m_type);
  20079. std::swap(m_value, other.m_value);
  20080. set_parents();
  20081. other.set_parents();
  20082. assert_invariant();
  20083. }
  20084. /*!
  20085. @brief exchanges the values
  20086. Exchanges the contents of the JSON value from @a left with those of @a right. Does not
  20087. invoke any move, copy, or swap operations on individual elements. All
  20088. iterators and references remain valid. The past-the-end iterator is
  20089. invalidated. implemented as a friend function callable via ADL.
  20090. @param[in,out] left JSON value to exchange the contents with
  20091. @param[in,out] right JSON value to exchange the contents with
  20092. @complexity Constant.
  20093. @liveexample{The example below shows how JSON values can be swapped with
  20094. `swap()`.,swap__reference}
  20095. @since version 1.0.0
  20096. */
  20097. friend void swap(reference left, reference right) noexcept (
  20098. std::is_nothrow_move_constructible<value_t>::value&&
  20099. std::is_nothrow_move_assignable<value_t>::value&&
  20100. std::is_nothrow_move_constructible<json_value>::value&&
  20101. std::is_nothrow_move_assignable<json_value>::value
  20102. )
  20103. {
  20104. left.swap(right);
  20105. }
  20106. /*!
  20107. @brief exchanges the values
  20108. Exchanges the contents of a JSON array with those of @a other. Does not
  20109. invoke any move, copy, or swap operations on individual elements. All
  20110. iterators and references remain valid. The past-the-end iterator is
  20111. invalidated.
  20112. @param[in,out] other array to exchange the contents with
  20113. @throw type_error.310 when JSON value is not an array; example: `"cannot
  20114. use swap() with string"`
  20115. @complexity Constant.
  20116. @liveexample{The example below shows how arrays can be swapped with
  20117. `swap()`.,swap__array_t}
  20118. @since version 1.0.0
  20119. */
  20120. void swap(array_t& other) // NOLINT(bugprone-exception-escape)
  20121. {
  20122. // swap only works for arrays
  20123. if (JSON_HEDLEY_LIKELY(is_array()))
  20124. {
  20125. std::swap(*(m_value.array), other);
  20126. }
  20127. else
  20128. {
  20129. JSON_THROW(type_error::create(310, "cannot use swap() with " + std::string(type_name()), *this));
  20130. }
  20131. }
  20132. /*!
  20133. @brief exchanges the values
  20134. Exchanges the contents of a JSON object with those of @a other. Does not
  20135. invoke any move, copy, or swap operations on individual elements. All
  20136. iterators and references remain valid. The past-the-end iterator is
  20137. invalidated.
  20138. @param[in,out] other object to exchange the contents with
  20139. @throw type_error.310 when JSON value is not an object; example:
  20140. `"cannot use swap() with string"`
  20141. @complexity Constant.
  20142. @liveexample{The example below shows how objects can be swapped with
  20143. `swap()`.,swap__object_t}
  20144. @since version 1.0.0
  20145. */
  20146. void swap(object_t& other) // NOLINT(bugprone-exception-escape)
  20147. {
  20148. // swap only works for objects
  20149. if (JSON_HEDLEY_LIKELY(is_object()))
  20150. {
  20151. std::swap(*(m_value.object), other);
  20152. }
  20153. else
  20154. {
  20155. JSON_THROW(type_error::create(310, "cannot use swap() with " + std::string(type_name()), *this));
  20156. }
  20157. }
  20158. /*!
  20159. @brief exchanges the values
  20160. Exchanges the contents of a JSON string with those of @a other. Does not
  20161. invoke any move, copy, or swap operations on individual elements. All
  20162. iterators and references remain valid. The past-the-end iterator is
  20163. invalidated.
  20164. @param[in,out] other string to exchange the contents with
  20165. @throw type_error.310 when JSON value is not a string; example: `"cannot
  20166. use swap() with boolean"`
  20167. @complexity Constant.
  20168. @liveexample{The example below shows how strings can be swapped with
  20169. `swap()`.,swap__string_t}
  20170. @since version 1.0.0
  20171. */
  20172. void swap(string_t& other) // NOLINT(bugprone-exception-escape)
  20173. {
  20174. // swap only works for strings
  20175. if (JSON_HEDLEY_LIKELY(is_string()))
  20176. {
  20177. std::swap(*(m_value.string), other);
  20178. }
  20179. else
  20180. {
  20181. JSON_THROW(type_error::create(310, "cannot use swap() with " + std::string(type_name()), *this));
  20182. }
  20183. }
  20184. /*!
  20185. @brief exchanges the values
  20186. Exchanges the contents of a JSON string with those of @a other. Does not
  20187. invoke any move, copy, or swap operations on individual elements. All
  20188. iterators and references remain valid. The past-the-end iterator is
  20189. invalidated.
  20190. @param[in,out] other binary to exchange the contents with
  20191. @throw type_error.310 when JSON value is not a string; example: `"cannot
  20192. use swap() with boolean"`
  20193. @complexity Constant.
  20194. @liveexample{The example below shows how strings can be swapped with
  20195. `swap()`.,swap__binary_t}
  20196. @since version 3.8.0
  20197. */
  20198. void swap(binary_t& other) // NOLINT(bugprone-exception-escape)
  20199. {
  20200. // swap only works for strings
  20201. if (JSON_HEDLEY_LIKELY(is_binary()))
  20202. {
  20203. std::swap(*(m_value.binary), other);
  20204. }
  20205. else
  20206. {
  20207. JSON_THROW(type_error::create(310, "cannot use swap() with " + std::string(type_name()), *this));
  20208. }
  20209. }
  20210. /// @copydoc swap(binary_t&)
  20211. void swap(typename binary_t::container_type& other) // NOLINT(bugprone-exception-escape)
  20212. {
  20213. // swap only works for strings
  20214. if (JSON_HEDLEY_LIKELY(is_binary()))
  20215. {
  20216. std::swap(*(m_value.binary), other);
  20217. }
  20218. else
  20219. {
  20220. JSON_THROW(type_error::create(310, "cannot use swap() with " + std::string(type_name()), *this));
  20221. }
  20222. }
  20223. /// @}
  20224. public:
  20225. //////////////////////////////////////////
  20226. // lexicographical comparison operators //
  20227. //////////////////////////////////////////
  20228. /// @name lexicographical comparison operators
  20229. /// @{
  20230. /*!
  20231. @brief comparison: equal
  20232. Compares two JSON values for equality according to the following rules:
  20233. - Two JSON values are equal if (1) they are from the same type and (2)
  20234. their stored values are the same according to their respective
  20235. `operator==`.
  20236. - Integer and floating-point numbers are automatically converted before
  20237. comparison. Note that two NaN values are always treated as unequal.
  20238. - Two JSON null values are equal.
  20239. @note Floating-point inside JSON values numbers are compared with
  20240. `json::number_float_t::operator==` which is `double::operator==` by
  20241. default. To compare floating-point while respecting an epsilon, an alternative
  20242. [comparison function](https://github.com/mariokonrad/marnav/blob/master/include/marnav/math/floatingpoint.hpp#L34-#L39)
  20243. could be used, for instance
  20244. @code {.cpp}
  20245. template<typename T, typename = typename std::enable_if<std::is_floating_point<T>::value, T>::type>
  20246. inline bool is_same(T a, T b, T epsilon = std::numeric_limits<T>::epsilon()) noexcept
  20247. {
  20248. return std::abs(a - b) <= epsilon;
  20249. }
  20250. @endcode
  20251. Or you can self-defined operator equal function like this:
  20252. @code {.cpp}
  20253. bool my_equal(const_reference lhs, const_reference rhs) {
  20254. const auto lhs_type lhs.type();
  20255. const auto rhs_type rhs.type();
  20256. if (lhs_type == rhs_type) {
  20257. switch(lhs_type)
  20258. // self_defined case
  20259. case value_t::number_float:
  20260. return std::abs(lhs - rhs) <= std::numeric_limits<float>::epsilon();
  20261. // other cases remain the same with the original
  20262. ...
  20263. }
  20264. ...
  20265. }
  20266. @endcode
  20267. @note NaN values never compare equal to themselves or to other NaN values.
  20268. @param[in] lhs first JSON value to consider
  20269. @param[in] rhs second JSON value to consider
  20270. @return whether the values @a lhs and @a rhs are equal
  20271. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  20272. @complexity Linear.
  20273. @liveexample{The example demonstrates comparing several JSON
  20274. types.,operator__equal}
  20275. @since version 1.0.0
  20276. */
  20277. friend bool operator==(const_reference lhs, const_reference rhs) noexcept
  20278. {
  20279. #ifdef __GNUC__
  20280. #pragma GCC diagnostic push
  20281. #pragma GCC diagnostic ignored "-Wfloat-equal"
  20282. #endif
  20283. const auto lhs_type = lhs.type();
  20284. const auto rhs_type = rhs.type();
  20285. if (lhs_type == rhs_type)
  20286. {
  20287. switch (lhs_type)
  20288. {
  20289. case value_t::array:
  20290. return *lhs.m_value.array == *rhs.m_value.array;
  20291. case value_t::object:
  20292. return *lhs.m_value.object == *rhs.m_value.object;
  20293. case value_t::null:
  20294. return true;
  20295. case value_t::string:
  20296. return *lhs.m_value.string == *rhs.m_value.string;
  20297. case value_t::boolean:
  20298. return lhs.m_value.boolean == rhs.m_value.boolean;
  20299. case value_t::number_integer:
  20300. return lhs.m_value.number_integer == rhs.m_value.number_integer;
  20301. case value_t::number_unsigned:
  20302. return lhs.m_value.number_unsigned == rhs.m_value.number_unsigned;
  20303. case value_t::number_float:
  20304. return lhs.m_value.number_float == rhs.m_value.number_float;
  20305. case value_t::binary:
  20306. return *lhs.m_value.binary == *rhs.m_value.binary;
  20307. case value_t::discarded:
  20308. default:
  20309. return false;
  20310. }
  20311. }
  20312. else if (lhs_type == value_t::number_integer && rhs_type == value_t::number_float)
  20313. {
  20314. return static_cast<number_float_t>(lhs.m_value.number_integer) == rhs.m_value.number_float;
  20315. }
  20316. else if (lhs_type == value_t::number_float && rhs_type == value_t::number_integer)
  20317. {
  20318. return lhs.m_value.number_float == static_cast<number_float_t>(rhs.m_value.number_integer);
  20319. }
  20320. else if (lhs_type == value_t::number_unsigned && rhs_type == value_t::number_float)
  20321. {
  20322. return static_cast<number_float_t>(lhs.m_value.number_unsigned) == rhs.m_value.number_float;
  20323. }
  20324. else if (lhs_type == value_t::number_float && rhs_type == value_t::number_unsigned)
  20325. {
  20326. return lhs.m_value.number_float == static_cast<number_float_t>(rhs.m_value.number_unsigned);
  20327. }
  20328. else if (lhs_type == value_t::number_unsigned && rhs_type == value_t::number_integer)
  20329. {
  20330. return static_cast<number_integer_t>(lhs.m_value.number_unsigned) == rhs.m_value.number_integer;
  20331. }
  20332. else if (lhs_type == value_t::number_integer && rhs_type == value_t::number_unsigned)
  20333. {
  20334. return lhs.m_value.number_integer == static_cast<number_integer_t>(rhs.m_value.number_unsigned);
  20335. }
  20336. return false;
  20337. #ifdef __GNUC__
  20338. #pragma GCC diagnostic pop
  20339. #endif
  20340. }
  20341. /*!
  20342. @brief comparison: equal
  20343. @copydoc operator==(const_reference, const_reference)
  20344. */
  20345. template<typename ScalarType, typename std::enable_if<
  20346. std::is_scalar<ScalarType>::value, int>::type = 0>
  20347. friend bool operator==(const_reference lhs, ScalarType rhs) noexcept
  20348. {
  20349. return lhs == basic_json(rhs);
  20350. }
  20351. /*!
  20352. @brief comparison: equal
  20353. @copydoc operator==(const_reference, const_reference)
  20354. */
  20355. template<typename ScalarType, typename std::enable_if<
  20356. std::is_scalar<ScalarType>::value, int>::type = 0>
  20357. friend bool operator==(ScalarType lhs, const_reference rhs) noexcept
  20358. {
  20359. return basic_json(lhs) == rhs;
  20360. }
  20361. /*!
  20362. @brief comparison: not equal
  20363. Compares two JSON values for inequality by calculating `not (lhs == rhs)`.
  20364. @param[in] lhs first JSON value to consider
  20365. @param[in] rhs second JSON value to consider
  20366. @return whether the values @a lhs and @a rhs are not equal
  20367. @complexity Linear.
  20368. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  20369. @liveexample{The example demonstrates comparing several JSON
  20370. types.,operator__notequal}
  20371. @since version 1.0.0
  20372. */
  20373. friend bool operator!=(const_reference lhs, const_reference rhs) noexcept
  20374. {
  20375. return !(lhs == rhs);
  20376. }
  20377. /*!
  20378. @brief comparison: not equal
  20379. @copydoc operator!=(const_reference, const_reference)
  20380. */
  20381. template<typename ScalarType, typename std::enable_if<
  20382. std::is_scalar<ScalarType>::value, int>::type = 0>
  20383. friend bool operator!=(const_reference lhs, ScalarType rhs) noexcept
  20384. {
  20385. return lhs != basic_json(rhs);
  20386. }
  20387. /*!
  20388. @brief comparison: not equal
  20389. @copydoc operator!=(const_reference, const_reference)
  20390. */
  20391. template<typename ScalarType, typename std::enable_if<
  20392. std::is_scalar<ScalarType>::value, int>::type = 0>
  20393. friend bool operator!=(ScalarType lhs, const_reference rhs) noexcept
  20394. {
  20395. return basic_json(lhs) != rhs;
  20396. }
  20397. /*!
  20398. @brief comparison: less than
  20399. Compares whether one JSON value @a lhs is less than another JSON value @a
  20400. rhs according to the following rules:
  20401. - If @a lhs and @a rhs have the same type, the values are compared using
  20402. the default `<` operator.
  20403. - Integer and floating-point numbers are automatically converted before
  20404. comparison
  20405. - In case @a lhs and @a rhs have different types, the values are ignored
  20406. and the order of the types is considered, see
  20407. @ref operator<(const value_t, const value_t).
  20408. @param[in] lhs first JSON value to consider
  20409. @param[in] rhs second JSON value to consider
  20410. @return whether @a lhs is less than @a rhs
  20411. @complexity Linear.
  20412. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  20413. @liveexample{The example demonstrates comparing several JSON
  20414. types.,operator__less}
  20415. @since version 1.0.0
  20416. */
  20417. friend bool operator<(const_reference lhs, const_reference rhs) noexcept
  20418. {
  20419. const auto lhs_type = lhs.type();
  20420. const auto rhs_type = rhs.type();
  20421. if (lhs_type == rhs_type)
  20422. {
  20423. switch (lhs_type)
  20424. {
  20425. case value_t::array:
  20426. // note parentheses are necessary, see
  20427. // https://github.com/nlohmann/json/issues/1530
  20428. return (*lhs.m_value.array) < (*rhs.m_value.array);
  20429. case value_t::object:
  20430. return (*lhs.m_value.object) < (*rhs.m_value.object);
  20431. case value_t::null:
  20432. return false;
  20433. case value_t::string:
  20434. return (*lhs.m_value.string) < (*rhs.m_value.string);
  20435. case value_t::boolean:
  20436. return (lhs.m_value.boolean) < (rhs.m_value.boolean);
  20437. case value_t::number_integer:
  20438. return (lhs.m_value.number_integer) < (rhs.m_value.number_integer);
  20439. case value_t::number_unsigned:
  20440. return (lhs.m_value.number_unsigned) < (rhs.m_value.number_unsigned);
  20441. case value_t::number_float:
  20442. return (lhs.m_value.number_float) < (rhs.m_value.number_float);
  20443. case value_t::binary:
  20444. return (*lhs.m_value.binary) < (*rhs.m_value.binary);
  20445. case value_t::discarded:
  20446. default:
  20447. return false;
  20448. }
  20449. }
  20450. else if (lhs_type == value_t::number_integer && rhs_type == value_t::number_float)
  20451. {
  20452. return static_cast<number_float_t>(lhs.m_value.number_integer) < rhs.m_value.number_float;
  20453. }
  20454. else if (lhs_type == value_t::number_float && rhs_type == value_t::number_integer)
  20455. {
  20456. return lhs.m_value.number_float < static_cast<number_float_t>(rhs.m_value.number_integer);
  20457. }
  20458. else if (lhs_type == value_t::number_unsigned && rhs_type == value_t::number_float)
  20459. {
  20460. return static_cast<number_float_t>(lhs.m_value.number_unsigned) < rhs.m_value.number_float;
  20461. }
  20462. else if (lhs_type == value_t::number_float && rhs_type == value_t::number_unsigned)
  20463. {
  20464. return lhs.m_value.number_float < static_cast<number_float_t>(rhs.m_value.number_unsigned);
  20465. }
  20466. else if (lhs_type == value_t::number_integer && rhs_type == value_t::number_unsigned)
  20467. {
  20468. return lhs.m_value.number_integer < static_cast<number_integer_t>(rhs.m_value.number_unsigned);
  20469. }
  20470. else if (lhs_type == value_t::number_unsigned && rhs_type == value_t::number_integer)
  20471. {
  20472. return static_cast<number_integer_t>(lhs.m_value.number_unsigned) < rhs.m_value.number_integer;
  20473. }
  20474. // We only reach this line if we cannot compare values. In that case,
  20475. // we compare types. Note we have to call the operator explicitly,
  20476. // because MSVC has problems otherwise.
  20477. return operator<(lhs_type, rhs_type);
  20478. }
  20479. /*!
  20480. @brief comparison: less than
  20481. @copydoc operator<(const_reference, const_reference)
  20482. */
  20483. template<typename ScalarType, typename std::enable_if<
  20484. std::is_scalar<ScalarType>::value, int>::type = 0>
  20485. friend bool operator<(const_reference lhs, ScalarType rhs) noexcept
  20486. {
  20487. return lhs < basic_json(rhs);
  20488. }
  20489. /*!
  20490. @brief comparison: less than
  20491. @copydoc operator<(const_reference, const_reference)
  20492. */
  20493. template<typename ScalarType, typename std::enable_if<
  20494. std::is_scalar<ScalarType>::value, int>::type = 0>
  20495. friend bool operator<(ScalarType lhs, const_reference rhs) noexcept
  20496. {
  20497. return basic_json(lhs) < rhs;
  20498. }
  20499. /*!
  20500. @brief comparison: less than or equal
  20501. Compares whether one JSON value @a lhs is less than or equal to another
  20502. JSON value by calculating `not (rhs < lhs)`.
  20503. @param[in] lhs first JSON value to consider
  20504. @param[in] rhs second JSON value to consider
  20505. @return whether @a lhs is less than or equal to @a rhs
  20506. @complexity Linear.
  20507. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  20508. @liveexample{The example demonstrates comparing several JSON
  20509. types.,operator__greater}
  20510. @since version 1.0.0
  20511. */
  20512. friend bool operator<=(const_reference lhs, const_reference rhs) noexcept
  20513. {
  20514. return !(rhs < lhs);
  20515. }
  20516. /*!
  20517. @brief comparison: less than or equal
  20518. @copydoc operator<=(const_reference, const_reference)
  20519. */
  20520. template<typename ScalarType, typename std::enable_if<
  20521. std::is_scalar<ScalarType>::value, int>::type = 0>
  20522. friend bool operator<=(const_reference lhs, ScalarType rhs) noexcept
  20523. {
  20524. return lhs <= basic_json(rhs);
  20525. }
  20526. /*!
  20527. @brief comparison: less than or equal
  20528. @copydoc operator<=(const_reference, const_reference)
  20529. */
  20530. template<typename ScalarType, typename std::enable_if<
  20531. std::is_scalar<ScalarType>::value, int>::type = 0>
  20532. friend bool operator<=(ScalarType lhs, const_reference rhs) noexcept
  20533. {
  20534. return basic_json(lhs) <= rhs;
  20535. }
  20536. /*!
  20537. @brief comparison: greater than
  20538. Compares whether one JSON value @a lhs is greater than another
  20539. JSON value by calculating `not (lhs <= rhs)`.
  20540. @param[in] lhs first JSON value to consider
  20541. @param[in] rhs second JSON value to consider
  20542. @return whether @a lhs is greater than to @a rhs
  20543. @complexity Linear.
  20544. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  20545. @liveexample{The example demonstrates comparing several JSON
  20546. types.,operator__lessequal}
  20547. @since version 1.0.0
  20548. */
  20549. friend bool operator>(const_reference lhs, const_reference rhs) noexcept
  20550. {
  20551. return !(lhs <= rhs);
  20552. }
  20553. /*!
  20554. @brief comparison: greater than
  20555. @copydoc operator>(const_reference, const_reference)
  20556. */
  20557. template<typename ScalarType, typename std::enable_if<
  20558. std::is_scalar<ScalarType>::value, int>::type = 0>
  20559. friend bool operator>(const_reference lhs, ScalarType rhs) noexcept
  20560. {
  20561. return lhs > basic_json(rhs);
  20562. }
  20563. /*!
  20564. @brief comparison: greater than
  20565. @copydoc operator>(const_reference, const_reference)
  20566. */
  20567. template<typename ScalarType, typename std::enable_if<
  20568. std::is_scalar<ScalarType>::value, int>::type = 0>
  20569. friend bool operator>(ScalarType lhs, const_reference rhs) noexcept
  20570. {
  20571. return basic_json(lhs) > rhs;
  20572. }
  20573. /*!
  20574. @brief comparison: greater than or equal
  20575. Compares whether one JSON value @a lhs is greater than or equal to another
  20576. JSON value by calculating `not (lhs < rhs)`.
  20577. @param[in] lhs first JSON value to consider
  20578. @param[in] rhs second JSON value to consider
  20579. @return whether @a lhs is greater than or equal to @a rhs
  20580. @complexity Linear.
  20581. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  20582. @liveexample{The example demonstrates comparing several JSON
  20583. types.,operator__greaterequal}
  20584. @since version 1.0.0
  20585. */
  20586. friend bool operator>=(const_reference lhs, const_reference rhs) noexcept
  20587. {
  20588. return !(lhs < rhs);
  20589. }
  20590. /*!
  20591. @brief comparison: greater than or equal
  20592. @copydoc operator>=(const_reference, const_reference)
  20593. */
  20594. template<typename ScalarType, typename std::enable_if<
  20595. std::is_scalar<ScalarType>::value, int>::type = 0>
  20596. friend bool operator>=(const_reference lhs, ScalarType rhs) noexcept
  20597. {
  20598. return lhs >= basic_json(rhs);
  20599. }
  20600. /*!
  20601. @brief comparison: greater than or equal
  20602. @copydoc operator>=(const_reference, const_reference)
  20603. */
  20604. template<typename ScalarType, typename std::enable_if<
  20605. std::is_scalar<ScalarType>::value, int>::type = 0>
  20606. friend bool operator>=(ScalarType lhs, const_reference rhs) noexcept
  20607. {
  20608. return basic_json(lhs) >= rhs;
  20609. }
  20610. /// @}
  20611. ///////////////////
  20612. // serialization //
  20613. ///////////////////
  20614. /// @name serialization
  20615. /// @{
  20616. #ifndef JSON_NO_IO
  20617. /*!
  20618. @brief serialize to stream
  20619. Serialize the given JSON value @a j to the output stream @a o. The JSON
  20620. value will be serialized using the @ref dump member function.
  20621. - The indentation of the output can be controlled with the member variable
  20622. `width` of the output stream @a o. For instance, using the manipulator
  20623. `std::setw(4)` on @a o sets the indentation level to `4` and the
  20624. serialization result is the same as calling `dump(4)`.
  20625. - The indentation character can be controlled with the member variable
  20626. `fill` of the output stream @a o. For instance, the manipulator
  20627. `std::setfill('\\t')` sets indentation to use a tab character rather than
  20628. the default space character.
  20629. @param[in,out] o stream to serialize to
  20630. @param[in] j JSON value to serialize
  20631. @return the stream @a o
  20632. @throw type_error.316 if a string stored inside the JSON value is not
  20633. UTF-8 encoded
  20634. @complexity Linear.
  20635. @liveexample{The example below shows the serialization with different
  20636. parameters to `width` to adjust the indentation level.,operator_serialize}
  20637. @since version 1.0.0; indentation character added in version 3.0.0
  20638. */
  20639. friend std::ostream& operator<<(std::ostream& o, const basic_json& j)
  20640. {
  20641. // read width member and use it as indentation parameter if nonzero
  20642. const bool pretty_print = o.width() > 0;
  20643. const auto indentation = pretty_print ? o.width() : 0;
  20644. // reset width to 0 for subsequent calls to this stream
  20645. o.width(0);
  20646. // do the actual serialization
  20647. serializer s(detail::output_adapter<char>(o), o.fill());
  20648. s.dump(j, pretty_print, false, static_cast<unsigned int>(indentation));
  20649. return o;
  20650. }
  20651. /*!
  20652. @brief serialize to stream
  20653. @deprecated This stream operator is deprecated and will be removed in
  20654. future 4.0.0 of the library. Please use
  20655. @ref operator<<(std::ostream&, const basic_json&)
  20656. instead; that is, replace calls like `j >> o;` with `o << j;`.
  20657. @since version 1.0.0; deprecated since version 3.0.0
  20658. */
  20659. JSON_HEDLEY_DEPRECATED_FOR(3.0.0, operator<<(std::ostream&, const basic_json&))
  20660. friend std::ostream& operator>>(const basic_json& j, std::ostream& o)
  20661. {
  20662. return o << j;
  20663. }
  20664. #endif // JSON_NO_IO
  20665. /// @}
  20666. /////////////////////
  20667. // deserialization //
  20668. /////////////////////
  20669. /// @name deserialization
  20670. /// @{
  20671. /*!
  20672. @brief deserialize from a compatible input
  20673. @tparam InputType A compatible input, for instance
  20674. - an std::istream object
  20675. - a FILE pointer
  20676. - a C-style array of characters
  20677. - a pointer to a null-terminated string of single byte characters
  20678. - an object obj for which begin(obj) and end(obj) produces a valid pair of
  20679. iterators.
  20680. @param[in] i input to read from
  20681. @param[in] cb a parser callback function of type @ref parser_callback_t
  20682. which is used to control the deserialization by filtering unwanted values
  20683. (optional)
  20684. @param[in] allow_exceptions whether to throw exceptions in case of a
  20685. parse error (optional, true by default)
  20686. @param[in] ignore_comments whether comments should be ignored and treated
  20687. like whitespace (true) or yield a parse error (true); (optional, false by
  20688. default)
  20689. @return deserialized JSON value; in case of a parse error and
  20690. @a allow_exceptions set to `false`, the return value will be
  20691. value_t::discarded.
  20692. @throw parse_error.101 if a parse error occurs; example: `""unexpected end
  20693. of input; expected string literal""`
  20694. @throw parse_error.102 if to_unicode fails or surrogate error
  20695. @throw parse_error.103 if to_unicode fails
  20696. @complexity Linear in the length of the input. The parser is a predictive
  20697. LL(1) parser. The complexity can be higher if the parser callback function
  20698. @a cb or reading from the input @a i has a super-linear complexity.
  20699. @note A UTF-8 byte order mark is silently ignored.
  20700. @liveexample{The example below demonstrates the `parse()` function reading
  20701. from an array.,parse__array__parser_callback_t}
  20702. @liveexample{The example below demonstrates the `parse()` function with
  20703. and without callback function.,parse__string__parser_callback_t}
  20704. @liveexample{The example below demonstrates the `parse()` function with
  20705. and without callback function.,parse__istream__parser_callback_t}
  20706. @liveexample{The example below demonstrates the `parse()` function reading
  20707. from a contiguous container.,parse__contiguouscontainer__parser_callback_t}
  20708. @since version 2.0.3 (contiguous containers); version 3.9.0 allowed to
  20709. ignore comments.
  20710. */
  20711. template<typename InputType>
  20712. JSON_HEDLEY_WARN_UNUSED_RESULT
  20713. static basic_json parse(InputType&& i,
  20714. const parser_callback_t cb = nullptr,
  20715. const bool allow_exceptions = true,
  20716. const bool ignore_comments = false)
  20717. {
  20718. basic_json result;
  20719. parser(detail::input_adapter(std::forward<InputType>(i)), cb, allow_exceptions, ignore_comments).parse(true, result);
  20720. return result;
  20721. }
  20722. /*!
  20723. @brief deserialize from a pair of character iterators
  20724. The value_type of the iterator must be a integral type with size of 1, 2 or
  20725. 4 bytes, which will be interpreted respectively as UTF-8, UTF-16 and UTF-32.
  20726. @param[in] first iterator to start of character range
  20727. @param[in] last iterator to end of character range
  20728. @param[in] cb a parser callback function of type @ref parser_callback_t
  20729. which is used to control the deserialization by filtering unwanted values
  20730. (optional)
  20731. @param[in] allow_exceptions whether to throw exceptions in case of a
  20732. parse error (optional, true by default)
  20733. @param[in] ignore_comments whether comments should be ignored and treated
  20734. like whitespace (true) or yield a parse error (true); (optional, false by
  20735. default)
  20736. @return deserialized JSON value; in case of a parse error and
  20737. @a allow_exceptions set to `false`, the return value will be
  20738. value_t::discarded.
  20739. @throw parse_error.101 if a parse error occurs; example: `""unexpected end
  20740. of input; expected string literal""`
  20741. @throw parse_error.102 if to_unicode fails or surrogate error
  20742. @throw parse_error.103 if to_unicode fails
  20743. */
  20744. template<typename IteratorType>
  20745. JSON_HEDLEY_WARN_UNUSED_RESULT
  20746. static basic_json parse(IteratorType first,
  20747. IteratorType last,
  20748. const parser_callback_t cb = nullptr,
  20749. const bool allow_exceptions = true,
  20750. const bool ignore_comments = false)
  20751. {
  20752. basic_json result;
  20753. parser(detail::input_adapter(std::move(first), std::move(last)), cb, allow_exceptions, ignore_comments).parse(true, result);
  20754. return result;
  20755. }
  20756. JSON_HEDLEY_WARN_UNUSED_RESULT
  20757. JSON_HEDLEY_DEPRECATED_FOR(3.8.0, parse(ptr, ptr + len))
  20758. static basic_json parse(detail::span_input_adapter&& i,
  20759. const parser_callback_t cb = nullptr,
  20760. const bool allow_exceptions = true,
  20761. const bool ignore_comments = false)
  20762. {
  20763. basic_json result;
  20764. parser(i.get(), cb, allow_exceptions, ignore_comments).parse(true, result);
  20765. return result;
  20766. }
  20767. /*!
  20768. @brief check if the input is valid JSON
  20769. Unlike the @ref parse(InputType&&, const parser_callback_t,const bool)
  20770. function, this function neither throws an exception in case of invalid JSON
  20771. input (i.e., a parse error) nor creates diagnostic information.
  20772. @tparam InputType A compatible input, for instance
  20773. - an std::istream object
  20774. - a FILE pointer
  20775. - a C-style array of characters
  20776. - a pointer to a null-terminated string of single byte characters
  20777. - an object obj for which begin(obj) and end(obj) produces a valid pair of
  20778. iterators.
  20779. @param[in] i input to read from
  20780. @param[in] ignore_comments whether comments should be ignored and treated
  20781. like whitespace (true) or yield a parse error (true); (optional, false by
  20782. default)
  20783. @return Whether the input read from @a i is valid JSON.
  20784. @complexity Linear in the length of the input. The parser is a predictive
  20785. LL(1) parser.
  20786. @note A UTF-8 byte order mark is silently ignored.
  20787. @liveexample{The example below demonstrates the `accept()` function reading
  20788. from a string.,accept__string}
  20789. */
  20790. template<typename InputType>
  20791. static bool accept(InputType&& i,
  20792. const bool ignore_comments = false)
  20793. {
  20794. return parser(detail::input_adapter(std::forward<InputType>(i)), nullptr, false, ignore_comments).accept(true);
  20795. }
  20796. template<typename IteratorType>
  20797. static bool accept(IteratorType first, IteratorType last,
  20798. const bool ignore_comments = false)
  20799. {
  20800. return parser(detail::input_adapter(std::move(first), std::move(last)), nullptr, false, ignore_comments).accept(true);
  20801. }
  20802. JSON_HEDLEY_WARN_UNUSED_RESULT
  20803. JSON_HEDLEY_DEPRECATED_FOR(3.8.0, accept(ptr, ptr + len))
  20804. static bool accept(detail::span_input_adapter&& i,
  20805. const bool ignore_comments = false)
  20806. {
  20807. return parser(i.get(), nullptr, false, ignore_comments).accept(true);
  20808. }
  20809. /*!
  20810. @brief generate SAX events
  20811. The SAX event lister must follow the interface of @ref json_sax.
  20812. This function reads from a compatible input. Examples are:
  20813. - an std::istream object
  20814. - a FILE pointer
  20815. - a C-style array of characters
  20816. - a pointer to a null-terminated string of single byte characters
  20817. - an object obj for which begin(obj) and end(obj) produces a valid pair of
  20818. iterators.
  20819. @param[in] i input to read from
  20820. @param[in,out] sax SAX event listener
  20821. @param[in] format the format to parse (JSON, CBOR, MessagePack, or UBJSON)
  20822. @param[in] strict whether the input has to be consumed completely
  20823. @param[in] ignore_comments whether comments should be ignored and treated
  20824. like whitespace (true) or yield a parse error (true); (optional, false by
  20825. default); only applies to the JSON file format.
  20826. @return return value of the last processed SAX event
  20827. @throw parse_error.101 if a parse error occurs; example: `""unexpected end
  20828. of input; expected string literal""`
  20829. @throw parse_error.102 if to_unicode fails or surrogate error
  20830. @throw parse_error.103 if to_unicode fails
  20831. @complexity Linear in the length of the input. The parser is a predictive
  20832. LL(1) parser. The complexity can be higher if the SAX consumer @a sax has
  20833. a super-linear complexity.
  20834. @note A UTF-8 byte order mark is silently ignored.
  20835. @liveexample{The example below demonstrates the `sax_parse()` function
  20836. reading from string and processing the events with a user-defined SAX
  20837. event consumer.,sax_parse}
  20838. @since version 3.2.0
  20839. */
  20840. template <typename InputType, typename SAX>
  20841. JSON_HEDLEY_NON_NULL(2)
  20842. static bool sax_parse(InputType&& i, SAX* sax,
  20843. input_format_t format = input_format_t::json,
  20844. const bool strict = true,
  20845. const bool ignore_comments = false)
  20846. {
  20847. auto ia = detail::input_adapter(std::forward<InputType>(i));
  20848. return format == input_format_t::json
  20849. ? parser(std::move(ia), nullptr, true, ignore_comments).sax_parse(sax, strict)
  20850. : detail::binary_reader<basic_json, decltype(ia), SAX>(std::move(ia)).sax_parse(format, sax, strict);
  20851. }
  20852. template<class IteratorType, class SAX>
  20853. JSON_HEDLEY_NON_NULL(3)
  20854. static bool sax_parse(IteratorType first, IteratorType last, SAX* sax,
  20855. input_format_t format = input_format_t::json,
  20856. const bool strict = true,
  20857. const bool ignore_comments = false)
  20858. {
  20859. auto ia = detail::input_adapter(std::move(first), std::move(last));
  20860. return format == input_format_t::json
  20861. ? parser(std::move(ia), nullptr, true, ignore_comments).sax_parse(sax, strict)
  20862. : detail::binary_reader<basic_json, decltype(ia), SAX>(std::move(ia)).sax_parse(format, sax, strict);
  20863. }
  20864. template <typename SAX>
  20865. JSON_HEDLEY_DEPRECATED_FOR(3.8.0, sax_parse(ptr, ptr + len, ...))
  20866. JSON_HEDLEY_NON_NULL(2)
  20867. static bool sax_parse(detail::span_input_adapter&& i, SAX* sax,
  20868. input_format_t format = input_format_t::json,
  20869. const bool strict = true,
  20870. const bool ignore_comments = false)
  20871. {
  20872. auto ia = i.get();
  20873. return format == input_format_t::json
  20874. // NOLINTNEXTLINE(hicpp-move-const-arg,performance-move-const-arg)
  20875. ? parser(std::move(ia), nullptr, true, ignore_comments).sax_parse(sax, strict)
  20876. // NOLINTNEXTLINE(hicpp-move-const-arg,performance-move-const-arg)
  20877. : detail::binary_reader<basic_json, decltype(ia), SAX>(std::move(ia)).sax_parse(format, sax, strict);
  20878. }
  20879. #ifndef JSON_NO_IO
  20880. /*!
  20881. @brief deserialize from stream
  20882. @deprecated This stream operator is deprecated and will be removed in
  20883. version 4.0.0 of the library. Please use
  20884. @ref operator>>(std::istream&, basic_json&)
  20885. instead; that is, replace calls like `j << i;` with `i >> j;`.
  20886. @since version 1.0.0; deprecated since version 3.0.0
  20887. */
  20888. JSON_HEDLEY_DEPRECATED_FOR(3.0.0, operator>>(std::istream&, basic_json&))
  20889. friend std::istream& operator<<(basic_json& j, std::istream& i)
  20890. {
  20891. return operator>>(i, j);
  20892. }
  20893. /*!
  20894. @brief deserialize from stream
  20895. Deserializes an input stream to a JSON value.
  20896. @param[in,out] i input stream to read a serialized JSON value from
  20897. @param[in,out] j JSON value to write the deserialized input to
  20898. @throw parse_error.101 in case of an unexpected token
  20899. @throw parse_error.102 if to_unicode fails or surrogate error
  20900. @throw parse_error.103 if to_unicode fails
  20901. @complexity Linear in the length of the input. The parser is a predictive
  20902. LL(1) parser.
  20903. @note A UTF-8 byte order mark is silently ignored.
  20904. @liveexample{The example below shows how a JSON value is constructed by
  20905. reading a serialization from a stream.,operator_deserialize}
  20906. @sa parse(std::istream&, const parser_callback_t) for a variant with a
  20907. parser callback function to filter values while parsing
  20908. @since version 1.0.0
  20909. */
  20910. friend std::istream& operator>>(std::istream& i, basic_json& j)
  20911. {
  20912. parser(detail::input_adapter(i)).parse(false, j);
  20913. return i;
  20914. }
  20915. #endif // JSON_NO_IO
  20916. /// @}
  20917. ///////////////////////////
  20918. // convenience functions //
  20919. ///////////////////////////
  20920. /*!
  20921. @brief return the type as string
  20922. Returns the type name as string to be used in error messages - usually to
  20923. indicate that a function was called on a wrong JSON type.
  20924. @return a string representation of a the @a m_type member:
  20925. Value type | return value
  20926. ----------- | -------------
  20927. null | `"null"`
  20928. boolean | `"boolean"`
  20929. string | `"string"`
  20930. number | `"number"` (for all number types)
  20931. object | `"object"`
  20932. array | `"array"`
  20933. binary | `"binary"`
  20934. discarded | `"discarded"`
  20935. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  20936. @complexity Constant.
  20937. @liveexample{The following code exemplifies `type_name()` for all JSON
  20938. types.,type_name}
  20939. @sa see @ref type() -- return the type of the JSON value
  20940. @sa see @ref operator value_t() -- return the type of the JSON value (implicit)
  20941. @since version 1.0.0, public since 2.1.0, `const char*` and `noexcept`
  20942. since 3.0.0
  20943. */
  20944. JSON_HEDLEY_RETURNS_NON_NULL
  20945. const char* type_name() const noexcept
  20946. {
  20947. {
  20948. switch (m_type)
  20949. {
  20950. case value_t::null:
  20951. return "null";
  20952. case value_t::object:
  20953. return "object";
  20954. case value_t::array:
  20955. return "array";
  20956. case value_t::string:
  20957. return "string";
  20958. case value_t::boolean:
  20959. return "boolean";
  20960. case value_t::binary:
  20961. return "binary";
  20962. case value_t::discarded:
  20963. return "discarded";
  20964. case value_t::number_integer:
  20965. case value_t::number_unsigned:
  20966. case value_t::number_float:
  20967. default:
  20968. return "number";
  20969. }
  20970. }
  20971. }
  20972. JSON_PRIVATE_UNLESS_TESTED:
  20973. //////////////////////
  20974. // member variables //
  20975. //////////////////////
  20976. /// the type of the current element
  20977. value_t m_type = value_t::null;
  20978. /// the value of the current element
  20979. json_value m_value = {};
  20980. #if JSON_DIAGNOSTICS
  20981. /// a pointer to a parent value (for debugging purposes)
  20982. basic_json* m_parent = nullptr;
  20983. #endif
  20984. //////////////////////////////////////////
  20985. // binary serialization/deserialization //
  20986. //////////////////////////////////////////
  20987. /// @name binary serialization/deserialization support
  20988. /// @{
  20989. public:
  20990. /*!
  20991. @brief create a CBOR serialization of a given JSON value
  20992. Serializes a given JSON value @a j to a byte vector using the CBOR (Concise
  20993. Binary Object Representation) serialization format. CBOR is a binary
  20994. serialization format which aims to be more compact than JSON itself, yet
  20995. more efficient to parse.
  20996. The library uses the following mapping from JSON values types to
  20997. CBOR types according to the CBOR specification (RFC 7049):
  20998. JSON value type | value/range | CBOR type | first byte
  20999. --------------- | ------------------------------------------ | ---------------------------------- | ---------------
  21000. null | `null` | Null | 0xF6
  21001. boolean | `true` | True | 0xF5
  21002. boolean | `false` | False | 0xF4
  21003. number_integer | -9223372036854775808..-2147483649 | Negative integer (8 bytes follow) | 0x3B
  21004. number_integer | -2147483648..-32769 | Negative integer (4 bytes follow) | 0x3A
  21005. number_integer | -32768..-129 | Negative integer (2 bytes follow) | 0x39
  21006. number_integer | -128..-25 | Negative integer (1 byte follow) | 0x38
  21007. number_integer | -24..-1 | Negative integer | 0x20..0x37
  21008. number_integer | 0..23 | Integer | 0x00..0x17
  21009. number_integer | 24..255 | Unsigned integer (1 byte follow) | 0x18
  21010. number_integer | 256..65535 | Unsigned integer (2 bytes follow) | 0x19
  21011. number_integer | 65536..4294967295 | Unsigned integer (4 bytes follow) | 0x1A
  21012. number_integer | 4294967296..18446744073709551615 | Unsigned integer (8 bytes follow) | 0x1B
  21013. number_unsigned | 0..23 | Integer | 0x00..0x17
  21014. number_unsigned | 24..255 | Unsigned integer (1 byte follow) | 0x18
  21015. number_unsigned | 256..65535 | Unsigned integer (2 bytes follow) | 0x19
  21016. number_unsigned | 65536..4294967295 | Unsigned integer (4 bytes follow) | 0x1A
  21017. number_unsigned | 4294967296..18446744073709551615 | Unsigned integer (8 bytes follow) | 0x1B
  21018. number_float | *any value representable by a float* | Single-Precision Float | 0xFA
  21019. number_float | *any value NOT representable by a float* | Double-Precision Float | 0xFB
  21020. string | *length*: 0..23 | UTF-8 string | 0x60..0x77
  21021. string | *length*: 23..255 | UTF-8 string (1 byte follow) | 0x78
  21022. string | *length*: 256..65535 | UTF-8 string (2 bytes follow) | 0x79
  21023. string | *length*: 65536..4294967295 | UTF-8 string (4 bytes follow) | 0x7A
  21024. string | *length*: 4294967296..18446744073709551615 | UTF-8 string (8 bytes follow) | 0x7B
  21025. array | *size*: 0..23 | array | 0x80..0x97
  21026. array | *size*: 23..255 | array (1 byte follow) | 0x98
  21027. array | *size*: 256..65535 | array (2 bytes follow) | 0x99
  21028. array | *size*: 65536..4294967295 | array (4 bytes follow) | 0x9A
  21029. array | *size*: 4294967296..18446744073709551615 | array (8 bytes follow) | 0x9B
  21030. object | *size*: 0..23 | map | 0xA0..0xB7
  21031. object | *size*: 23..255 | map (1 byte follow) | 0xB8
  21032. object | *size*: 256..65535 | map (2 bytes follow) | 0xB9
  21033. object | *size*: 65536..4294967295 | map (4 bytes follow) | 0xBA
  21034. object | *size*: 4294967296..18446744073709551615 | map (8 bytes follow) | 0xBB
  21035. binary | *size*: 0..23 | byte string | 0x40..0x57
  21036. binary | *size*: 23..255 | byte string (1 byte follow) | 0x58
  21037. binary | *size*: 256..65535 | byte string (2 bytes follow) | 0x59
  21038. binary | *size*: 65536..4294967295 | byte string (4 bytes follow) | 0x5A
  21039. binary | *size*: 4294967296..18446744073709551615 | byte string (8 bytes follow) | 0x5B
  21040. Binary values with subtype are mapped to tagged values (0xD8..0xDB)
  21041. depending on the subtype, followed by a byte string, see "binary" cells
  21042. in the table above.
  21043. @note The mapping is **complete** in the sense that any JSON value type
  21044. can be converted to a CBOR value.
  21045. @note If NaN or Infinity are stored inside a JSON number, they are
  21046. serialized properly. This behavior differs from the @ref dump()
  21047. function which serializes NaN or Infinity to `null`.
  21048. @note The following CBOR types are not used in the conversion:
  21049. - UTF-8 strings terminated by "break" (0x7F)
  21050. - arrays terminated by "break" (0x9F)
  21051. - maps terminated by "break" (0xBF)
  21052. - byte strings terminated by "break" (0x5F)
  21053. - date/time (0xC0..0xC1)
  21054. - bignum (0xC2..0xC3)
  21055. - decimal fraction (0xC4)
  21056. - bigfloat (0xC5)
  21057. - expected conversions (0xD5..0xD7)
  21058. - simple values (0xE0..0xF3, 0xF8)
  21059. - undefined (0xF7)
  21060. - half-precision floats (0xF9)
  21061. - break (0xFF)
  21062. @param[in] j JSON value to serialize
  21063. @return CBOR serialization as byte vector
  21064. @complexity Linear in the size of the JSON value @a j.
  21065. @liveexample{The example shows the serialization of a JSON value to a byte
  21066. vector in CBOR format.,to_cbor}
  21067. @sa http://cbor.io
  21068. @sa see @ref from_cbor(InputType&&, const bool, const bool, const cbor_tag_handler_t) for the
  21069. analogous deserialization
  21070. @sa see @ref to_msgpack(const basic_json&) for the related MessagePack format
  21071. @sa see @ref to_ubjson(const basic_json&, const bool, const bool) for the
  21072. related UBJSON format
  21073. @since version 2.0.9; compact representation of floating-point numbers
  21074. since version 3.8.0
  21075. */
  21076. static std::vector<std::uint8_t> to_cbor(const basic_json& j)
  21077. {
  21078. std::vector<std::uint8_t> result;
  21079. to_cbor(j, result);
  21080. return result;
  21081. }
  21082. static void to_cbor(const basic_json& j, detail::output_adapter<std::uint8_t> o)
  21083. {
  21084. binary_writer<std::uint8_t>(o).write_cbor(j);
  21085. }
  21086. static void to_cbor(const basic_json& j, detail::output_adapter<char> o)
  21087. {
  21088. binary_writer<char>(o).write_cbor(j);
  21089. }
  21090. /*!
  21091. @brief create a MessagePack serialization of a given JSON value
  21092. Serializes a given JSON value @a j to a byte vector using the MessagePack
  21093. serialization format. MessagePack is a binary serialization format which
  21094. aims to be more compact than JSON itself, yet more efficient to parse.
  21095. The library uses the following mapping from JSON values types to
  21096. MessagePack types according to the MessagePack specification:
  21097. JSON value type | value/range | MessagePack type | first byte
  21098. --------------- | --------------------------------- | ---------------- | ----------
  21099. null | `null` | nil | 0xC0
  21100. boolean | `true` | true | 0xC3
  21101. boolean | `false` | false | 0xC2
  21102. number_integer | -9223372036854775808..-2147483649 | int64 | 0xD3
  21103. number_integer | -2147483648..-32769 | int32 | 0xD2
  21104. number_integer | -32768..-129 | int16 | 0xD1
  21105. number_integer | -128..-33 | int8 | 0xD0
  21106. number_integer | -32..-1 | negative fixint | 0xE0..0xFF
  21107. number_integer | 0..127 | positive fixint | 0x00..0x7F
  21108. number_integer | 128..255 | uint 8 | 0xCC
  21109. number_integer | 256..65535 | uint 16 | 0xCD
  21110. number_integer | 65536..4294967295 | uint 32 | 0xCE
  21111. number_integer | 4294967296..18446744073709551615 | uint 64 | 0xCF
  21112. number_unsigned | 0..127 | positive fixint | 0x00..0x7F
  21113. number_unsigned | 128..255 | uint 8 | 0xCC
  21114. number_unsigned | 256..65535 | uint 16 | 0xCD
  21115. number_unsigned | 65536..4294967295 | uint 32 | 0xCE
  21116. number_unsigned | 4294967296..18446744073709551615 | uint 64 | 0xCF
  21117. number_float | *any value representable by a float* | float 32 | 0xCA
  21118. number_float | *any value NOT representable by a float* | float 64 | 0xCB
  21119. string | *length*: 0..31 | fixstr | 0xA0..0xBF
  21120. string | *length*: 32..255 | str 8 | 0xD9
  21121. string | *length*: 256..65535 | str 16 | 0xDA
  21122. string | *length*: 65536..4294967295 | str 32 | 0xDB
  21123. array | *size*: 0..15 | fixarray | 0x90..0x9F
  21124. array | *size*: 16..65535 | array 16 | 0xDC
  21125. array | *size*: 65536..4294967295 | array 32 | 0xDD
  21126. object | *size*: 0..15 | fix map | 0x80..0x8F
  21127. object | *size*: 16..65535 | map 16 | 0xDE
  21128. object | *size*: 65536..4294967295 | map 32 | 0xDF
  21129. binary | *size*: 0..255 | bin 8 | 0xC4
  21130. binary | *size*: 256..65535 | bin 16 | 0xC5
  21131. binary | *size*: 65536..4294967295 | bin 32 | 0xC6
  21132. @note The mapping is **complete** in the sense that any JSON value type
  21133. can be converted to a MessagePack value.
  21134. @note The following values can **not** be converted to a MessagePack value:
  21135. - strings with more than 4294967295 bytes
  21136. - byte strings with more than 4294967295 bytes
  21137. - arrays with more than 4294967295 elements
  21138. - objects with more than 4294967295 elements
  21139. @note Any MessagePack output created @ref to_msgpack can be successfully
  21140. parsed by @ref from_msgpack.
  21141. @note If NaN or Infinity are stored inside a JSON number, they are
  21142. serialized properly. This behavior differs from the @ref dump()
  21143. function which serializes NaN or Infinity to `null`.
  21144. @param[in] j JSON value to serialize
  21145. @return MessagePack serialization as byte vector
  21146. @complexity Linear in the size of the JSON value @a j.
  21147. @liveexample{The example shows the serialization of a JSON value to a byte
  21148. vector in MessagePack format.,to_msgpack}
  21149. @sa http://msgpack.org
  21150. @sa see @ref from_msgpack for the analogous deserialization
  21151. @sa see @ref to_cbor(const basic_json& for the related CBOR format
  21152. @sa see @ref to_ubjson(const basic_json&, const bool, const bool) for the
  21153. related UBJSON format
  21154. @since version 2.0.9
  21155. */
  21156. static std::vector<std::uint8_t> to_msgpack(const basic_json& j)
  21157. {
  21158. std::vector<std::uint8_t> result;
  21159. to_msgpack(j, result);
  21160. return result;
  21161. }
  21162. static void to_msgpack(const basic_json& j, detail::output_adapter<std::uint8_t> o)
  21163. {
  21164. binary_writer<std::uint8_t>(o).write_msgpack(j);
  21165. }
  21166. static void to_msgpack(const basic_json& j, detail::output_adapter<char> o)
  21167. {
  21168. binary_writer<char>(o).write_msgpack(j);
  21169. }
  21170. /*!
  21171. @brief create a UBJSON serialization of a given JSON value
  21172. Serializes a given JSON value @a j to a byte vector using the UBJSON
  21173. (Universal Binary JSON) serialization format. UBJSON aims to be more compact
  21174. than JSON itself, yet more efficient to parse.
  21175. The library uses the following mapping from JSON values types to
  21176. UBJSON types according to the UBJSON specification:
  21177. JSON value type | value/range | UBJSON type | marker
  21178. --------------- | --------------------------------- | ----------- | ------
  21179. null | `null` | null | `Z`
  21180. boolean | `true` | true | `T`
  21181. boolean | `false` | false | `F`
  21182. number_integer | -9223372036854775808..-2147483649 | int64 | `L`
  21183. number_integer | -2147483648..-32769 | int32 | `l`
  21184. number_integer | -32768..-129 | int16 | `I`
  21185. number_integer | -128..127 | int8 | `i`
  21186. number_integer | 128..255 | uint8 | `U`
  21187. number_integer | 256..32767 | int16 | `I`
  21188. number_integer | 32768..2147483647 | int32 | `l`
  21189. number_integer | 2147483648..9223372036854775807 | int64 | `L`
  21190. number_unsigned | 0..127 | int8 | `i`
  21191. number_unsigned | 128..255 | uint8 | `U`
  21192. number_unsigned | 256..32767 | int16 | `I`
  21193. number_unsigned | 32768..2147483647 | int32 | `l`
  21194. number_unsigned | 2147483648..9223372036854775807 | int64 | `L`
  21195. number_unsigned | 2147483649..18446744073709551615 | high-precision | `H`
  21196. number_float | *any value* | float64 | `D`
  21197. string | *with shortest length indicator* | string | `S`
  21198. array | *see notes on optimized format* | array | `[`
  21199. object | *see notes on optimized format* | map | `{`
  21200. @note The mapping is **complete** in the sense that any JSON value type
  21201. can be converted to a UBJSON value.
  21202. @note The following values can **not** be converted to a UBJSON value:
  21203. - strings with more than 9223372036854775807 bytes (theoretical)
  21204. @note The following markers are not used in the conversion:
  21205. - `Z`: no-op values are not created.
  21206. - `C`: single-byte strings are serialized with `S` markers.
  21207. @note Any UBJSON output created @ref to_ubjson can be successfully parsed
  21208. by @ref from_ubjson.
  21209. @note If NaN or Infinity are stored inside a JSON number, they are
  21210. serialized properly. This behavior differs from the @ref dump()
  21211. function which serializes NaN or Infinity to `null`.
  21212. @note The optimized formats for containers are supported: Parameter
  21213. @a use_size adds size information to the beginning of a container and
  21214. removes the closing marker. Parameter @a use_type further checks
  21215. whether all elements of a container have the same type and adds the
  21216. type marker to the beginning of the container. The @a use_type
  21217. parameter must only be used together with @a use_size = true. Note
  21218. that @a use_size = true alone may result in larger representations -
  21219. the benefit of this parameter is that the receiving side is
  21220. immediately informed on the number of elements of the container.
  21221. @note If the JSON data contains the binary type, the value stored is a list
  21222. of integers, as suggested by the UBJSON documentation. In particular,
  21223. this means that serialization and the deserialization of a JSON
  21224. containing binary values into UBJSON and back will result in a
  21225. different JSON object.
  21226. @param[in] j JSON value to serialize
  21227. @param[in] use_size whether to add size annotations to container types
  21228. @param[in] use_type whether to add type annotations to container types
  21229. (must be combined with @a use_size = true)
  21230. @return UBJSON serialization as byte vector
  21231. @complexity Linear in the size of the JSON value @a j.
  21232. @liveexample{The example shows the serialization of a JSON value to a byte
  21233. vector in UBJSON format.,to_ubjson}
  21234. @sa http://ubjson.org
  21235. @sa see @ref from_ubjson(InputType&&, const bool, const bool) for the
  21236. analogous deserialization
  21237. @sa see @ref to_cbor(const basic_json& for the related CBOR format
  21238. @sa see @ref to_msgpack(const basic_json&) for the related MessagePack format
  21239. @since version 3.1.0
  21240. */
  21241. static std::vector<std::uint8_t> to_ubjson(const basic_json& j,
  21242. const bool use_size = false,
  21243. const bool use_type = false)
  21244. {
  21245. std::vector<std::uint8_t> result;
  21246. to_ubjson(j, result, use_size, use_type);
  21247. return result;
  21248. }
  21249. static void to_ubjson(const basic_json& j, detail::output_adapter<std::uint8_t> o,
  21250. const bool use_size = false, const bool use_type = false)
  21251. {
  21252. binary_writer<std::uint8_t>(o).write_ubjson(j, use_size, use_type);
  21253. }
  21254. static void to_ubjson(const basic_json& j, detail::output_adapter<char> o,
  21255. const bool use_size = false, const bool use_type = false)
  21256. {
  21257. binary_writer<char>(o).write_ubjson(j, use_size, use_type);
  21258. }
  21259. /*!
  21260. @brief Serializes the given JSON object `j` to BSON and returns a vector
  21261. containing the corresponding BSON-representation.
  21262. BSON (Binary JSON) is a binary format in which zero or more ordered key/value pairs are
  21263. stored as a single entity (a so-called document).
  21264. The library uses the following mapping from JSON values types to BSON types:
  21265. JSON value type | value/range | BSON type | marker
  21266. --------------- | --------------------------------- | ----------- | ------
  21267. null | `null` | null | 0x0A
  21268. boolean | `true`, `false` | boolean | 0x08
  21269. number_integer | -9223372036854775808..-2147483649 | int64 | 0x12
  21270. number_integer | -2147483648..2147483647 | int32 | 0x10
  21271. number_integer | 2147483648..9223372036854775807 | int64 | 0x12
  21272. number_unsigned | 0..2147483647 | int32 | 0x10
  21273. number_unsigned | 2147483648..9223372036854775807 | int64 | 0x12
  21274. number_unsigned | 9223372036854775808..18446744073709551615| -- | --
  21275. number_float | *any value* | double | 0x01
  21276. string | *any value* | string | 0x02
  21277. array | *any value* | document | 0x04
  21278. object | *any value* | document | 0x03
  21279. binary | *any value* | binary | 0x05
  21280. @warning The mapping is **incomplete**, since only JSON-objects (and things
  21281. contained therein) can be serialized to BSON.
  21282. Also, integers larger than 9223372036854775807 cannot be serialized to BSON,
  21283. and the keys may not contain U+0000, since they are serialized a
  21284. zero-terminated c-strings.
  21285. @throw out_of_range.407 if `j.is_number_unsigned() && j.get<std::uint64_t>() > 9223372036854775807`
  21286. @throw out_of_range.409 if a key in `j` contains a NULL (U+0000)
  21287. @throw type_error.317 if `!j.is_object()`
  21288. @pre The input `j` is required to be an object: `j.is_object() == true`.
  21289. @note Any BSON output created via @ref to_bson can be successfully parsed
  21290. by @ref from_bson.
  21291. @param[in] j JSON value to serialize
  21292. @return BSON serialization as byte vector
  21293. @complexity Linear in the size of the JSON value @a j.
  21294. @liveexample{The example shows the serialization of a JSON value to a byte
  21295. vector in BSON format.,to_bson}
  21296. @sa http://bsonspec.org/spec.html
  21297. @sa see @ref from_bson(detail::input_adapter&&, const bool strict) for the
  21298. analogous deserialization
  21299. @sa see @ref to_ubjson(const basic_json&, const bool, const bool) for the
  21300. related UBJSON format
  21301. @sa see @ref to_cbor(const basic_json&) for the related CBOR format
  21302. @sa see @ref to_msgpack(const basic_json&) for the related MessagePack format
  21303. */
  21304. static std::vector<std::uint8_t> to_bson(const basic_json& j)
  21305. {
  21306. std::vector<std::uint8_t> result;
  21307. to_bson(j, result);
  21308. return result;
  21309. }
  21310. /*!
  21311. @brief Serializes the given JSON object `j` to BSON and forwards the
  21312. corresponding BSON-representation to the given output_adapter `o`.
  21313. @param j The JSON object to convert to BSON.
  21314. @param o The output adapter that receives the binary BSON representation.
  21315. @pre The input `j` shall be an object: `j.is_object() == true`
  21316. @sa see @ref to_bson(const basic_json&)
  21317. */
  21318. static void to_bson(const basic_json& j, detail::output_adapter<std::uint8_t> o)
  21319. {
  21320. binary_writer<std::uint8_t>(o).write_bson(j);
  21321. }
  21322. /*!
  21323. @copydoc to_bson(const basic_json&, detail::output_adapter<std::uint8_t>)
  21324. */
  21325. static void to_bson(const basic_json& j, detail::output_adapter<char> o)
  21326. {
  21327. binary_writer<char>(o).write_bson(j);
  21328. }
  21329. /*!
  21330. @brief create a JSON value from an input in CBOR format
  21331. Deserializes a given input @a i to a JSON value using the CBOR (Concise
  21332. Binary Object Representation) serialization format.
  21333. The library maps CBOR types to JSON value types as follows:
  21334. CBOR type | JSON value type | first byte
  21335. ---------------------- | --------------- | ----------
  21336. Integer | number_unsigned | 0x00..0x17
  21337. Unsigned integer | number_unsigned | 0x18
  21338. Unsigned integer | number_unsigned | 0x19
  21339. Unsigned integer | number_unsigned | 0x1A
  21340. Unsigned integer | number_unsigned | 0x1B
  21341. Negative integer | number_integer | 0x20..0x37
  21342. Negative integer | number_integer | 0x38
  21343. Negative integer | number_integer | 0x39
  21344. Negative integer | number_integer | 0x3A
  21345. Negative integer | number_integer | 0x3B
  21346. Byte string | binary | 0x40..0x57
  21347. Byte string | binary | 0x58
  21348. Byte string | binary | 0x59
  21349. Byte string | binary | 0x5A
  21350. Byte string | binary | 0x5B
  21351. UTF-8 string | string | 0x60..0x77
  21352. UTF-8 string | string | 0x78
  21353. UTF-8 string | string | 0x79
  21354. UTF-8 string | string | 0x7A
  21355. UTF-8 string | string | 0x7B
  21356. UTF-8 string | string | 0x7F
  21357. array | array | 0x80..0x97
  21358. array | array | 0x98
  21359. array | array | 0x99
  21360. array | array | 0x9A
  21361. array | array | 0x9B
  21362. array | array | 0x9F
  21363. map | object | 0xA0..0xB7
  21364. map | object | 0xB8
  21365. map | object | 0xB9
  21366. map | object | 0xBA
  21367. map | object | 0xBB
  21368. map | object | 0xBF
  21369. False | `false` | 0xF4
  21370. True | `true` | 0xF5
  21371. Null | `null` | 0xF6
  21372. Half-Precision Float | number_float | 0xF9
  21373. Single-Precision Float | number_float | 0xFA
  21374. Double-Precision Float | number_float | 0xFB
  21375. @warning The mapping is **incomplete** in the sense that not all CBOR
  21376. types can be converted to a JSON value. The following CBOR types
  21377. are not supported and will yield parse errors (parse_error.112):
  21378. - date/time (0xC0..0xC1)
  21379. - bignum (0xC2..0xC3)
  21380. - decimal fraction (0xC4)
  21381. - bigfloat (0xC5)
  21382. - expected conversions (0xD5..0xD7)
  21383. - simple values (0xE0..0xF3, 0xF8)
  21384. - undefined (0xF7)
  21385. @warning CBOR allows map keys of any type, whereas JSON only allows
  21386. strings as keys in object values. Therefore, CBOR maps with keys
  21387. other than UTF-8 strings are rejected (parse_error.113).
  21388. @note Any CBOR output created @ref to_cbor can be successfully parsed by
  21389. @ref from_cbor.
  21390. @param[in] i an input in CBOR format convertible to an input adapter
  21391. @param[in] strict whether to expect the input to be consumed until EOF
  21392. (true by default)
  21393. @param[in] allow_exceptions whether to throw exceptions in case of a
  21394. parse error (optional, true by default)
  21395. @param[in] tag_handler how to treat CBOR tags (optional, error by default)
  21396. @return deserialized JSON value; in case of a parse error and
  21397. @a allow_exceptions set to `false`, the return value will be
  21398. value_t::discarded.
  21399. @throw parse_error.110 if the given input ends prematurely or the end of
  21400. file was not reached when @a strict was set to true
  21401. @throw parse_error.112 if unsupported features from CBOR were
  21402. used in the given input @a v or if the input is not valid CBOR
  21403. @throw parse_error.113 if a string was expected as map key, but not found
  21404. @complexity Linear in the size of the input @a i.
  21405. @liveexample{The example shows the deserialization of a byte vector in CBOR
  21406. format to a JSON value.,from_cbor}
  21407. @sa http://cbor.io
  21408. @sa see @ref to_cbor(const basic_json&) for the analogous serialization
  21409. @sa see @ref from_msgpack(InputType&&, const bool, const bool) for the
  21410. related MessagePack format
  21411. @sa see @ref from_ubjson(InputType&&, const bool, const bool) for the
  21412. related UBJSON format
  21413. @since version 2.0.9; parameter @a start_index since 2.1.1; changed to
  21414. consume input adapters, removed start_index parameter, and added
  21415. @a strict parameter since 3.0.0; added @a allow_exceptions parameter
  21416. since 3.2.0; added @a tag_handler parameter since 3.9.0.
  21417. */
  21418. template<typename InputType>
  21419. JSON_HEDLEY_WARN_UNUSED_RESULT
  21420. static basic_json from_cbor(InputType&& i,
  21421. const bool strict = true,
  21422. const bool allow_exceptions = true,
  21423. const cbor_tag_handler_t tag_handler = cbor_tag_handler_t::error)
  21424. {
  21425. basic_json result;
  21426. detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
  21427. auto ia = detail::input_adapter(std::forward<InputType>(i));
  21428. const bool res = binary_reader<decltype(ia)>(std::move(ia)).sax_parse(input_format_t::cbor, &sdp, strict, tag_handler);
  21429. return res ? result : basic_json(value_t::discarded);
  21430. }
  21431. /*!
  21432. @copydoc from_cbor(InputType&&, const bool, const bool, const cbor_tag_handler_t)
  21433. */
  21434. template<typename IteratorType>
  21435. JSON_HEDLEY_WARN_UNUSED_RESULT
  21436. static basic_json from_cbor(IteratorType first, IteratorType last,
  21437. const bool strict = true,
  21438. const bool allow_exceptions = true,
  21439. const cbor_tag_handler_t tag_handler = cbor_tag_handler_t::error)
  21440. {
  21441. basic_json result;
  21442. detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
  21443. auto ia = detail::input_adapter(std::move(first), std::move(last));
  21444. const bool res = binary_reader<decltype(ia)>(std::move(ia)).sax_parse(input_format_t::cbor, &sdp, strict, tag_handler);
  21445. return res ? result : basic_json(value_t::discarded);
  21446. }
  21447. template<typename T>
  21448. JSON_HEDLEY_WARN_UNUSED_RESULT
  21449. JSON_HEDLEY_DEPRECATED_FOR(3.8.0, from_cbor(ptr, ptr + len))
  21450. static basic_json from_cbor(const T* ptr, std::size_t len,
  21451. const bool strict = true,
  21452. const bool allow_exceptions = true,
  21453. const cbor_tag_handler_t tag_handler = cbor_tag_handler_t::error)
  21454. {
  21455. return from_cbor(ptr, ptr + len, strict, allow_exceptions, tag_handler);
  21456. }
  21457. JSON_HEDLEY_WARN_UNUSED_RESULT
  21458. JSON_HEDLEY_DEPRECATED_FOR(3.8.0, from_cbor(ptr, ptr + len))
  21459. static basic_json from_cbor(detail::span_input_adapter&& i,
  21460. const bool strict = true,
  21461. const bool allow_exceptions = true,
  21462. const cbor_tag_handler_t tag_handler = cbor_tag_handler_t::error)
  21463. {
  21464. basic_json result;
  21465. detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
  21466. auto ia = i.get();
  21467. // NOLINTNEXTLINE(hicpp-move-const-arg,performance-move-const-arg)
  21468. const bool res = binary_reader<decltype(ia)>(std::move(ia)).sax_parse(input_format_t::cbor, &sdp, strict, tag_handler);
  21469. return res ? result : basic_json(value_t::discarded);
  21470. }
  21471. /*!
  21472. @brief create a JSON value from an input in MessagePack format
  21473. Deserializes a given input @a i to a JSON value using the MessagePack
  21474. serialization format.
  21475. The library maps MessagePack types to JSON value types as follows:
  21476. MessagePack type | JSON value type | first byte
  21477. ---------------- | --------------- | ----------
  21478. positive fixint | number_unsigned | 0x00..0x7F
  21479. fixmap | object | 0x80..0x8F
  21480. fixarray | array | 0x90..0x9F
  21481. fixstr | string | 0xA0..0xBF
  21482. nil | `null` | 0xC0
  21483. false | `false` | 0xC2
  21484. true | `true` | 0xC3
  21485. float 32 | number_float | 0xCA
  21486. float 64 | number_float | 0xCB
  21487. uint 8 | number_unsigned | 0xCC
  21488. uint 16 | number_unsigned | 0xCD
  21489. uint 32 | number_unsigned | 0xCE
  21490. uint 64 | number_unsigned | 0xCF
  21491. int 8 | number_integer | 0xD0
  21492. int 16 | number_integer | 0xD1
  21493. int 32 | number_integer | 0xD2
  21494. int 64 | number_integer | 0xD3
  21495. str 8 | string | 0xD9
  21496. str 16 | string | 0xDA
  21497. str 32 | string | 0xDB
  21498. array 16 | array | 0xDC
  21499. array 32 | array | 0xDD
  21500. map 16 | object | 0xDE
  21501. map 32 | object | 0xDF
  21502. bin 8 | binary | 0xC4
  21503. bin 16 | binary | 0xC5
  21504. bin 32 | binary | 0xC6
  21505. ext 8 | binary | 0xC7
  21506. ext 16 | binary | 0xC8
  21507. ext 32 | binary | 0xC9
  21508. fixext 1 | binary | 0xD4
  21509. fixext 2 | binary | 0xD5
  21510. fixext 4 | binary | 0xD6
  21511. fixext 8 | binary | 0xD7
  21512. fixext 16 | binary | 0xD8
  21513. negative fixint | number_integer | 0xE0-0xFF
  21514. @note Any MessagePack output created @ref to_msgpack can be successfully
  21515. parsed by @ref from_msgpack.
  21516. @param[in] i an input in MessagePack format convertible to an input
  21517. adapter
  21518. @param[in] strict whether to expect the input to be consumed until EOF
  21519. (true by default)
  21520. @param[in] allow_exceptions whether to throw exceptions in case of a
  21521. parse error (optional, true by default)
  21522. @return deserialized JSON value; in case of a parse error and
  21523. @a allow_exceptions set to `false`, the return value will be
  21524. value_t::discarded.
  21525. @throw parse_error.110 if the given input ends prematurely or the end of
  21526. file was not reached when @a strict was set to true
  21527. @throw parse_error.112 if unsupported features from MessagePack were
  21528. used in the given input @a i or if the input is not valid MessagePack
  21529. @throw parse_error.113 if a string was expected as map key, but not found
  21530. @complexity Linear in the size of the input @a i.
  21531. @liveexample{The example shows the deserialization of a byte vector in
  21532. MessagePack format to a JSON value.,from_msgpack}
  21533. @sa http://msgpack.org
  21534. @sa see @ref to_msgpack(const basic_json&) for the analogous serialization
  21535. @sa see @ref from_cbor(InputType&&, const bool, const bool, const cbor_tag_handler_t) for the
  21536. related CBOR format
  21537. @sa see @ref from_ubjson(InputType&&, const bool, const bool) for
  21538. the related UBJSON format
  21539. @sa see @ref from_bson(InputType&&, const bool, const bool) for
  21540. the related BSON format
  21541. @since version 2.0.9; parameter @a start_index since 2.1.1; changed to
  21542. consume input adapters, removed start_index parameter, and added
  21543. @a strict parameter since 3.0.0; added @a allow_exceptions parameter
  21544. since 3.2.0
  21545. */
  21546. template<typename InputType>
  21547. JSON_HEDLEY_WARN_UNUSED_RESULT
  21548. static basic_json from_msgpack(InputType&& i,
  21549. const bool strict = true,
  21550. const bool allow_exceptions = true)
  21551. {
  21552. basic_json result;
  21553. detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
  21554. auto ia = detail::input_adapter(std::forward<InputType>(i));
  21555. const bool res = binary_reader<decltype(ia)>(std::move(ia)).sax_parse(input_format_t::msgpack, &sdp, strict);
  21556. return res ? result : basic_json(value_t::discarded);
  21557. }
  21558. /*!
  21559. @copydoc from_msgpack(InputType&&, const bool, const bool)
  21560. */
  21561. template<typename IteratorType>
  21562. JSON_HEDLEY_WARN_UNUSED_RESULT
  21563. static basic_json from_msgpack(IteratorType first, IteratorType last,
  21564. const bool strict = true,
  21565. const bool allow_exceptions = true)
  21566. {
  21567. basic_json result;
  21568. detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
  21569. auto ia = detail::input_adapter(std::move(first), std::move(last));
  21570. const bool res = binary_reader<decltype(ia)>(std::move(ia)).sax_parse(input_format_t::msgpack, &sdp, strict);
  21571. return res ? result : basic_json(value_t::discarded);
  21572. }
  21573. template<typename T>
  21574. JSON_HEDLEY_WARN_UNUSED_RESULT
  21575. JSON_HEDLEY_DEPRECATED_FOR(3.8.0, from_msgpack(ptr, ptr + len))
  21576. static basic_json from_msgpack(const T* ptr, std::size_t len,
  21577. const bool strict = true,
  21578. const bool allow_exceptions = true)
  21579. {
  21580. return from_msgpack(ptr, ptr + len, strict, allow_exceptions);
  21581. }
  21582. JSON_HEDLEY_WARN_UNUSED_RESULT
  21583. JSON_HEDLEY_DEPRECATED_FOR(3.8.0, from_msgpack(ptr, ptr + len))
  21584. static basic_json from_msgpack(detail::span_input_adapter&& i,
  21585. const bool strict = true,
  21586. const bool allow_exceptions = true)
  21587. {
  21588. basic_json result;
  21589. detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
  21590. auto ia = i.get();
  21591. // NOLINTNEXTLINE(hicpp-move-const-arg,performance-move-const-arg)
  21592. const bool res = binary_reader<decltype(ia)>(std::move(ia)).sax_parse(input_format_t::msgpack, &sdp, strict);
  21593. return res ? result : basic_json(value_t::discarded);
  21594. }
  21595. /*!
  21596. @brief create a JSON value from an input in UBJSON format
  21597. Deserializes a given input @a i to a JSON value using the UBJSON (Universal
  21598. Binary JSON) serialization format.
  21599. The library maps UBJSON types to JSON value types as follows:
  21600. UBJSON type | JSON value type | marker
  21601. ----------- | --------------------------------------- | ------
  21602. no-op | *no value, next value is read* | `N`
  21603. null | `null` | `Z`
  21604. false | `false` | `F`
  21605. true | `true` | `T`
  21606. float32 | number_float | `d`
  21607. float64 | number_float | `D`
  21608. uint8 | number_unsigned | `U`
  21609. int8 | number_integer | `i`
  21610. int16 | number_integer | `I`
  21611. int32 | number_integer | `l`
  21612. int64 | number_integer | `L`
  21613. high-precision number | number_integer, number_unsigned, or number_float - depends on number string | 'H'
  21614. string | string | `S`
  21615. char | string | `C`
  21616. array | array (optimized values are supported) | `[`
  21617. object | object (optimized values are supported) | `{`
  21618. @note The mapping is **complete** in the sense that any UBJSON value can
  21619. be converted to a JSON value.
  21620. @param[in] i an input in UBJSON format convertible to an input adapter
  21621. @param[in] strict whether to expect the input to be consumed until EOF
  21622. (true by default)
  21623. @param[in] allow_exceptions whether to throw exceptions in case of a
  21624. parse error (optional, true by default)
  21625. @return deserialized JSON value; in case of a parse error and
  21626. @a allow_exceptions set to `false`, the return value will be
  21627. value_t::discarded.
  21628. @throw parse_error.110 if the given input ends prematurely or the end of
  21629. file was not reached when @a strict was set to true
  21630. @throw parse_error.112 if a parse error occurs
  21631. @throw parse_error.113 if a string could not be parsed successfully
  21632. @complexity Linear in the size of the input @a i.
  21633. @liveexample{The example shows the deserialization of a byte vector in
  21634. UBJSON format to a JSON value.,from_ubjson}
  21635. @sa http://ubjson.org
  21636. @sa see @ref to_ubjson(const basic_json&, const bool, const bool) for the
  21637. analogous serialization
  21638. @sa see @ref from_cbor(InputType&&, const bool, const bool, const cbor_tag_handler_t) for the
  21639. related CBOR format
  21640. @sa see @ref from_msgpack(InputType&&, const bool, const bool) for
  21641. the related MessagePack format
  21642. @sa see @ref from_bson(InputType&&, const bool, const bool) for
  21643. the related BSON format
  21644. @since version 3.1.0; added @a allow_exceptions parameter since 3.2.0
  21645. */
  21646. template<typename InputType>
  21647. JSON_HEDLEY_WARN_UNUSED_RESULT
  21648. static basic_json from_ubjson(InputType&& i,
  21649. const bool strict = true,
  21650. const bool allow_exceptions = true)
  21651. {
  21652. basic_json result;
  21653. detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
  21654. auto ia = detail::input_adapter(std::forward<InputType>(i));
  21655. const bool res = binary_reader<decltype(ia)>(std::move(ia)).sax_parse(input_format_t::ubjson, &sdp, strict);
  21656. return res ? result : basic_json(value_t::discarded);
  21657. }
  21658. /*!
  21659. @copydoc from_ubjson(InputType&&, const bool, const bool)
  21660. */
  21661. template<typename IteratorType>
  21662. JSON_HEDLEY_WARN_UNUSED_RESULT
  21663. static basic_json from_ubjson(IteratorType first, IteratorType last,
  21664. const bool strict = true,
  21665. const bool allow_exceptions = true)
  21666. {
  21667. basic_json result;
  21668. detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
  21669. auto ia = detail::input_adapter(std::move(first), std::move(last));
  21670. const bool res = binary_reader<decltype(ia)>(std::move(ia)).sax_parse(input_format_t::ubjson, &sdp, strict);
  21671. return res ? result : basic_json(value_t::discarded);
  21672. }
  21673. template<typename T>
  21674. JSON_HEDLEY_WARN_UNUSED_RESULT
  21675. JSON_HEDLEY_DEPRECATED_FOR(3.8.0, from_ubjson(ptr, ptr + len))
  21676. static basic_json from_ubjson(const T* ptr, std::size_t len,
  21677. const bool strict = true,
  21678. const bool allow_exceptions = true)
  21679. {
  21680. return from_ubjson(ptr, ptr + len, strict, allow_exceptions);
  21681. }
  21682. JSON_HEDLEY_WARN_UNUSED_RESULT
  21683. JSON_HEDLEY_DEPRECATED_FOR(3.8.0, from_ubjson(ptr, ptr + len))
  21684. static basic_json from_ubjson(detail::span_input_adapter&& i,
  21685. const bool strict = true,
  21686. const bool allow_exceptions = true)
  21687. {
  21688. basic_json result;
  21689. detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
  21690. auto ia = i.get();
  21691. // NOLINTNEXTLINE(hicpp-move-const-arg,performance-move-const-arg)
  21692. const bool res = binary_reader<decltype(ia)>(std::move(ia)).sax_parse(input_format_t::ubjson, &sdp, strict);
  21693. return res ? result : basic_json(value_t::discarded);
  21694. }
  21695. /*!
  21696. @brief Create a JSON value from an input in BSON format
  21697. Deserializes a given input @a i to a JSON value using the BSON (Binary JSON)
  21698. serialization format.
  21699. The library maps BSON record types to JSON value types as follows:
  21700. BSON type | BSON marker byte | JSON value type
  21701. --------------- | ---------------- | ---------------------------
  21702. double | 0x01 | number_float
  21703. string | 0x02 | string
  21704. document | 0x03 | object
  21705. array | 0x04 | array
  21706. binary | 0x05 | binary
  21707. undefined | 0x06 | still unsupported
  21708. ObjectId | 0x07 | still unsupported
  21709. boolean | 0x08 | boolean
  21710. UTC Date-Time | 0x09 | still unsupported
  21711. null | 0x0A | null
  21712. Regular Expr. | 0x0B | still unsupported
  21713. DB Pointer | 0x0C | still unsupported
  21714. JavaScript Code | 0x0D | still unsupported
  21715. Symbol | 0x0E | still unsupported
  21716. JavaScript Code | 0x0F | still unsupported
  21717. int32 | 0x10 | number_integer
  21718. Timestamp | 0x11 | still unsupported
  21719. 128-bit decimal float | 0x13 | still unsupported
  21720. Max Key | 0x7F | still unsupported
  21721. Min Key | 0xFF | still unsupported
  21722. @warning The mapping is **incomplete**. The unsupported mappings
  21723. are indicated in the table above.
  21724. @param[in] i an input in BSON format convertible to an input adapter
  21725. @param[in] strict whether to expect the input to be consumed until EOF
  21726. (true by default)
  21727. @param[in] allow_exceptions whether to throw exceptions in case of a
  21728. parse error (optional, true by default)
  21729. @return deserialized JSON value; in case of a parse error and
  21730. @a allow_exceptions set to `false`, the return value will be
  21731. value_t::discarded.
  21732. @throw parse_error.114 if an unsupported BSON record type is encountered
  21733. @complexity Linear in the size of the input @a i.
  21734. @liveexample{The example shows the deserialization of a byte vector in
  21735. BSON format to a JSON value.,from_bson}
  21736. @sa http://bsonspec.org/spec.html
  21737. @sa see @ref to_bson(const basic_json&) for the analogous serialization
  21738. @sa see @ref from_cbor(InputType&&, const bool, const bool, const cbor_tag_handler_t) for the
  21739. related CBOR format
  21740. @sa see @ref from_msgpack(InputType&&, const bool, const bool) for
  21741. the related MessagePack format
  21742. @sa see @ref from_ubjson(InputType&&, const bool, const bool) for the
  21743. related UBJSON format
  21744. */
  21745. template<typename InputType>
  21746. JSON_HEDLEY_WARN_UNUSED_RESULT
  21747. static basic_json from_bson(InputType&& i,
  21748. const bool strict = true,
  21749. const bool allow_exceptions = true)
  21750. {
  21751. basic_json result;
  21752. detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
  21753. auto ia = detail::input_adapter(std::forward<InputType>(i));
  21754. const bool res = binary_reader<decltype(ia)>(std::move(ia)).sax_parse(input_format_t::bson, &sdp, strict);
  21755. return res ? result : basic_json(value_t::discarded);
  21756. }
  21757. /*!
  21758. @copydoc from_bson(InputType&&, const bool, const bool)
  21759. */
  21760. template<typename IteratorType>
  21761. JSON_HEDLEY_WARN_UNUSED_RESULT
  21762. static basic_json from_bson(IteratorType first, IteratorType last,
  21763. const bool strict = true,
  21764. const bool allow_exceptions = true)
  21765. {
  21766. basic_json result;
  21767. detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
  21768. auto ia = detail::input_adapter(std::move(first), std::move(last));
  21769. const bool res = binary_reader<decltype(ia)>(std::move(ia)).sax_parse(input_format_t::bson, &sdp, strict);
  21770. return res ? result : basic_json(value_t::discarded);
  21771. }
  21772. template<typename T>
  21773. JSON_HEDLEY_WARN_UNUSED_RESULT
  21774. JSON_HEDLEY_DEPRECATED_FOR(3.8.0, from_bson(ptr, ptr + len))
  21775. static basic_json from_bson(const T* ptr, std::size_t len,
  21776. const bool strict = true,
  21777. const bool allow_exceptions = true)
  21778. {
  21779. return from_bson(ptr, ptr + len, strict, allow_exceptions);
  21780. }
  21781. JSON_HEDLEY_WARN_UNUSED_RESULT
  21782. JSON_HEDLEY_DEPRECATED_FOR(3.8.0, from_bson(ptr, ptr + len))
  21783. static basic_json from_bson(detail::span_input_adapter&& i,
  21784. const bool strict = true,
  21785. const bool allow_exceptions = true)
  21786. {
  21787. basic_json result;
  21788. detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
  21789. auto ia = i.get();
  21790. // NOLINTNEXTLINE(hicpp-move-const-arg,performance-move-const-arg)
  21791. const bool res = binary_reader<decltype(ia)>(std::move(ia)).sax_parse(input_format_t::bson, &sdp, strict);
  21792. return res ? result : basic_json(value_t::discarded);
  21793. }
  21794. /// @}
  21795. //////////////////////////
  21796. // JSON Pointer support //
  21797. //////////////////////////
  21798. /// @name JSON Pointer functions
  21799. /// @{
  21800. /*!
  21801. @brief access specified element via JSON Pointer
  21802. Uses a JSON pointer to retrieve a reference to the respective JSON value.
  21803. No bound checking is performed. Similar to @ref operator[](const typename
  21804. object_t::key_type&), `null` values are created in arrays and objects if
  21805. necessary.
  21806. In particular:
  21807. - If the JSON pointer points to an object key that does not exist, it
  21808. is created an filled with a `null` value before a reference to it
  21809. is returned.
  21810. - If the JSON pointer points to an array index that does not exist, it
  21811. is created an filled with a `null` value before a reference to it
  21812. is returned. All indices between the current maximum and the given
  21813. index are also filled with `null`.
  21814. - The special value `-` is treated as a synonym for the index past the
  21815. end.
  21816. @param[in] ptr a JSON pointer
  21817. @return reference to the element pointed to by @a ptr
  21818. @complexity Constant.
  21819. @throw parse_error.106 if an array index begins with '0'
  21820. @throw parse_error.109 if an array index was not a number
  21821. @throw out_of_range.404 if the JSON pointer can not be resolved
  21822. @liveexample{The behavior is shown in the example.,operatorjson_pointer}
  21823. @since version 2.0.0
  21824. */
  21825. reference operator[](const json_pointer& ptr)
  21826. {
  21827. return ptr.get_unchecked(this);
  21828. }
  21829. /*!
  21830. @brief access specified element via JSON Pointer
  21831. Uses a JSON pointer to retrieve a reference to the respective JSON value.
  21832. No bound checking is performed. The function does not change the JSON
  21833. value; no `null` values are created. In particular, the special value
  21834. `-` yields an exception.
  21835. @param[in] ptr JSON pointer to the desired element
  21836. @return const reference to the element pointed to by @a ptr
  21837. @complexity Constant.
  21838. @throw parse_error.106 if an array index begins with '0'
  21839. @throw parse_error.109 if an array index was not a number
  21840. @throw out_of_range.402 if the array index '-' is used
  21841. @throw out_of_range.404 if the JSON pointer can not be resolved
  21842. @liveexample{The behavior is shown in the example.,operatorjson_pointer_const}
  21843. @since version 2.0.0
  21844. */
  21845. const_reference operator[](const json_pointer& ptr) const
  21846. {
  21847. return ptr.get_unchecked(this);
  21848. }
  21849. /*!
  21850. @brief access specified element via JSON Pointer
  21851. Returns a reference to the element at with specified JSON pointer @a ptr,
  21852. with bounds checking.
  21853. @param[in] ptr JSON pointer to the desired element
  21854. @return reference to the element pointed to by @a ptr
  21855. @throw parse_error.106 if an array index in the passed JSON pointer @a ptr
  21856. begins with '0'. See example below.
  21857. @throw parse_error.109 if an array index in the passed JSON pointer @a ptr
  21858. is not a number. See example below.
  21859. @throw out_of_range.401 if an array index in the passed JSON pointer @a ptr
  21860. is out of range. See example below.
  21861. @throw out_of_range.402 if the array index '-' is used in the passed JSON
  21862. pointer @a ptr. As `at` provides checked access (and no elements are
  21863. implicitly inserted), the index '-' is always invalid. See example below.
  21864. @throw out_of_range.403 if the JSON pointer describes a key of an object
  21865. which cannot be found. See example below.
  21866. @throw out_of_range.404 if the JSON pointer @a ptr can not be resolved.
  21867. See example below.
  21868. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  21869. changes in the JSON value.
  21870. @complexity Constant.
  21871. @since version 2.0.0
  21872. @liveexample{The behavior is shown in the example.,at_json_pointer}
  21873. */
  21874. reference at(const json_pointer& ptr)
  21875. {
  21876. return ptr.get_checked(this);
  21877. }
  21878. /*!
  21879. @brief access specified element via JSON Pointer
  21880. Returns a const reference to the element at with specified JSON pointer @a
  21881. ptr, with bounds checking.
  21882. @param[in] ptr JSON pointer to the desired element
  21883. @return reference to the element pointed to by @a ptr
  21884. @throw parse_error.106 if an array index in the passed JSON pointer @a ptr
  21885. begins with '0'. See example below.
  21886. @throw parse_error.109 if an array index in the passed JSON pointer @a ptr
  21887. is not a number. See example below.
  21888. @throw out_of_range.401 if an array index in the passed JSON pointer @a ptr
  21889. is out of range. See example below.
  21890. @throw out_of_range.402 if the array index '-' is used in the passed JSON
  21891. pointer @a ptr. As `at` provides checked access (and no elements are
  21892. implicitly inserted), the index '-' is always invalid. See example below.
  21893. @throw out_of_range.403 if the JSON pointer describes a key of an object
  21894. which cannot be found. See example below.
  21895. @throw out_of_range.404 if the JSON pointer @a ptr can not be resolved.
  21896. See example below.
  21897. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  21898. changes in the JSON value.
  21899. @complexity Constant.
  21900. @since version 2.0.0
  21901. @liveexample{The behavior is shown in the example.,at_json_pointer_const}
  21902. */
  21903. const_reference at(const json_pointer& ptr) const
  21904. {
  21905. return ptr.get_checked(this);
  21906. }
  21907. /*!
  21908. @brief return flattened JSON value
  21909. The function creates a JSON object whose keys are JSON pointers (see [RFC
  21910. 6901](https://tools.ietf.org/html/rfc6901)) and whose values are all
  21911. primitive. The original JSON value can be restored using the @ref
  21912. unflatten() function.
  21913. @return an object that maps JSON pointers to primitive values
  21914. @note Empty objects and arrays are flattened to `null` and will not be
  21915. reconstructed correctly by the @ref unflatten() function.
  21916. @complexity Linear in the size the JSON value.
  21917. @liveexample{The following code shows how a JSON object is flattened to an
  21918. object whose keys consist of JSON pointers.,flatten}
  21919. @sa see @ref unflatten() for the reverse function
  21920. @since version 2.0.0
  21921. */
  21922. basic_json flatten() const
  21923. {
  21924. basic_json result(value_t::object);
  21925. json_pointer::flatten("", *this, result);
  21926. return result;
  21927. }
  21928. /*!
  21929. @brief unflatten a previously flattened JSON value
  21930. The function restores the arbitrary nesting of a JSON value that has been
  21931. flattened before using the @ref flatten() function. The JSON value must
  21932. meet certain constraints:
  21933. 1. The value must be an object.
  21934. 2. The keys must be JSON pointers (see
  21935. [RFC 6901](https://tools.ietf.org/html/rfc6901))
  21936. 3. The mapped values must be primitive JSON types.
  21937. @return the original JSON from a flattened version
  21938. @note Empty objects and arrays are flattened by @ref flatten() to `null`
  21939. values and can not unflattened to their original type. Apart from
  21940. this example, for a JSON value `j`, the following is always true:
  21941. `j == j.flatten().unflatten()`.
  21942. @complexity Linear in the size the JSON value.
  21943. @throw type_error.314 if value is not an object
  21944. @throw type_error.315 if object values are not primitive
  21945. @liveexample{The following code shows how a flattened JSON object is
  21946. unflattened into the original nested JSON object.,unflatten}
  21947. @sa see @ref flatten() for the reverse function
  21948. @since version 2.0.0
  21949. */
  21950. basic_json unflatten() const
  21951. {
  21952. return json_pointer::unflatten(*this);
  21953. }
  21954. /// @}
  21955. //////////////////////////
  21956. // JSON Patch functions //
  21957. //////////////////////////
  21958. /// @name JSON Patch functions
  21959. /// @{
  21960. /*!
  21961. @brief applies a JSON patch
  21962. [JSON Patch](http://jsonpatch.com) defines a JSON document structure for
  21963. expressing a sequence of operations to apply to a JSON) document. With
  21964. this function, a JSON Patch is applied to the current JSON value by
  21965. executing all operations from the patch.
  21966. @param[in] json_patch JSON patch document
  21967. @return patched document
  21968. @note The application of a patch is atomic: Either all operations succeed
  21969. and the patched document is returned or an exception is thrown. In
  21970. any case, the original value is not changed: the patch is applied
  21971. to a copy of the value.
  21972. @throw parse_error.104 if the JSON patch does not consist of an array of
  21973. objects
  21974. @throw parse_error.105 if the JSON patch is malformed (e.g., mandatory
  21975. attributes are missing); example: `"operation add must have member path"`
  21976. @throw out_of_range.401 if an array index is out of range.
  21977. @throw out_of_range.403 if a JSON pointer inside the patch could not be
  21978. resolved successfully in the current JSON value; example: `"key baz not
  21979. found"`
  21980. @throw out_of_range.405 if JSON pointer has no parent ("add", "remove",
  21981. "move")
  21982. @throw other_error.501 if "test" operation was unsuccessful
  21983. @complexity Linear in the size of the JSON value and the length of the
  21984. JSON patch. As usually only a fraction of the JSON value is affected by
  21985. the patch, the complexity can usually be neglected.
  21986. @liveexample{The following code shows how a JSON patch is applied to a
  21987. value.,patch}
  21988. @sa see @ref diff -- create a JSON patch by comparing two JSON values
  21989. @sa [RFC 6902 (JSON Patch)](https://tools.ietf.org/html/rfc6902)
  21990. @sa [RFC 6901 (JSON Pointer)](https://tools.ietf.org/html/rfc6901)
  21991. @since version 2.0.0
  21992. */
  21993. basic_json patch(const basic_json& json_patch) const
  21994. {
  21995. // make a working copy to apply the patch to
  21996. basic_json result = *this;
  21997. // the valid JSON Patch operations
  21998. enum class patch_operations {add, remove, replace, move, copy, test, invalid};
  21999. const auto get_op = [](const std::string & op)
  22000. {
  22001. if (op == "add")
  22002. {
  22003. return patch_operations::add;
  22004. }
  22005. if (op == "remove")
  22006. {
  22007. return patch_operations::remove;
  22008. }
  22009. if (op == "replace")
  22010. {
  22011. return patch_operations::replace;
  22012. }
  22013. if (op == "move")
  22014. {
  22015. return patch_operations::move;
  22016. }
  22017. if (op == "copy")
  22018. {
  22019. return patch_operations::copy;
  22020. }
  22021. if (op == "test")
  22022. {
  22023. return patch_operations::test;
  22024. }
  22025. return patch_operations::invalid;
  22026. };
  22027. // wrapper for "add" operation; add value at ptr
  22028. const auto operation_add = [&result](json_pointer & ptr, basic_json val)
  22029. {
  22030. // adding to the root of the target document means replacing it
  22031. if (ptr.empty())
  22032. {
  22033. result = val;
  22034. return;
  22035. }
  22036. // make sure the top element of the pointer exists
  22037. json_pointer top_pointer = ptr.top();
  22038. if (top_pointer != ptr)
  22039. {
  22040. result.at(top_pointer);
  22041. }
  22042. // get reference to parent of JSON pointer ptr
  22043. const auto last_path = ptr.back();
  22044. ptr.pop_back();
  22045. basic_json& parent = result[ptr];
  22046. switch (parent.m_type)
  22047. {
  22048. case value_t::null:
  22049. case value_t::object:
  22050. {
  22051. // use operator[] to add value
  22052. parent[last_path] = val;
  22053. break;
  22054. }
  22055. case value_t::array:
  22056. {
  22057. if (last_path == "-")
  22058. {
  22059. // special case: append to back
  22060. parent.push_back(val);
  22061. }
  22062. else
  22063. {
  22064. const auto idx = json_pointer::array_index(last_path);
  22065. if (JSON_HEDLEY_UNLIKELY(idx > parent.size()))
  22066. {
  22067. // avoid undefined behavior
  22068. JSON_THROW(out_of_range::create(401, "array index " + std::to_string(idx) + " is out of range", parent));
  22069. }
  22070. // default case: insert add offset
  22071. parent.insert(parent.begin() + static_cast<difference_type>(idx), val);
  22072. }
  22073. break;
  22074. }
  22075. // if there exists a parent it cannot be primitive
  22076. case value_t::string: // LCOV_EXCL_LINE
  22077. case value_t::boolean: // LCOV_EXCL_LINE
  22078. case value_t::number_integer: // LCOV_EXCL_LINE
  22079. case value_t::number_unsigned: // LCOV_EXCL_LINE
  22080. case value_t::number_float: // LCOV_EXCL_LINE
  22081. case value_t::binary: // LCOV_EXCL_LINE
  22082. case value_t::discarded: // LCOV_EXCL_LINE
  22083. default: // LCOV_EXCL_LINE
  22084. JSON_ASSERT(false); // NOLINT(cert-dcl03-c,hicpp-static-assert,misc-static-assert) LCOV_EXCL_LINE
  22085. }
  22086. };
  22087. // wrapper for "remove" operation; remove value at ptr
  22088. const auto operation_remove = [this, &result](json_pointer & ptr)
  22089. {
  22090. // get reference to parent of JSON pointer ptr
  22091. const auto last_path = ptr.back();
  22092. ptr.pop_back();
  22093. basic_json& parent = result.at(ptr);
  22094. // remove child
  22095. if (parent.is_object())
  22096. {
  22097. // perform range check
  22098. auto it = parent.find(last_path);
  22099. if (JSON_HEDLEY_LIKELY(it != parent.end()))
  22100. {
  22101. parent.erase(it);
  22102. }
  22103. else
  22104. {
  22105. JSON_THROW(out_of_range::create(403, "key '" + last_path + "' not found", *this));
  22106. }
  22107. }
  22108. else if (parent.is_array())
  22109. {
  22110. // note erase performs range check
  22111. parent.erase(json_pointer::array_index(last_path));
  22112. }
  22113. };
  22114. // type check: top level value must be an array
  22115. if (JSON_HEDLEY_UNLIKELY(!json_patch.is_array()))
  22116. {
  22117. JSON_THROW(parse_error::create(104, 0, "JSON patch must be an array of objects", json_patch));
  22118. }
  22119. // iterate and apply the operations
  22120. for (const auto& val : json_patch)
  22121. {
  22122. // wrapper to get a value for an operation
  22123. const auto get_value = [&val](const std::string & op,
  22124. const std::string & member,
  22125. bool string_type) -> basic_json &
  22126. {
  22127. // find value
  22128. auto it = val.m_value.object->find(member);
  22129. // context-sensitive error message
  22130. const auto error_msg = (op == "op") ? "operation" : "operation '" + op + "'";
  22131. // check if desired value is present
  22132. if (JSON_HEDLEY_UNLIKELY(it == val.m_value.object->end()))
  22133. {
  22134. // NOLINTNEXTLINE(performance-inefficient-string-concatenation)
  22135. JSON_THROW(parse_error::create(105, 0, error_msg + " must have member '" + member + "'", val));
  22136. }
  22137. // check if result is of type string
  22138. if (JSON_HEDLEY_UNLIKELY(string_type && !it->second.is_string()))
  22139. {
  22140. // NOLINTNEXTLINE(performance-inefficient-string-concatenation)
  22141. JSON_THROW(parse_error::create(105, 0, error_msg + " must have string member '" + member + "'", val));
  22142. }
  22143. // no error: return value
  22144. return it->second;
  22145. };
  22146. // type check: every element of the array must be an object
  22147. if (JSON_HEDLEY_UNLIKELY(!val.is_object()))
  22148. {
  22149. JSON_THROW(parse_error::create(104, 0, "JSON patch must be an array of objects", val));
  22150. }
  22151. // collect mandatory members
  22152. const auto op = get_value("op", "op", true).template get<std::string>();
  22153. const auto path = get_value(op, "path", true).template get<std::string>();
  22154. json_pointer ptr(path);
  22155. switch (get_op(op))
  22156. {
  22157. case patch_operations::add:
  22158. {
  22159. operation_add(ptr, get_value("add", "value", false));
  22160. break;
  22161. }
  22162. case patch_operations::remove:
  22163. {
  22164. operation_remove(ptr);
  22165. break;
  22166. }
  22167. case patch_operations::replace:
  22168. {
  22169. // the "path" location must exist - use at()
  22170. result.at(ptr) = get_value("replace", "value", false);
  22171. break;
  22172. }
  22173. case patch_operations::move:
  22174. {
  22175. const auto from_path = get_value("move", "from", true).template get<std::string>();
  22176. json_pointer from_ptr(from_path);
  22177. // the "from" location must exist - use at()
  22178. basic_json v = result.at(from_ptr);
  22179. // The move operation is functionally identical to a
  22180. // "remove" operation on the "from" location, followed
  22181. // immediately by an "add" operation at the target
  22182. // location with the value that was just removed.
  22183. operation_remove(from_ptr);
  22184. operation_add(ptr, v);
  22185. break;
  22186. }
  22187. case patch_operations::copy:
  22188. {
  22189. const auto from_path = get_value("copy", "from", true).template get<std::string>();
  22190. const json_pointer from_ptr(from_path);
  22191. // the "from" location must exist - use at()
  22192. basic_json v = result.at(from_ptr);
  22193. // The copy is functionally identical to an "add"
  22194. // operation at the target location using the value
  22195. // specified in the "from" member.
  22196. operation_add(ptr, v);
  22197. break;
  22198. }
  22199. case patch_operations::test:
  22200. {
  22201. bool success = false;
  22202. JSON_TRY
  22203. {
  22204. // check if "value" matches the one at "path"
  22205. // the "path" location must exist - use at()
  22206. success = (result.at(ptr) == get_value("test", "value", false));
  22207. }
  22208. JSON_INTERNAL_CATCH (out_of_range&)
  22209. {
  22210. // ignore out of range errors: success remains false
  22211. }
  22212. // throw an exception if test fails
  22213. if (JSON_HEDLEY_UNLIKELY(!success))
  22214. {
  22215. JSON_THROW(other_error::create(501, "unsuccessful: " + val.dump(), val));
  22216. }
  22217. break;
  22218. }
  22219. case patch_operations::invalid:
  22220. default:
  22221. {
  22222. // op must be "add", "remove", "replace", "move", "copy", or
  22223. // "test"
  22224. JSON_THROW(parse_error::create(105, 0, "operation value '" + op + "' is invalid", val));
  22225. }
  22226. }
  22227. }
  22228. return result;
  22229. }
  22230. /*!
  22231. @brief creates a diff as a JSON patch
  22232. Creates a [JSON Patch](http://jsonpatch.com) so that value @a source can
  22233. be changed into the value @a target by calling @ref patch function.
  22234. @invariant For two JSON values @a source and @a target, the following code
  22235. yields always `true`:
  22236. @code {.cpp}
  22237. source.patch(diff(source, target)) == target;
  22238. @endcode
  22239. @note Currently, only `remove`, `add`, and `replace` operations are
  22240. generated.
  22241. @param[in] source JSON value to compare from
  22242. @param[in] target JSON value to compare against
  22243. @param[in] path helper value to create JSON pointers
  22244. @return a JSON patch to convert the @a source to @a target
  22245. @complexity Linear in the lengths of @a source and @a target.
  22246. @liveexample{The following code shows how a JSON patch is created as a
  22247. diff for two JSON values.,diff}
  22248. @sa see @ref patch -- apply a JSON patch
  22249. @sa see @ref merge_patch -- apply a JSON Merge Patch
  22250. @sa [RFC 6902 (JSON Patch)](https://tools.ietf.org/html/rfc6902)
  22251. @since version 2.0.0
  22252. */
  22253. JSON_HEDLEY_WARN_UNUSED_RESULT
  22254. static basic_json diff(const basic_json& source, const basic_json& target,
  22255. const std::string& path = "")
  22256. {
  22257. // the patch
  22258. basic_json result(value_t::array);
  22259. // if the values are the same, return empty patch
  22260. if (source == target)
  22261. {
  22262. return result;
  22263. }
  22264. if (source.type() != target.type())
  22265. {
  22266. // different types: replace value
  22267. result.push_back(
  22268. {
  22269. {"op", "replace"}, {"path", path}, {"value", target}
  22270. });
  22271. return result;
  22272. }
  22273. switch (source.type())
  22274. {
  22275. case value_t::array:
  22276. {
  22277. // first pass: traverse common elements
  22278. std::size_t i = 0;
  22279. while (i < source.size() && i < target.size())
  22280. {
  22281. // recursive call to compare array values at index i
  22282. auto temp_diff = diff(source[i], target[i], path + "/" + std::to_string(i));
  22283. result.insert(result.end(), temp_diff.begin(), temp_diff.end());
  22284. ++i;
  22285. }
  22286. // i now reached the end of at least one array
  22287. // in a second pass, traverse the remaining elements
  22288. // remove my remaining elements
  22289. const auto end_index = static_cast<difference_type>(result.size());
  22290. while (i < source.size())
  22291. {
  22292. // add operations in reverse order to avoid invalid
  22293. // indices
  22294. result.insert(result.begin() + end_index, object(
  22295. {
  22296. {"op", "remove"},
  22297. {"path", path + "/" + std::to_string(i)}
  22298. }));
  22299. ++i;
  22300. }
  22301. // add other remaining elements
  22302. while (i < target.size())
  22303. {
  22304. result.push_back(
  22305. {
  22306. {"op", "add"},
  22307. {"path", path + "/-"},
  22308. {"value", target[i]}
  22309. });
  22310. ++i;
  22311. }
  22312. break;
  22313. }
  22314. case value_t::object:
  22315. {
  22316. // first pass: traverse this object's elements
  22317. for (auto it = source.cbegin(); it != source.cend(); ++it)
  22318. {
  22319. // escape the key name to be used in a JSON patch
  22320. const auto path_key = path + "/" + detail::escape(it.key());
  22321. if (target.find(it.key()) != target.end())
  22322. {
  22323. // recursive call to compare object values at key it
  22324. auto temp_diff = diff(it.value(), target[it.key()], path_key);
  22325. result.insert(result.end(), temp_diff.begin(), temp_diff.end());
  22326. }
  22327. else
  22328. {
  22329. // found a key that is not in o -> remove it
  22330. result.push_back(object(
  22331. {
  22332. {"op", "remove"}, {"path", path_key}
  22333. }));
  22334. }
  22335. }
  22336. // second pass: traverse other object's elements
  22337. for (auto it = target.cbegin(); it != target.cend(); ++it)
  22338. {
  22339. if (source.find(it.key()) == source.end())
  22340. {
  22341. // found a key that is not in this -> add it
  22342. const auto path_key = path + "/" + detail::escape(it.key());
  22343. result.push_back(
  22344. {
  22345. {"op", "add"}, {"path", path_key},
  22346. {"value", it.value()}
  22347. });
  22348. }
  22349. }
  22350. break;
  22351. }
  22352. case value_t::null:
  22353. case value_t::string:
  22354. case value_t::boolean:
  22355. case value_t::number_integer:
  22356. case value_t::number_unsigned:
  22357. case value_t::number_float:
  22358. case value_t::binary:
  22359. case value_t::discarded:
  22360. default:
  22361. {
  22362. // both primitive type: replace value
  22363. result.push_back(
  22364. {
  22365. {"op", "replace"}, {"path", path}, {"value", target}
  22366. });
  22367. break;
  22368. }
  22369. }
  22370. return result;
  22371. }
  22372. /// @}
  22373. ////////////////////////////////
  22374. // JSON Merge Patch functions //
  22375. ////////////////////////////////
  22376. /// @name JSON Merge Patch functions
  22377. /// @{
  22378. /*!
  22379. @brief applies a JSON Merge Patch
  22380. The merge patch format is primarily intended for use with the HTTP PATCH
  22381. method as a means of describing a set of modifications to a target
  22382. resource's content. This function applies a merge patch to the current
  22383. JSON value.
  22384. The function implements the following algorithm from Section 2 of
  22385. [RFC 7396 (JSON Merge Patch)](https://tools.ietf.org/html/rfc7396):
  22386. ```
  22387. define MergePatch(Target, Patch):
  22388. if Patch is an Object:
  22389. if Target is not an Object:
  22390. Target = {} // Ignore the contents and set it to an empty Object
  22391. for each Name/Value pair in Patch:
  22392. if Value is null:
  22393. if Name exists in Target:
  22394. remove the Name/Value pair from Target
  22395. else:
  22396. Target[Name] = MergePatch(Target[Name], Value)
  22397. return Target
  22398. else:
  22399. return Patch
  22400. ```
  22401. Thereby, `Target` is the current object; that is, the patch is applied to
  22402. the current value.
  22403. @param[in] apply_patch the patch to apply
  22404. @complexity Linear in the lengths of @a patch.
  22405. @liveexample{The following code shows how a JSON Merge Patch is applied to
  22406. a JSON document.,merge_patch}
  22407. @sa see @ref patch -- apply a JSON patch
  22408. @sa [RFC 7396 (JSON Merge Patch)](https://tools.ietf.org/html/rfc7396)
  22409. @since version 3.0.0
  22410. */
  22411. void merge_patch(const basic_json& apply_patch)
  22412. {
  22413. if (apply_patch.is_object())
  22414. {
  22415. if (!is_object())
  22416. {
  22417. *this = object();
  22418. }
  22419. for (auto it = apply_patch.begin(); it != apply_patch.end(); ++it)
  22420. {
  22421. if (it.value().is_null())
  22422. {
  22423. erase(it.key());
  22424. }
  22425. else
  22426. {
  22427. operator[](it.key()).merge_patch(it.value());
  22428. }
  22429. }
  22430. }
  22431. else
  22432. {
  22433. *this = apply_patch;
  22434. }
  22435. }
  22436. /// @}
  22437. };
  22438. /*!
  22439. @brief user-defined to_string function for JSON values
  22440. This function implements a user-defined to_string for JSON objects.
  22441. @param[in] j a JSON object
  22442. @return a std::string object
  22443. */
  22444. NLOHMANN_BASIC_JSON_TPL_DECLARATION
  22445. std::string to_string(const NLOHMANN_BASIC_JSON_TPL& j)
  22446. {
  22447. return j.dump();
  22448. }
  22449. } // namespace nlohmann
  22450. ///////////////////////
  22451. // nonmember support //
  22452. ///////////////////////
  22453. // specialization of std::swap, and std::hash
  22454. namespace std
  22455. {
  22456. /// hash value for JSON objects
  22457. template<>
  22458. struct hash<nlohmann::json>
  22459. {
  22460. /*!
  22461. @brief return a hash value for a JSON object
  22462. @since version 1.0.0
  22463. */
  22464. std::size_t operator()(const nlohmann::json& j) const
  22465. {
  22466. return nlohmann::detail::hash(j);
  22467. }
  22468. };
  22469. /// specialization for std::less<value_t>
  22470. /// @note: do not remove the space after '<',
  22471. /// see https://github.com/nlohmann/json/pull/679
  22472. template<>
  22473. struct less<::nlohmann::detail::value_t>
  22474. {
  22475. /*!
  22476. @brief compare two value_t enum values
  22477. @since version 3.0.0
  22478. */
  22479. bool operator()(nlohmann::detail::value_t lhs,
  22480. nlohmann::detail::value_t rhs) const noexcept
  22481. {
  22482. return nlohmann::detail::operator<(lhs, rhs);
  22483. }
  22484. };
  22485. // C++20 prohibit function specialization in the std namespace.
  22486. #ifndef JSON_HAS_CPP_20
  22487. /*!
  22488. @brief exchanges the values of two JSON objects
  22489. @since version 1.0.0
  22490. */
  22491. template<>
  22492. inline void swap<nlohmann::json>(nlohmann::json& j1, nlohmann::json& j2) noexcept( // NOLINT(readability-inconsistent-declaration-parameter-name)
  22493. is_nothrow_move_constructible<nlohmann::json>::value&& // NOLINT(misc-redundant-expression)
  22494. is_nothrow_move_assignable<nlohmann::json>::value
  22495. )
  22496. {
  22497. j1.swap(j2);
  22498. }
  22499. #endif
  22500. } // namespace std
  22501. /*!
  22502. @brief user-defined string literal for JSON values
  22503. This operator implements a user-defined string literal for JSON objects. It
  22504. can be used by adding `"_json"` to a string literal and returns a JSON object
  22505. if no parse error occurred.
  22506. @param[in] s a string representation of a JSON object
  22507. @param[in] n the length of string @a s
  22508. @return a JSON object
  22509. @since version 1.0.0
  22510. */
  22511. JSON_HEDLEY_NON_NULL(1)
  22512. inline nlohmann::json operator "" _json(const char* s, std::size_t n)
  22513. {
  22514. return nlohmann::json::parse(s, s + n);
  22515. }
  22516. /*!
  22517. @brief user-defined string literal for JSON pointer
  22518. This operator implements a user-defined string literal for JSON Pointers. It
  22519. can be used by adding `"_json_pointer"` to a string literal and returns a JSON pointer
  22520. object if no parse error occurred.
  22521. @param[in] s a string representation of a JSON Pointer
  22522. @param[in] n the length of string @a s
  22523. @return a JSON pointer object
  22524. @since version 2.0.0
  22525. */
  22526. JSON_HEDLEY_NON_NULL(1)
  22527. inline nlohmann::json::json_pointer operator "" _json_pointer(const char* s, std::size_t n)
  22528. {
  22529. return nlohmann::json::json_pointer(std::string(s, n));
  22530. }
  22531. // #include <nlohmann/detail/macro_unscope.hpp>
  22532. // restore clang diagnostic settings
  22533. #if defined(__clang__)
  22534. #pragma clang diagnostic pop
  22535. #endif
  22536. // clean up
  22537. #undef JSON_ASSERT
  22538. #undef JSON_INTERNAL_CATCH
  22539. #undef JSON_CATCH
  22540. #undef JSON_THROW
  22541. #undef JSON_TRY
  22542. #undef JSON_PRIVATE_UNLESS_TESTED
  22543. #undef JSON_HAS_CPP_11
  22544. #undef JSON_HAS_CPP_14
  22545. #undef JSON_HAS_CPP_17
  22546. #undef JSON_HAS_CPP_20
  22547. #undef NLOHMANN_BASIC_JSON_TPL_DECLARATION
  22548. #undef NLOHMANN_BASIC_JSON_TPL
  22549. #undef JSON_EXPLICIT
  22550. #undef NLOHMANN_CAN_CALL_STD_FUNC_IMPL
  22551. // #include <nlohmann/thirdparty/hedley/hedley_undef.hpp>
  22552. #undef JSON_HEDLEY_ALWAYS_INLINE
  22553. #undef JSON_HEDLEY_ARM_VERSION
  22554. #undef JSON_HEDLEY_ARM_VERSION_CHECK
  22555. #undef JSON_HEDLEY_ARRAY_PARAM
  22556. #undef JSON_HEDLEY_ASSUME
  22557. #undef JSON_HEDLEY_BEGIN_C_DECLS
  22558. #undef JSON_HEDLEY_CLANG_HAS_ATTRIBUTE
  22559. #undef JSON_HEDLEY_CLANG_HAS_BUILTIN
  22560. #undef JSON_HEDLEY_CLANG_HAS_CPP_ATTRIBUTE
  22561. #undef JSON_HEDLEY_CLANG_HAS_DECLSPEC_DECLSPEC_ATTRIBUTE
  22562. #undef JSON_HEDLEY_CLANG_HAS_EXTENSION
  22563. #undef JSON_HEDLEY_CLANG_HAS_FEATURE
  22564. #undef JSON_HEDLEY_CLANG_HAS_WARNING
  22565. #undef JSON_HEDLEY_COMPCERT_VERSION
  22566. #undef JSON_HEDLEY_COMPCERT_VERSION_CHECK
  22567. #undef JSON_HEDLEY_CONCAT
  22568. #undef JSON_HEDLEY_CONCAT3
  22569. #undef JSON_HEDLEY_CONCAT3_EX
  22570. #undef JSON_HEDLEY_CONCAT_EX
  22571. #undef JSON_HEDLEY_CONST
  22572. #undef JSON_HEDLEY_CONSTEXPR
  22573. #undef JSON_HEDLEY_CONST_CAST
  22574. #undef JSON_HEDLEY_CPP_CAST
  22575. #undef JSON_HEDLEY_CRAY_VERSION
  22576. #undef JSON_HEDLEY_CRAY_VERSION_CHECK
  22577. #undef JSON_HEDLEY_C_DECL
  22578. #undef JSON_HEDLEY_DEPRECATED
  22579. #undef JSON_HEDLEY_DEPRECATED_FOR
  22580. #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL
  22581. #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_
  22582. #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED
  22583. #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES
  22584. #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS
  22585. #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNUSED_FUNCTION
  22586. #undef JSON_HEDLEY_DIAGNOSTIC_POP
  22587. #undef JSON_HEDLEY_DIAGNOSTIC_PUSH
  22588. #undef JSON_HEDLEY_DMC_VERSION
  22589. #undef JSON_HEDLEY_DMC_VERSION_CHECK
  22590. #undef JSON_HEDLEY_EMPTY_BASES
  22591. #undef JSON_HEDLEY_EMSCRIPTEN_VERSION
  22592. #undef JSON_HEDLEY_EMSCRIPTEN_VERSION_CHECK
  22593. #undef JSON_HEDLEY_END_C_DECLS
  22594. #undef JSON_HEDLEY_FLAGS
  22595. #undef JSON_HEDLEY_FLAGS_CAST
  22596. #undef JSON_HEDLEY_GCC_HAS_ATTRIBUTE
  22597. #undef JSON_HEDLEY_GCC_HAS_BUILTIN
  22598. #undef JSON_HEDLEY_GCC_HAS_CPP_ATTRIBUTE
  22599. #undef JSON_HEDLEY_GCC_HAS_DECLSPEC_ATTRIBUTE
  22600. #undef JSON_HEDLEY_GCC_HAS_EXTENSION
  22601. #undef JSON_HEDLEY_GCC_HAS_FEATURE
  22602. #undef JSON_HEDLEY_GCC_HAS_WARNING
  22603. #undef JSON_HEDLEY_GCC_NOT_CLANG_VERSION_CHECK
  22604. #undef JSON_HEDLEY_GCC_VERSION
  22605. #undef JSON_HEDLEY_GCC_VERSION_CHECK
  22606. #undef JSON_HEDLEY_GNUC_HAS_ATTRIBUTE
  22607. #undef JSON_HEDLEY_GNUC_HAS_BUILTIN
  22608. #undef JSON_HEDLEY_GNUC_HAS_CPP_ATTRIBUTE
  22609. #undef JSON_HEDLEY_GNUC_HAS_DECLSPEC_ATTRIBUTE
  22610. #undef JSON_HEDLEY_GNUC_HAS_EXTENSION
  22611. #undef JSON_HEDLEY_GNUC_HAS_FEATURE
  22612. #undef JSON_HEDLEY_GNUC_HAS_WARNING
  22613. #undef JSON_HEDLEY_GNUC_VERSION
  22614. #undef JSON_HEDLEY_GNUC_VERSION_CHECK
  22615. #undef JSON_HEDLEY_HAS_ATTRIBUTE
  22616. #undef JSON_HEDLEY_HAS_BUILTIN
  22617. #undef JSON_HEDLEY_HAS_CPP_ATTRIBUTE
  22618. #undef JSON_HEDLEY_HAS_CPP_ATTRIBUTE_NS
  22619. #undef JSON_HEDLEY_HAS_DECLSPEC_ATTRIBUTE
  22620. #undef JSON_HEDLEY_HAS_EXTENSION
  22621. #undef JSON_HEDLEY_HAS_FEATURE
  22622. #undef JSON_HEDLEY_HAS_WARNING
  22623. #undef JSON_HEDLEY_IAR_VERSION
  22624. #undef JSON_HEDLEY_IAR_VERSION_CHECK
  22625. #undef JSON_HEDLEY_IBM_VERSION
  22626. #undef JSON_HEDLEY_IBM_VERSION_CHECK
  22627. #undef JSON_HEDLEY_IMPORT
  22628. #undef JSON_HEDLEY_INLINE
  22629. #undef JSON_HEDLEY_INTEL_CL_VERSION
  22630. #undef JSON_HEDLEY_INTEL_CL_VERSION_CHECK
  22631. #undef JSON_HEDLEY_INTEL_VERSION
  22632. #undef JSON_HEDLEY_INTEL_VERSION_CHECK
  22633. #undef JSON_HEDLEY_IS_CONSTANT
  22634. #undef JSON_HEDLEY_IS_CONSTEXPR_
  22635. #undef JSON_HEDLEY_LIKELY
  22636. #undef JSON_HEDLEY_MALLOC
  22637. #undef JSON_HEDLEY_MCST_LCC_VERSION
  22638. #undef JSON_HEDLEY_MCST_LCC_VERSION_CHECK
  22639. #undef JSON_HEDLEY_MESSAGE
  22640. #undef JSON_HEDLEY_MSVC_VERSION
  22641. #undef JSON_HEDLEY_MSVC_VERSION_CHECK
  22642. #undef JSON_HEDLEY_NEVER_INLINE
  22643. #undef JSON_HEDLEY_NON_NULL
  22644. #undef JSON_HEDLEY_NO_ESCAPE
  22645. #undef JSON_HEDLEY_NO_RETURN
  22646. #undef JSON_HEDLEY_NO_THROW
  22647. #undef JSON_HEDLEY_NULL
  22648. #undef JSON_HEDLEY_PELLES_VERSION
  22649. #undef JSON_HEDLEY_PELLES_VERSION_CHECK
  22650. #undef JSON_HEDLEY_PGI_VERSION
  22651. #undef JSON_HEDLEY_PGI_VERSION_CHECK
  22652. #undef JSON_HEDLEY_PREDICT
  22653. #undef JSON_HEDLEY_PRINTF_FORMAT
  22654. #undef JSON_HEDLEY_PRIVATE
  22655. #undef JSON_HEDLEY_PUBLIC
  22656. #undef JSON_HEDLEY_PURE
  22657. #undef JSON_HEDLEY_REINTERPRET_CAST
  22658. #undef JSON_HEDLEY_REQUIRE
  22659. #undef JSON_HEDLEY_REQUIRE_CONSTEXPR
  22660. #undef JSON_HEDLEY_REQUIRE_MSG
  22661. #undef JSON_HEDLEY_RESTRICT
  22662. #undef JSON_HEDLEY_RETURNS_NON_NULL
  22663. #undef JSON_HEDLEY_SENTINEL
  22664. #undef JSON_HEDLEY_STATIC_ASSERT
  22665. #undef JSON_HEDLEY_STATIC_CAST
  22666. #undef JSON_HEDLEY_STRINGIFY
  22667. #undef JSON_HEDLEY_STRINGIFY_EX
  22668. #undef JSON_HEDLEY_SUNPRO_VERSION
  22669. #undef JSON_HEDLEY_SUNPRO_VERSION_CHECK
  22670. #undef JSON_HEDLEY_TINYC_VERSION
  22671. #undef JSON_HEDLEY_TINYC_VERSION_CHECK
  22672. #undef JSON_HEDLEY_TI_ARMCL_VERSION
  22673. #undef JSON_HEDLEY_TI_ARMCL_VERSION_CHECK
  22674. #undef JSON_HEDLEY_TI_CL2000_VERSION
  22675. #undef JSON_HEDLEY_TI_CL2000_VERSION_CHECK
  22676. #undef JSON_HEDLEY_TI_CL430_VERSION
  22677. #undef JSON_HEDLEY_TI_CL430_VERSION_CHECK
  22678. #undef JSON_HEDLEY_TI_CL6X_VERSION
  22679. #undef JSON_HEDLEY_TI_CL6X_VERSION_CHECK
  22680. #undef JSON_HEDLEY_TI_CL7X_VERSION
  22681. #undef JSON_HEDLEY_TI_CL7X_VERSION_CHECK
  22682. #undef JSON_HEDLEY_TI_CLPRU_VERSION
  22683. #undef JSON_HEDLEY_TI_CLPRU_VERSION_CHECK
  22684. #undef JSON_HEDLEY_TI_VERSION
  22685. #undef JSON_HEDLEY_TI_VERSION_CHECK
  22686. #undef JSON_HEDLEY_UNAVAILABLE
  22687. #undef JSON_HEDLEY_UNLIKELY
  22688. #undef JSON_HEDLEY_UNPREDICTABLE
  22689. #undef JSON_HEDLEY_UNREACHABLE
  22690. #undef JSON_HEDLEY_UNREACHABLE_RETURN
  22691. #undef JSON_HEDLEY_VERSION
  22692. #undef JSON_HEDLEY_VERSION_DECODE_MAJOR
  22693. #undef JSON_HEDLEY_VERSION_DECODE_MINOR
  22694. #undef JSON_HEDLEY_VERSION_DECODE_REVISION
  22695. #undef JSON_HEDLEY_VERSION_ENCODE
  22696. #undef JSON_HEDLEY_WARNING
  22697. #undef JSON_HEDLEY_WARN_UNUSED_RESULT
  22698. #undef JSON_HEDLEY_WARN_UNUSED_RESULT_MSG
  22699. #undef JSON_HEDLEY_FALL_THROUGH
  22700. #endif // INCLUDE_NLOHMANN_JSON_HPP_