json.hpp 960 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757
  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. #include <boost/filesystem.hpp>
  3485. #endif
  3486. namespace nlohmann
  3487. {
  3488. namespace detail
  3489. {
  3490. template<typename BasicJsonType>
  3491. void from_json(const BasicJsonType& j, typename std::nullptr_t& n)
  3492. {
  3493. if (JSON_HEDLEY_UNLIKELY(!j.is_null()))
  3494. {
  3495. JSON_THROW(type_error::create(302, "type must be null, but is " + std::string(j.type_name()), j));
  3496. }
  3497. n = nullptr;
  3498. }
  3499. // overloads for basic_json template parameters
  3500. template < typename BasicJsonType, typename ArithmeticType,
  3501. enable_if_t < std::is_arithmetic<ArithmeticType>::value&&
  3502. !std::is_same<ArithmeticType, typename BasicJsonType::boolean_t>::value,
  3503. int > = 0 >
  3504. void get_arithmetic_value(const BasicJsonType& j, ArithmeticType& val)
  3505. {
  3506. switch (static_cast<value_t>(j))
  3507. {
  3508. case value_t::number_unsigned:
  3509. {
  3510. val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::number_unsigned_t*>());
  3511. break;
  3512. }
  3513. case value_t::number_integer:
  3514. {
  3515. val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::number_integer_t*>());
  3516. break;
  3517. }
  3518. case value_t::number_float:
  3519. {
  3520. val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::number_float_t*>());
  3521. break;
  3522. }
  3523. case value_t::null:
  3524. case value_t::object:
  3525. case value_t::array:
  3526. case value_t::string:
  3527. case value_t::boolean:
  3528. case value_t::binary:
  3529. case value_t::discarded:
  3530. default:
  3531. JSON_THROW(type_error::create(302, "type must be number, but is " + std::string(j.type_name()), j));
  3532. }
  3533. }
  3534. template<typename BasicJsonType>
  3535. void from_json(const BasicJsonType& j, typename BasicJsonType::boolean_t& b)
  3536. {
  3537. if (JSON_HEDLEY_UNLIKELY(!j.is_boolean()))
  3538. {
  3539. JSON_THROW(type_error::create(302, "type must be boolean, but is " + std::string(j.type_name()), j));
  3540. }
  3541. b = *j.template get_ptr<const typename BasicJsonType::boolean_t*>();
  3542. }
  3543. template<typename BasicJsonType>
  3544. void from_json(const BasicJsonType& j, typename BasicJsonType::string_t& s)
  3545. {
  3546. if (JSON_HEDLEY_UNLIKELY(!j.is_string()))
  3547. {
  3548. JSON_THROW(type_error::create(302, "type must be string, but is " + std::string(j.type_name()), j));
  3549. }
  3550. s = *j.template get_ptr<const typename BasicJsonType::string_t*>();
  3551. }
  3552. template <
  3553. typename BasicJsonType, typename ConstructibleStringType,
  3554. enable_if_t <
  3555. is_constructible_string_type<BasicJsonType, ConstructibleStringType>::value&&
  3556. !std::is_same<typename BasicJsonType::string_t,
  3557. ConstructibleStringType>::value,
  3558. int > = 0 >
  3559. void from_json(const BasicJsonType& j, ConstructibleStringType& s)
  3560. {
  3561. if (JSON_HEDLEY_UNLIKELY(!j.is_string()))
  3562. {
  3563. JSON_THROW(type_error::create(302, "type must be string, but is " + std::string(j.type_name()), j));
  3564. }
  3565. s = *j.template get_ptr<const typename BasicJsonType::string_t*>();
  3566. }
  3567. template<typename BasicJsonType>
  3568. void from_json(const BasicJsonType& j, typename BasicJsonType::number_float_t& val)
  3569. {
  3570. get_arithmetic_value(j, val);
  3571. }
  3572. template<typename BasicJsonType>
  3573. void from_json(const BasicJsonType& j, typename BasicJsonType::number_unsigned_t& val)
  3574. {
  3575. get_arithmetic_value(j, val);
  3576. }
  3577. template<typename BasicJsonType>
  3578. void from_json(const BasicJsonType& j, typename BasicJsonType::number_integer_t& val)
  3579. {
  3580. get_arithmetic_value(j, val);
  3581. }
  3582. template<typename BasicJsonType, typename EnumType,
  3583. enable_if_t<std::is_enum<EnumType>::value, int> = 0>
  3584. void from_json(const BasicJsonType& j, EnumType& e)
  3585. {
  3586. typename std::underlying_type<EnumType>::type val;
  3587. get_arithmetic_value(j, val);
  3588. e = static_cast<EnumType>(val);
  3589. }
  3590. // forward_list doesn't have an insert method
  3591. template<typename BasicJsonType, typename T, typename Allocator,
  3592. enable_if_t<is_getable<BasicJsonType, T>::value, int> = 0>
  3593. void from_json(const BasicJsonType& j, std::forward_list<T, Allocator>& l)
  3594. {
  3595. if (JSON_HEDLEY_UNLIKELY(!j.is_array()))
  3596. {
  3597. JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(j.type_name()), j));
  3598. }
  3599. l.clear();
  3600. std::transform(j.rbegin(), j.rend(),
  3601. std::front_inserter(l), [](const BasicJsonType & i)
  3602. {
  3603. return i.template get<T>();
  3604. });
  3605. }
  3606. // valarray doesn't have an insert method
  3607. template<typename BasicJsonType, typename T,
  3608. enable_if_t<is_getable<BasicJsonType, T>::value, int> = 0>
  3609. void from_json(const BasicJsonType& j, std::valarray<T>& l)
  3610. {
  3611. if (JSON_HEDLEY_UNLIKELY(!j.is_array()))
  3612. {
  3613. JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(j.type_name()), j));
  3614. }
  3615. l.resize(j.size());
  3616. std::transform(j.begin(), j.end(), std::begin(l),
  3617. [](const BasicJsonType & elem)
  3618. {
  3619. return elem.template get<T>();
  3620. });
  3621. }
  3622. template<typename BasicJsonType, typename T, std::size_t N>
  3623. auto from_json(const BasicJsonType& j, T (&arr)[N]) // NOLINT(cppcoreguidelines-avoid-c-arrays,hicpp-avoid-c-arrays,modernize-avoid-c-arrays)
  3624. -> decltype(j.template get<T>(), void())
  3625. {
  3626. for (std::size_t i = 0; i < N; ++i)
  3627. {
  3628. arr[i] = j.at(i).template get<T>();
  3629. }
  3630. }
  3631. template<typename BasicJsonType>
  3632. void from_json_array_impl(const BasicJsonType& j, typename BasicJsonType::array_t& arr, priority_tag<3> /*unused*/)
  3633. {
  3634. arr = *j.template get_ptr<const typename BasicJsonType::array_t*>();
  3635. }
  3636. template<typename BasicJsonType, typename T, std::size_t N>
  3637. auto from_json_array_impl(const BasicJsonType& j, std::array<T, N>& arr,
  3638. priority_tag<2> /*unused*/)
  3639. -> decltype(j.template get<T>(), void())
  3640. {
  3641. for (std::size_t i = 0; i < N; ++i)
  3642. {
  3643. arr[i] = j.at(i).template get<T>();
  3644. }
  3645. }
  3646. template<typename BasicJsonType, typename ConstructibleArrayType,
  3647. enable_if_t<
  3648. std::is_assignable<ConstructibleArrayType&, ConstructibleArrayType>::value,
  3649. int> = 0>
  3650. auto from_json_array_impl(const BasicJsonType& j, ConstructibleArrayType& arr, priority_tag<1> /*unused*/)
  3651. -> decltype(
  3652. arr.reserve(std::declval<typename ConstructibleArrayType::size_type>()),
  3653. j.template get<typename ConstructibleArrayType::value_type>(),
  3654. void())
  3655. {
  3656. using std::end;
  3657. ConstructibleArrayType ret;
  3658. ret.reserve(j.size());
  3659. std::transform(j.begin(), j.end(),
  3660. std::inserter(ret, end(ret)), [](const BasicJsonType & i)
  3661. {
  3662. // get<BasicJsonType>() returns *this, this won't call a from_json
  3663. // method when value_type is BasicJsonType
  3664. return i.template get<typename ConstructibleArrayType::value_type>();
  3665. });
  3666. arr = std::move(ret);
  3667. }
  3668. template<typename BasicJsonType, typename ConstructibleArrayType,
  3669. enable_if_t<
  3670. std::is_assignable<ConstructibleArrayType&, ConstructibleArrayType>::value,
  3671. int> = 0>
  3672. void from_json_array_impl(const BasicJsonType& j, ConstructibleArrayType& arr,
  3673. priority_tag<0> /*unused*/)
  3674. {
  3675. using std::end;
  3676. ConstructibleArrayType ret;
  3677. std::transform(
  3678. j.begin(), j.end(), std::inserter(ret, end(ret)),
  3679. [](const BasicJsonType & i)
  3680. {
  3681. // get<BasicJsonType>() returns *this, this won't call a from_json
  3682. // method when value_type is BasicJsonType
  3683. return i.template get<typename ConstructibleArrayType::value_type>();
  3684. });
  3685. arr = std::move(ret);
  3686. }
  3687. template < typename BasicJsonType, typename ConstructibleArrayType,
  3688. enable_if_t <
  3689. is_constructible_array_type<BasicJsonType, ConstructibleArrayType>::value&&
  3690. !is_constructible_object_type<BasicJsonType, ConstructibleArrayType>::value&&
  3691. !is_constructible_string_type<BasicJsonType, ConstructibleArrayType>::value&&
  3692. !std::is_same<ConstructibleArrayType, typename BasicJsonType::binary_t>::value&&
  3693. !is_basic_json<ConstructibleArrayType>::value,
  3694. int > = 0 >
  3695. auto from_json(const BasicJsonType& j, ConstructibleArrayType& arr)
  3696. -> decltype(from_json_array_impl(j, arr, priority_tag<3> {}),
  3697. j.template get<typename ConstructibleArrayType::value_type>(),
  3698. void())
  3699. {
  3700. if (JSON_HEDLEY_UNLIKELY(!j.is_array()))
  3701. {
  3702. JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(j.type_name()), j));
  3703. }
  3704. from_json_array_impl(j, arr, priority_tag<3> {});
  3705. }
  3706. template < typename BasicJsonType, typename T, std::size_t... Idx >
  3707. std::array<T, sizeof...(Idx)> from_json_inplace_array_impl(BasicJsonType&& j,
  3708. identity_tag<std::array<T, sizeof...(Idx)>> /*unused*/, index_sequence<Idx...> /*unused*/)
  3709. {
  3710. return { { std::forward<BasicJsonType>(j).at(Idx).template get<T>()... } };
  3711. }
  3712. template < typename BasicJsonType, typename T, std::size_t N >
  3713. auto from_json(BasicJsonType&& j, identity_tag<std::array<T, N>> tag)
  3714. -> decltype(from_json_inplace_array_impl(std::forward<BasicJsonType>(j), tag, make_index_sequence<N> {}))
  3715. {
  3716. if (JSON_HEDLEY_UNLIKELY(!j.is_array()))
  3717. {
  3718. JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(j.type_name()), j));
  3719. }
  3720. return from_json_inplace_array_impl(std::forward<BasicJsonType>(j), tag, make_index_sequence<N> {});
  3721. }
  3722. template<typename BasicJsonType>
  3723. void from_json(const BasicJsonType& j, typename BasicJsonType::binary_t& bin)
  3724. {
  3725. if (JSON_HEDLEY_UNLIKELY(!j.is_binary()))
  3726. {
  3727. JSON_THROW(type_error::create(302, "type must be binary, but is " + std::string(j.type_name()), j));
  3728. }
  3729. bin = *j.template get_ptr<const typename BasicJsonType::binary_t*>();
  3730. }
  3731. template<typename BasicJsonType, typename ConstructibleObjectType,
  3732. enable_if_t<is_constructible_object_type<BasicJsonType, ConstructibleObjectType>::value, int> = 0>
  3733. void from_json(const BasicJsonType& j, ConstructibleObjectType& obj)
  3734. {
  3735. if (JSON_HEDLEY_UNLIKELY(!j.is_object()))
  3736. {
  3737. JSON_THROW(type_error::create(302, "type must be object, but is " + std::string(j.type_name()), j));
  3738. }
  3739. ConstructibleObjectType ret;
  3740. const auto* inner_object = j.template get_ptr<const typename BasicJsonType::object_t*>();
  3741. using value_type = typename ConstructibleObjectType::value_type;
  3742. std::transform(
  3743. inner_object->begin(), inner_object->end(),
  3744. std::inserter(ret, ret.begin()),
  3745. [](typename BasicJsonType::object_t::value_type const & p)
  3746. {
  3747. return value_type(p.first, p.second.template get<typename ConstructibleObjectType::mapped_type>());
  3748. });
  3749. obj = std::move(ret);
  3750. }
  3751. // overload for arithmetic types, not chosen for basic_json template arguments
  3752. // (BooleanType, etc..); note: Is it really necessary to provide explicit
  3753. // overloads for boolean_t etc. in case of a custom BooleanType which is not
  3754. // an arithmetic type?
  3755. template < typename BasicJsonType, typename ArithmeticType,
  3756. enable_if_t <
  3757. std::is_arithmetic<ArithmeticType>::value&&
  3758. !std::is_same<ArithmeticType, typename BasicJsonType::number_unsigned_t>::value&&
  3759. !std::is_same<ArithmeticType, typename BasicJsonType::number_integer_t>::value&&
  3760. !std::is_same<ArithmeticType, typename BasicJsonType::number_float_t>::value&&
  3761. !std::is_same<ArithmeticType, typename BasicJsonType::boolean_t>::value,
  3762. int > = 0 >
  3763. void from_json(const BasicJsonType& j, ArithmeticType& val)
  3764. {
  3765. switch (static_cast<value_t>(j))
  3766. {
  3767. case value_t::number_unsigned:
  3768. {
  3769. val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::number_unsigned_t*>());
  3770. break;
  3771. }
  3772. case value_t::number_integer:
  3773. {
  3774. val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::number_integer_t*>());
  3775. break;
  3776. }
  3777. case value_t::number_float:
  3778. {
  3779. val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::number_float_t*>());
  3780. break;
  3781. }
  3782. case value_t::boolean:
  3783. {
  3784. val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::boolean_t*>());
  3785. break;
  3786. }
  3787. case value_t::null:
  3788. case value_t::object:
  3789. case value_t::array:
  3790. case value_t::string:
  3791. case value_t::binary:
  3792. case value_t::discarded:
  3793. default:
  3794. JSON_THROW(type_error::create(302, "type must be number, but is " + std::string(j.type_name()), j));
  3795. }
  3796. }
  3797. template<typename BasicJsonType, typename... Args, std::size_t... Idx>
  3798. std::tuple<Args...> from_json_tuple_impl_base(BasicJsonType&& j, index_sequence<Idx...> /*unused*/)
  3799. {
  3800. return std::make_tuple(std::forward<BasicJsonType>(j).at(Idx).template get<Args>()...);
  3801. }
  3802. template < typename BasicJsonType, class A1, class A2 >
  3803. std::pair<A1, A2> from_json_tuple_impl(BasicJsonType&& j, identity_tag<std::pair<A1, A2>> /*unused*/, priority_tag<0> /*unused*/)
  3804. {
  3805. return {std::forward<BasicJsonType>(j).at(0).template get<A1>(),
  3806. std::forward<BasicJsonType>(j).at(1).template get<A2>()};
  3807. }
  3808. template<typename BasicJsonType, typename A1, typename A2>
  3809. void from_json_tuple_impl(BasicJsonType&& j, std::pair<A1, A2>& p, priority_tag<1> /*unused*/)
  3810. {
  3811. p = from_json_tuple_impl(std::forward<BasicJsonType>(j), identity_tag<std::pair<A1, A2>> {}, priority_tag<0> {});
  3812. }
  3813. template<typename BasicJsonType, typename... Args>
  3814. std::tuple<Args...> from_json_tuple_impl(BasicJsonType&& j, identity_tag<std::tuple<Args...>> /*unused*/, priority_tag<2> /*unused*/)
  3815. {
  3816. return from_json_tuple_impl_base<BasicJsonType, Args...>(std::forward<BasicJsonType>(j), index_sequence_for<Args...> {});
  3817. }
  3818. template<typename BasicJsonType, typename... Args>
  3819. void from_json_tuple_impl(BasicJsonType&& j, std::tuple<Args...>& t, priority_tag<3> /*unused*/)
  3820. {
  3821. t = from_json_tuple_impl_base<BasicJsonType, Args...>(std::forward<BasicJsonType>(j), index_sequence_for<Args...> {});
  3822. }
  3823. template<typename BasicJsonType, typename TupleRelated>
  3824. auto from_json(BasicJsonType&& j, TupleRelated&& t)
  3825. -> decltype(from_json_tuple_impl(std::forward<BasicJsonType>(j), std::forward<TupleRelated>(t), priority_tag<3> {}))
  3826. {
  3827. if (JSON_HEDLEY_UNLIKELY(!j.is_array()))
  3828. {
  3829. JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(j.type_name()), j));
  3830. }
  3831. return from_json_tuple_impl(std::forward<BasicJsonType>(j), std::forward<TupleRelated>(t), priority_tag<3> {});
  3832. }
  3833. template < typename BasicJsonType, typename Key, typename Value, typename Compare, typename Allocator,
  3834. typename = enable_if_t < !std::is_constructible <
  3835. typename BasicJsonType::string_t, Key >::value >>
  3836. void from_json(const BasicJsonType& j, std::map<Key, Value, Compare, Allocator>& m)
  3837. {
  3838. if (JSON_HEDLEY_UNLIKELY(!j.is_array()))
  3839. {
  3840. JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(j.type_name()), j));
  3841. }
  3842. m.clear();
  3843. for (const auto& p : j)
  3844. {
  3845. if (JSON_HEDLEY_UNLIKELY(!p.is_array()))
  3846. {
  3847. JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(p.type_name()), j));
  3848. }
  3849. m.emplace(p.at(0).template get<Key>(), p.at(1).template get<Value>());
  3850. }
  3851. }
  3852. template < typename BasicJsonType, typename Key, typename Value, typename Hash, typename KeyEqual, typename Allocator,
  3853. typename = enable_if_t < !std::is_constructible <
  3854. typename BasicJsonType::string_t, Key >::value >>
  3855. void from_json(const BasicJsonType& j, std::unordered_map<Key, Value, Hash, KeyEqual, Allocator>& m)
  3856. {
  3857. if (JSON_HEDLEY_UNLIKELY(!j.is_array()))
  3858. {
  3859. JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(j.type_name()), j));
  3860. }
  3861. m.clear();
  3862. for (const auto& p : j)
  3863. {
  3864. if (JSON_HEDLEY_UNLIKELY(!p.is_array()))
  3865. {
  3866. JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(p.type_name()), j));
  3867. }
  3868. m.emplace(p.at(0).template get<Key>(), p.at(1).template get<Value>());
  3869. }
  3870. }
  3871. #ifdef JSON_HAS_CPP_17
  3872. template<typename BasicJsonType>
  3873. // void from_json(const BasicJsonType& j, std::filesystem::path& p)
  3874. void from_json(const BasicJsonType& j, boost::filesystem::path& p)
  3875. {
  3876. if (JSON_HEDLEY_UNLIKELY(!j.is_string()))
  3877. {
  3878. JSON_THROW(type_error::create(302, "type must be string, but is " + std::string(j.type_name()), j));
  3879. }
  3880. p = *j.template get_ptr<const typename BasicJsonType::string_t*>();
  3881. }
  3882. #endif
  3883. struct from_json_fn
  3884. {
  3885. template<typename BasicJsonType, typename T>
  3886. auto operator()(const BasicJsonType& j, T&& val) const
  3887. noexcept(noexcept(from_json(j, std::forward<T>(val))))
  3888. -> decltype(from_json(j, std::forward<T>(val)))
  3889. {
  3890. return from_json(j, std::forward<T>(val));
  3891. }
  3892. };
  3893. } // namespace detail
  3894. /// namespace to hold default `from_json` function
  3895. /// to see why this is required:
  3896. /// http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2015/n4381.html
  3897. namespace // NOLINT(cert-dcl59-cpp,fuchsia-header-anon-namespaces,google-build-namespaces)
  3898. {
  3899. constexpr const auto& from_json = detail::static_const<detail::from_json_fn>::value; // NOLINT(misc-definitions-in-headers)
  3900. } // namespace
  3901. } // namespace nlohmann
  3902. // #include <nlohmann/detail/conversions/to_json.hpp>
  3903. #include <algorithm> // copy
  3904. #include <iterator> // begin, end
  3905. #include <string> // string
  3906. #include <tuple> // tuple, get
  3907. #include <type_traits> // is_same, is_constructible, is_floating_point, is_enum, underlying_type
  3908. #include <utility> // move, forward, declval, pair
  3909. #include <valarray> // valarray
  3910. #include <vector> // vector
  3911. // #include <nlohmann/detail/macro_scope.hpp>
  3912. // #include <nlohmann/detail/iterators/iteration_proxy.hpp>
  3913. #include <cstddef> // size_t
  3914. #include <iterator> // input_iterator_tag
  3915. #include <string> // string, to_string
  3916. #include <tuple> // tuple_size, get, tuple_element
  3917. #include <utility> // move
  3918. // #include <nlohmann/detail/meta/type_traits.hpp>
  3919. // #include <nlohmann/detail/value_t.hpp>
  3920. namespace nlohmann
  3921. {
  3922. namespace detail
  3923. {
  3924. template<typename string_type>
  3925. void int_to_string( string_type& target, std::size_t value )
  3926. {
  3927. // For ADL
  3928. using std::to_string;
  3929. target = to_string(value);
  3930. }
  3931. template<typename IteratorType> class iteration_proxy_value
  3932. {
  3933. public:
  3934. using difference_type = std::ptrdiff_t;
  3935. using value_type = iteration_proxy_value;
  3936. using pointer = value_type * ;
  3937. using reference = value_type & ;
  3938. using iterator_category = std::input_iterator_tag;
  3939. using string_type = typename std::remove_cv< typename std::remove_reference<decltype( std::declval<IteratorType>().key() ) >::type >::type;
  3940. private:
  3941. /// the iterator
  3942. IteratorType anchor;
  3943. /// an index for arrays (used to create key names)
  3944. std::size_t array_index = 0;
  3945. /// last stringified array index
  3946. mutable std::size_t array_index_last = 0;
  3947. /// a string representation of the array index
  3948. mutable string_type array_index_str = "0";
  3949. /// an empty string (to return a reference for primitive values)
  3950. const string_type empty_str{};
  3951. public:
  3952. explicit iteration_proxy_value(IteratorType it) noexcept
  3953. : anchor(std::move(it))
  3954. {}
  3955. /// dereference operator (needed for range-based for)
  3956. iteration_proxy_value& operator*()
  3957. {
  3958. return *this;
  3959. }
  3960. /// increment operator (needed for range-based for)
  3961. iteration_proxy_value& operator++()
  3962. {
  3963. ++anchor;
  3964. ++array_index;
  3965. return *this;
  3966. }
  3967. /// equality operator (needed for InputIterator)
  3968. bool operator==(const iteration_proxy_value& o) const
  3969. {
  3970. return anchor == o.anchor;
  3971. }
  3972. /// inequality operator (needed for range-based for)
  3973. bool operator!=(const iteration_proxy_value& o) const
  3974. {
  3975. return anchor != o.anchor;
  3976. }
  3977. /// return key of the iterator
  3978. const string_type& key() const
  3979. {
  3980. JSON_ASSERT(anchor.m_object != nullptr);
  3981. switch (anchor.m_object->type())
  3982. {
  3983. // use integer array index as key
  3984. case value_t::array:
  3985. {
  3986. if (array_index != array_index_last)
  3987. {
  3988. int_to_string( array_index_str, array_index );
  3989. array_index_last = array_index;
  3990. }
  3991. return array_index_str;
  3992. }
  3993. // use key from the object
  3994. case value_t::object:
  3995. return anchor.key();
  3996. // use an empty key for all primitive types
  3997. case value_t::null:
  3998. case value_t::string:
  3999. case value_t::boolean:
  4000. case value_t::number_integer:
  4001. case value_t::number_unsigned:
  4002. case value_t::number_float:
  4003. case value_t::binary:
  4004. case value_t::discarded:
  4005. default:
  4006. return empty_str;
  4007. }
  4008. }
  4009. /// return value of the iterator
  4010. typename IteratorType::reference value() const
  4011. {
  4012. return anchor.value();
  4013. }
  4014. };
  4015. /// proxy class for the items() function
  4016. template<typename IteratorType> class iteration_proxy
  4017. {
  4018. private:
  4019. /// the container to iterate
  4020. typename IteratorType::reference container;
  4021. public:
  4022. /// construct iteration proxy from a container
  4023. explicit iteration_proxy(typename IteratorType::reference cont) noexcept
  4024. : container(cont) {}
  4025. /// return iterator begin (needed for range-based for)
  4026. iteration_proxy_value<IteratorType> begin() noexcept
  4027. {
  4028. return iteration_proxy_value<IteratorType>(container.begin());
  4029. }
  4030. /// return iterator end (needed for range-based for)
  4031. iteration_proxy_value<IteratorType> end() noexcept
  4032. {
  4033. return iteration_proxy_value<IteratorType>(container.end());
  4034. }
  4035. };
  4036. // Structured Bindings Support
  4037. // For further reference see https://blog.tartanllama.xyz/structured-bindings/
  4038. // And see https://github.com/nlohmann/json/pull/1391
  4039. template<std::size_t N, typename IteratorType, enable_if_t<N == 0, int> = 0>
  4040. auto get(const nlohmann::detail::iteration_proxy_value<IteratorType>& i) -> decltype(i.key())
  4041. {
  4042. return i.key();
  4043. }
  4044. // Structured Bindings Support
  4045. // For further reference see https://blog.tartanllama.xyz/structured-bindings/
  4046. // And see https://github.com/nlohmann/json/pull/1391
  4047. template<std::size_t N, typename IteratorType, enable_if_t<N == 1, int> = 0>
  4048. auto get(const nlohmann::detail::iteration_proxy_value<IteratorType>& i) -> decltype(i.value())
  4049. {
  4050. return i.value();
  4051. }
  4052. } // namespace detail
  4053. } // namespace nlohmann
  4054. // The Addition to the STD Namespace is required to add
  4055. // Structured Bindings Support to the iteration_proxy_value class
  4056. // For further reference see https://blog.tartanllama.xyz/structured-bindings/
  4057. // And see https://github.com/nlohmann/json/pull/1391
  4058. namespace std
  4059. {
  4060. #if defined(__clang__)
  4061. // Fix: https://github.com/nlohmann/json/issues/1401
  4062. #pragma clang diagnostic push
  4063. #pragma clang diagnostic ignored "-Wmismatched-tags"
  4064. #endif
  4065. template<typename IteratorType>
  4066. class tuple_size<::nlohmann::detail::iteration_proxy_value<IteratorType>>
  4067. : public std::integral_constant<std::size_t, 2> {};
  4068. template<std::size_t N, typename IteratorType>
  4069. class tuple_element<N, ::nlohmann::detail::iteration_proxy_value<IteratorType >>
  4070. {
  4071. public:
  4072. using type = decltype(
  4073. get<N>(std::declval <
  4074. ::nlohmann::detail::iteration_proxy_value<IteratorType >> ()));
  4075. };
  4076. #if defined(__clang__)
  4077. #pragma clang diagnostic pop
  4078. #endif
  4079. } // namespace std
  4080. // #include <nlohmann/detail/meta/cpp_future.hpp>
  4081. // #include <nlohmann/detail/meta/type_traits.hpp>
  4082. // #include <nlohmann/detail/value_t.hpp>
  4083. #ifdef JSON_HAS_CPP_17
  4084. // #include <filesystem>
  4085. #include <boost/filesystem.hpp>
  4086. #endif
  4087. namespace nlohmann
  4088. {
  4089. namespace detail
  4090. {
  4091. //////////////////
  4092. // constructors //
  4093. //////////////////
  4094. /*
  4095. * Note all external_constructor<>::construct functions need to call
  4096. * j.m_value.destroy(j.m_type) to avoid a memory leak in case j contains an
  4097. * allocated value (e.g., a string). See bug issue
  4098. * https://github.com/nlohmann/json/issues/2865 for more information.
  4099. */
  4100. template<value_t> struct external_constructor;
  4101. template<>
  4102. struct external_constructor<value_t::boolean>
  4103. {
  4104. template<typename BasicJsonType>
  4105. static void construct(BasicJsonType& j, typename BasicJsonType::boolean_t b) noexcept
  4106. {
  4107. j.m_value.destroy(j.m_type);
  4108. j.m_type = value_t::boolean;
  4109. j.m_value = b;
  4110. j.assert_invariant();
  4111. }
  4112. };
  4113. template<>
  4114. struct external_constructor<value_t::string>
  4115. {
  4116. template<typename BasicJsonType>
  4117. static void construct(BasicJsonType& j, const typename BasicJsonType::string_t& s)
  4118. {
  4119. j.m_value.destroy(j.m_type);
  4120. j.m_type = value_t::string;
  4121. j.m_value = s;
  4122. j.assert_invariant();
  4123. }
  4124. template<typename BasicJsonType>
  4125. static void construct(BasicJsonType& j, typename BasicJsonType::string_t&& s)
  4126. {
  4127. j.m_value.destroy(j.m_type);
  4128. j.m_type = value_t::string;
  4129. j.m_value = std::move(s);
  4130. j.assert_invariant();
  4131. }
  4132. template < typename BasicJsonType, typename CompatibleStringType,
  4133. enable_if_t < !std::is_same<CompatibleStringType, typename BasicJsonType::string_t>::value,
  4134. int > = 0 >
  4135. static void construct(BasicJsonType& j, const CompatibleStringType& str)
  4136. {
  4137. j.m_value.destroy(j.m_type);
  4138. j.m_type = value_t::string;
  4139. j.m_value.string = j.template create<typename BasicJsonType::string_t>(str);
  4140. j.assert_invariant();
  4141. }
  4142. };
  4143. template<>
  4144. struct external_constructor<value_t::binary>
  4145. {
  4146. template<typename BasicJsonType>
  4147. static void construct(BasicJsonType& j, const typename BasicJsonType::binary_t& b)
  4148. {
  4149. j.m_value.destroy(j.m_type);
  4150. j.m_type = value_t::binary;
  4151. j.m_value = typename BasicJsonType::binary_t(b);
  4152. j.assert_invariant();
  4153. }
  4154. template<typename BasicJsonType>
  4155. static void construct(BasicJsonType& j, typename BasicJsonType::binary_t&& b)
  4156. {
  4157. j.m_value.destroy(j.m_type);
  4158. j.m_type = value_t::binary;
  4159. j.m_value = typename BasicJsonType::binary_t(std::move(b));
  4160. j.assert_invariant();
  4161. }
  4162. };
  4163. template<>
  4164. struct external_constructor<value_t::number_float>
  4165. {
  4166. template<typename BasicJsonType>
  4167. static void construct(BasicJsonType& j, typename BasicJsonType::number_float_t val) noexcept
  4168. {
  4169. j.m_value.destroy(j.m_type);
  4170. j.m_type = value_t::number_float;
  4171. j.m_value = val;
  4172. j.assert_invariant();
  4173. }
  4174. };
  4175. template<>
  4176. struct external_constructor<value_t::number_unsigned>
  4177. {
  4178. template<typename BasicJsonType>
  4179. static void construct(BasicJsonType& j, typename BasicJsonType::number_unsigned_t val) noexcept
  4180. {
  4181. j.m_value.destroy(j.m_type);
  4182. j.m_type = value_t::number_unsigned;
  4183. j.m_value = val;
  4184. j.assert_invariant();
  4185. }
  4186. };
  4187. template<>
  4188. struct external_constructor<value_t::number_integer>
  4189. {
  4190. template<typename BasicJsonType>
  4191. static void construct(BasicJsonType& j, typename BasicJsonType::number_integer_t val) noexcept
  4192. {
  4193. j.m_value.destroy(j.m_type);
  4194. j.m_type = value_t::number_integer;
  4195. j.m_value = val;
  4196. j.assert_invariant();
  4197. }
  4198. };
  4199. template<>
  4200. struct external_constructor<value_t::array>
  4201. {
  4202. template<typename BasicJsonType>
  4203. static void construct(BasicJsonType& j, const typename BasicJsonType::array_t& arr)
  4204. {
  4205. j.m_value.destroy(j.m_type);
  4206. j.m_type = value_t::array;
  4207. j.m_value = arr;
  4208. j.set_parents();
  4209. j.assert_invariant();
  4210. }
  4211. template<typename BasicJsonType>
  4212. static void construct(BasicJsonType& j, typename BasicJsonType::array_t&& arr)
  4213. {
  4214. j.m_value.destroy(j.m_type);
  4215. j.m_type = value_t::array;
  4216. j.m_value = std::move(arr);
  4217. j.set_parents();
  4218. j.assert_invariant();
  4219. }
  4220. template < typename BasicJsonType, typename CompatibleArrayType,
  4221. enable_if_t < !std::is_same<CompatibleArrayType, typename BasicJsonType::array_t>::value,
  4222. int > = 0 >
  4223. static void construct(BasicJsonType& j, const CompatibleArrayType& arr)
  4224. {
  4225. using std::begin;
  4226. using std::end;
  4227. j.m_value.destroy(j.m_type);
  4228. j.m_type = value_t::array;
  4229. j.m_value.array = j.template create<typename BasicJsonType::array_t>(begin(arr), end(arr));
  4230. j.set_parents();
  4231. j.assert_invariant();
  4232. }
  4233. template<typename BasicJsonType>
  4234. static void construct(BasicJsonType& j, const std::vector<bool>& arr)
  4235. {
  4236. j.m_value.destroy(j.m_type);
  4237. j.m_type = value_t::array;
  4238. j.m_value = value_t::array;
  4239. j.m_value.array->reserve(arr.size());
  4240. for (const bool x : arr)
  4241. {
  4242. j.m_value.array->push_back(x);
  4243. j.set_parent(j.m_value.array->back());
  4244. }
  4245. j.assert_invariant();
  4246. }
  4247. template<typename BasicJsonType, typename T,
  4248. enable_if_t<std::is_convertible<T, BasicJsonType>::value, int> = 0>
  4249. static void construct(BasicJsonType& j, const std::valarray<T>& arr)
  4250. {
  4251. j.m_value.destroy(j.m_type);
  4252. j.m_type = value_t::array;
  4253. j.m_value = value_t::array;
  4254. j.m_value.array->resize(arr.size());
  4255. if (arr.size() > 0)
  4256. {
  4257. std::copy(std::begin(arr), std::end(arr), j.m_value.array->begin());
  4258. }
  4259. j.set_parents();
  4260. j.assert_invariant();
  4261. }
  4262. };
  4263. template<>
  4264. struct external_constructor<value_t::object>
  4265. {
  4266. template<typename BasicJsonType>
  4267. static void construct(BasicJsonType& j, const typename BasicJsonType::object_t& obj)
  4268. {
  4269. j.m_value.destroy(j.m_type);
  4270. j.m_type = value_t::object;
  4271. j.m_value = obj;
  4272. j.set_parents();
  4273. j.assert_invariant();
  4274. }
  4275. template<typename BasicJsonType>
  4276. static void construct(BasicJsonType& j, typename BasicJsonType::object_t&& obj)
  4277. {
  4278. j.m_value.destroy(j.m_type);
  4279. j.m_type = value_t::object;
  4280. j.m_value = std::move(obj);
  4281. j.set_parents();
  4282. j.assert_invariant();
  4283. }
  4284. template < typename BasicJsonType, typename CompatibleObjectType,
  4285. enable_if_t < !std::is_same<CompatibleObjectType, typename BasicJsonType::object_t>::value, int > = 0 >
  4286. static void construct(BasicJsonType& j, const CompatibleObjectType& obj)
  4287. {
  4288. using std::begin;
  4289. using std::end;
  4290. j.m_value.destroy(j.m_type);
  4291. j.m_type = value_t::object;
  4292. j.m_value.object = j.template create<typename BasicJsonType::object_t>(begin(obj), end(obj));
  4293. j.set_parents();
  4294. j.assert_invariant();
  4295. }
  4296. };
  4297. /////////////
  4298. // to_json //
  4299. /////////////
  4300. template<typename BasicJsonType, typename T,
  4301. enable_if_t<std::is_same<T, typename BasicJsonType::boolean_t>::value, int> = 0>
  4302. void to_json(BasicJsonType& j, T b) noexcept
  4303. {
  4304. external_constructor<value_t::boolean>::construct(j, b);
  4305. }
  4306. template<typename BasicJsonType, typename CompatibleString,
  4307. enable_if_t<std::is_constructible<typename BasicJsonType::string_t, CompatibleString>::value, int> = 0>
  4308. void to_json(BasicJsonType& j, const CompatibleString& s)
  4309. {
  4310. external_constructor<value_t::string>::construct(j, s);
  4311. }
  4312. template<typename BasicJsonType>
  4313. void to_json(BasicJsonType& j, typename BasicJsonType::string_t&& s)
  4314. {
  4315. external_constructor<value_t::string>::construct(j, std::move(s));
  4316. }
  4317. template<typename BasicJsonType, typename FloatType,
  4318. enable_if_t<std::is_floating_point<FloatType>::value, int> = 0>
  4319. void to_json(BasicJsonType& j, FloatType val) noexcept
  4320. {
  4321. external_constructor<value_t::number_float>::construct(j, static_cast<typename BasicJsonType::number_float_t>(val));
  4322. }
  4323. template<typename BasicJsonType, typename CompatibleNumberUnsignedType,
  4324. enable_if_t<is_compatible_integer_type<typename BasicJsonType::number_unsigned_t, CompatibleNumberUnsignedType>::value, int> = 0>
  4325. void to_json(BasicJsonType& j, CompatibleNumberUnsignedType val) noexcept
  4326. {
  4327. external_constructor<value_t::number_unsigned>::construct(j, static_cast<typename BasicJsonType::number_unsigned_t>(val));
  4328. }
  4329. template<typename BasicJsonType, typename CompatibleNumberIntegerType,
  4330. enable_if_t<is_compatible_integer_type<typename BasicJsonType::number_integer_t, CompatibleNumberIntegerType>::value, int> = 0>
  4331. void to_json(BasicJsonType& j, CompatibleNumberIntegerType val) noexcept
  4332. {
  4333. external_constructor<value_t::number_integer>::construct(j, static_cast<typename BasicJsonType::number_integer_t>(val));
  4334. }
  4335. template<typename BasicJsonType, typename EnumType,
  4336. enable_if_t<std::is_enum<EnumType>::value, int> = 0>
  4337. void to_json(BasicJsonType& j, EnumType e) noexcept
  4338. {
  4339. using underlying_type = typename std::underlying_type<EnumType>::type;
  4340. external_constructor<value_t::number_integer>::construct(j, static_cast<underlying_type>(e));
  4341. }
  4342. template<typename BasicJsonType>
  4343. void to_json(BasicJsonType& j, const std::vector<bool>& e)
  4344. {
  4345. external_constructor<value_t::array>::construct(j, e);
  4346. }
  4347. template < typename BasicJsonType, typename CompatibleArrayType,
  4348. enable_if_t < is_compatible_array_type<BasicJsonType,
  4349. CompatibleArrayType>::value&&
  4350. !is_compatible_object_type<BasicJsonType, CompatibleArrayType>::value&&
  4351. !is_compatible_string_type<BasicJsonType, CompatibleArrayType>::value&&
  4352. !std::is_same<typename BasicJsonType::binary_t, CompatibleArrayType>::value&&
  4353. !is_basic_json<CompatibleArrayType>::value,
  4354. int > = 0 >
  4355. void to_json(BasicJsonType& j, const CompatibleArrayType& arr)
  4356. {
  4357. external_constructor<value_t::array>::construct(j, arr);
  4358. }
  4359. template<typename BasicJsonType>
  4360. void to_json(BasicJsonType& j, const typename BasicJsonType::binary_t& bin)
  4361. {
  4362. external_constructor<value_t::binary>::construct(j, bin);
  4363. }
  4364. template<typename BasicJsonType, typename T,
  4365. enable_if_t<std::is_convertible<T, BasicJsonType>::value, int> = 0>
  4366. void to_json(BasicJsonType& j, const std::valarray<T>& arr)
  4367. {
  4368. external_constructor<value_t::array>::construct(j, std::move(arr));
  4369. }
  4370. template<typename BasicJsonType>
  4371. void to_json(BasicJsonType& j, typename BasicJsonType::array_t&& arr)
  4372. {
  4373. external_constructor<value_t::array>::construct(j, std::move(arr));
  4374. }
  4375. template < typename BasicJsonType, typename CompatibleObjectType,
  4376. enable_if_t < is_compatible_object_type<BasicJsonType, CompatibleObjectType>::value&& !is_basic_json<CompatibleObjectType>::value, int > = 0 >
  4377. void to_json(BasicJsonType& j, const CompatibleObjectType& obj)
  4378. {
  4379. external_constructor<value_t::object>::construct(j, obj);
  4380. }
  4381. template<typename BasicJsonType>
  4382. void to_json(BasicJsonType& j, typename BasicJsonType::object_t&& obj)
  4383. {
  4384. external_constructor<value_t::object>::construct(j, std::move(obj));
  4385. }
  4386. template <
  4387. typename BasicJsonType, typename T, std::size_t N,
  4388. enable_if_t < !std::is_constructible<typename BasicJsonType::string_t,
  4389. const T(&)[N]>::value, // NOLINT(cppcoreguidelines-avoid-c-arrays,hicpp-avoid-c-arrays,modernize-avoid-c-arrays)
  4390. int > = 0 >
  4391. void to_json(BasicJsonType& j, const T(&arr)[N]) // NOLINT(cppcoreguidelines-avoid-c-arrays,hicpp-avoid-c-arrays,modernize-avoid-c-arrays)
  4392. {
  4393. external_constructor<value_t::array>::construct(j, arr);
  4394. }
  4395. template < typename BasicJsonType, typename T1, typename T2, enable_if_t < std::is_constructible<BasicJsonType, T1>::value&& std::is_constructible<BasicJsonType, T2>::value, int > = 0 >
  4396. void to_json(BasicJsonType& j, const std::pair<T1, T2>& p)
  4397. {
  4398. j = { p.first, p.second };
  4399. }
  4400. // for https://github.com/nlohmann/json/pull/1134
  4401. template<typename BasicJsonType, typename T,
  4402. enable_if_t<std::is_same<T, iteration_proxy_value<typename BasicJsonType::iterator>>::value, int> = 0>
  4403. void to_json(BasicJsonType& j, const T& b)
  4404. {
  4405. j = { {b.key(), b.value()} };
  4406. }
  4407. template<typename BasicJsonType, typename Tuple, std::size_t... Idx>
  4408. void to_json_tuple_impl(BasicJsonType& j, const Tuple& t, index_sequence<Idx...> /*unused*/)
  4409. {
  4410. j = { std::get<Idx>(t)... };
  4411. }
  4412. template<typename BasicJsonType, typename T, enable_if_t<is_constructible_tuple<BasicJsonType, T>::value, int > = 0>
  4413. void to_json(BasicJsonType& j, const T& t)
  4414. {
  4415. to_json_tuple_impl(j, t, make_index_sequence<std::tuple_size<T>::value> {});
  4416. }
  4417. #ifdef JSON_HAS_CPP_17
  4418. template<typename BasicJsonType>
  4419. // void to_json(BasicJsonType& j, const std::filesystem::path& p)
  4420. void to_json(BasicJsonType& j, const boost::filesystem::path& p)
  4421. {
  4422. j = p.string();
  4423. }
  4424. #endif
  4425. struct to_json_fn
  4426. {
  4427. template<typename BasicJsonType, typename T>
  4428. auto operator()(BasicJsonType& j, T&& val) const noexcept(noexcept(to_json(j, std::forward<T>(val))))
  4429. -> decltype(to_json(j, std::forward<T>(val)), void())
  4430. {
  4431. return to_json(j, std::forward<T>(val));
  4432. }
  4433. };
  4434. } // namespace detail
  4435. /// namespace to hold default `to_json` function
  4436. /// to see why this is required:
  4437. /// http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2015/n4381.html
  4438. namespace // NOLINT(cert-dcl59-cpp,fuchsia-header-anon-namespaces,google-build-namespaces)
  4439. {
  4440. constexpr const auto& to_json = detail::static_const<detail::to_json_fn>::value; // NOLINT(misc-definitions-in-headers)
  4441. } // namespace
  4442. } // namespace nlohmann
  4443. // #include <nlohmann/detail/meta/identity_tag.hpp>
  4444. // #include <nlohmann/detail/meta/type_traits.hpp>
  4445. namespace nlohmann
  4446. {
  4447. template<typename ValueType, typename>
  4448. struct adl_serializer
  4449. {
  4450. /*!
  4451. @brief convert a JSON value to any value type
  4452. This function is usually called by the `get()` function of the
  4453. @ref basic_json class (either explicit or via conversion operators).
  4454. @note This function is chosen for default-constructible value types.
  4455. @param[in] j JSON value to read from
  4456. @param[in,out] val value to write to
  4457. */
  4458. template<typename BasicJsonType, typename TargetType = ValueType>
  4459. static auto from_json(BasicJsonType && j, TargetType& val) noexcept(
  4460. noexcept(::nlohmann::from_json(std::forward<BasicJsonType>(j), val)))
  4461. -> decltype(::nlohmann::from_json(std::forward<BasicJsonType>(j), val), void())
  4462. {
  4463. ::nlohmann::from_json(std::forward<BasicJsonType>(j), val);
  4464. }
  4465. /*!
  4466. @brief convert a JSON value to any value type
  4467. This function is usually called by the `get()` function of the
  4468. @ref basic_json class (either explicit or via conversion operators).
  4469. @note This function is chosen for value types which are not default-constructible.
  4470. @param[in] j JSON value to read from
  4471. @return copy of the JSON value, converted to @a ValueType
  4472. */
  4473. template<typename BasicJsonType, typename TargetType = ValueType>
  4474. static auto from_json(BasicJsonType && j) noexcept(
  4475. noexcept(::nlohmann::from_json(std::forward<BasicJsonType>(j), detail::identity_tag<TargetType> {})))
  4476. -> decltype(::nlohmann::from_json(std::forward<BasicJsonType>(j), detail::identity_tag<TargetType> {}))
  4477. {
  4478. return ::nlohmann::from_json(std::forward<BasicJsonType>(j), detail::identity_tag<TargetType> {});
  4479. }
  4480. /*!
  4481. @brief convert any value type to a JSON value
  4482. This function is usually called by the constructors of the @ref basic_json
  4483. class.
  4484. @param[in,out] j JSON value to write to
  4485. @param[in] val value to read from
  4486. */
  4487. template<typename BasicJsonType, typename TargetType = ValueType>
  4488. static auto to_json(BasicJsonType& j, TargetType && val) noexcept(
  4489. noexcept(::nlohmann::to_json(j, std::forward<TargetType>(val))))
  4490. -> decltype(::nlohmann::to_json(j, std::forward<TargetType>(val)), void())
  4491. {
  4492. ::nlohmann::to_json(j, std::forward<TargetType>(val));
  4493. }
  4494. };
  4495. } // namespace nlohmann
  4496. // #include <nlohmann/byte_container_with_subtype.hpp>
  4497. #include <cstdint> // uint8_t, uint64_t
  4498. #include <tuple> // tie
  4499. #include <utility> // move
  4500. namespace nlohmann
  4501. {
  4502. /*!
  4503. @brief an internal type for a backed binary type
  4504. This type extends the template parameter @a BinaryType provided to `basic_json`
  4505. with a subtype used by BSON and MessagePack. This type exists so that the user
  4506. does not have to specify a type themselves with a specific naming scheme in
  4507. order to override the binary type.
  4508. @tparam BinaryType container to store bytes (`std::vector<std::uint8_t>` by
  4509. default)
  4510. @since version 3.8.0; changed type of subtypes to std::uint64_t in 3.10.0.
  4511. */
  4512. template<typename BinaryType>
  4513. class byte_container_with_subtype : public BinaryType
  4514. {
  4515. public:
  4516. /// the type of the underlying container
  4517. using container_type = BinaryType;
  4518. /// the type of the subtype
  4519. using subtype_type = std::uint64_t;
  4520. byte_container_with_subtype() noexcept(noexcept(container_type()))
  4521. : container_type()
  4522. {}
  4523. byte_container_with_subtype(const container_type& b) noexcept(noexcept(container_type(b)))
  4524. : container_type(b)
  4525. {}
  4526. byte_container_with_subtype(container_type&& b) noexcept(noexcept(container_type(std::move(b))))
  4527. : container_type(std::move(b))
  4528. {}
  4529. byte_container_with_subtype(const container_type& b, subtype_type subtype_) noexcept(noexcept(container_type(b)))
  4530. : container_type(b)
  4531. , m_subtype(subtype_)
  4532. , m_has_subtype(true)
  4533. {}
  4534. byte_container_with_subtype(container_type&& b, subtype_type subtype_) noexcept(noexcept(container_type(std::move(b))))
  4535. : container_type(std::move(b))
  4536. , m_subtype(subtype_)
  4537. , m_has_subtype(true)
  4538. {}
  4539. bool operator==(const byte_container_with_subtype& rhs) const
  4540. {
  4541. return std::tie(static_cast<const BinaryType&>(*this), m_subtype, m_has_subtype) ==
  4542. std::tie(static_cast<const BinaryType&>(rhs), rhs.m_subtype, rhs.m_has_subtype);
  4543. }
  4544. bool operator!=(const byte_container_with_subtype& rhs) const
  4545. {
  4546. return !(rhs == *this);
  4547. }
  4548. /*!
  4549. @brief sets the binary subtype
  4550. Sets the binary subtype of the value, also flags a binary JSON value as
  4551. having a subtype, which has implications for serialization.
  4552. @complexity Constant.
  4553. @exceptionsafety No-throw guarantee: this member function never throws
  4554. exceptions.
  4555. @sa see @ref subtype() -- return the binary subtype
  4556. @sa see @ref clear_subtype() -- clears the binary subtype
  4557. @sa see @ref has_subtype() -- returns whether or not the binary value has a
  4558. subtype
  4559. @since version 3.8.0
  4560. */
  4561. void set_subtype(subtype_type subtype_) noexcept
  4562. {
  4563. m_subtype = subtype_;
  4564. m_has_subtype = true;
  4565. }
  4566. /*!
  4567. @brief return the binary subtype
  4568. Returns the numerical subtype of the value if it has a subtype. If it does
  4569. not have a subtype, this function will return subtype_type(-1) as a sentinel
  4570. value.
  4571. @return the numerical subtype of the binary value
  4572. @complexity Constant.
  4573. @exceptionsafety No-throw guarantee: this member function never throws
  4574. exceptions.
  4575. @sa see @ref set_subtype() -- sets the binary subtype
  4576. @sa see @ref clear_subtype() -- clears the binary subtype
  4577. @sa see @ref has_subtype() -- returns whether or not the binary value has a
  4578. subtype
  4579. @since version 3.8.0; fixed return value to properly return
  4580. subtype_type(-1) as documented in version 3.10.0
  4581. */
  4582. constexpr subtype_type subtype() const noexcept
  4583. {
  4584. return m_has_subtype ? m_subtype : subtype_type(-1);
  4585. }
  4586. /*!
  4587. @brief return whether the value has a subtype
  4588. @return whether the value has a subtype
  4589. @complexity Constant.
  4590. @exceptionsafety No-throw guarantee: this member function never throws
  4591. exceptions.
  4592. @sa see @ref subtype() -- return the binary subtype
  4593. @sa see @ref set_subtype() -- sets the binary subtype
  4594. @sa see @ref clear_subtype() -- clears the binary subtype
  4595. @since version 3.8.0
  4596. */
  4597. constexpr bool has_subtype() const noexcept
  4598. {
  4599. return m_has_subtype;
  4600. }
  4601. /*!
  4602. @brief clears the binary subtype
  4603. Clears the binary subtype and flags the value as not having a subtype, which
  4604. has implications for serialization; for instance MessagePack will prefer the
  4605. bin family over the ext family.
  4606. @complexity Constant.
  4607. @exceptionsafety No-throw guarantee: this member function never throws
  4608. exceptions.
  4609. @sa see @ref subtype() -- return the binary subtype
  4610. @sa see @ref set_subtype() -- sets the binary subtype
  4611. @sa see @ref has_subtype() -- returns whether or not the binary value has a
  4612. subtype
  4613. @since version 3.8.0
  4614. */
  4615. void clear_subtype() noexcept
  4616. {
  4617. m_subtype = 0;
  4618. m_has_subtype = false;
  4619. }
  4620. private:
  4621. subtype_type m_subtype = 0;
  4622. bool m_has_subtype = false;
  4623. };
  4624. } // namespace nlohmann
  4625. // #include <nlohmann/detail/conversions/from_json.hpp>
  4626. // #include <nlohmann/detail/conversions/to_json.hpp>
  4627. // #include <nlohmann/detail/exceptions.hpp>
  4628. // #include <nlohmann/detail/hash.hpp>
  4629. #include <cstdint> // uint8_t
  4630. #include <cstddef> // size_t
  4631. #include <functional> // hash
  4632. // #include <nlohmann/detail/macro_scope.hpp>
  4633. // #include <nlohmann/detail/value_t.hpp>
  4634. namespace nlohmann
  4635. {
  4636. namespace detail
  4637. {
  4638. // boost::hash_combine
  4639. inline std::size_t combine(std::size_t seed, std::size_t h) noexcept
  4640. {
  4641. seed ^= h + 0x9e3779b9 + (seed << 6U) + (seed >> 2U);
  4642. return seed;
  4643. }
  4644. /*!
  4645. @brief hash a JSON value
  4646. The hash function tries to rely on std::hash where possible. Furthermore, the
  4647. type of the JSON value is taken into account to have different hash values for
  4648. null, 0, 0U, and false, etc.
  4649. @tparam BasicJsonType basic_json specialization
  4650. @param j JSON value to hash
  4651. @return hash value of j
  4652. */
  4653. template<typename BasicJsonType>
  4654. std::size_t hash(const BasicJsonType& j)
  4655. {
  4656. using string_t = typename BasicJsonType::string_t;
  4657. using number_integer_t = typename BasicJsonType::number_integer_t;
  4658. using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
  4659. using number_float_t = typename BasicJsonType::number_float_t;
  4660. const auto type = static_cast<std::size_t>(j.type());
  4661. switch (j.type())
  4662. {
  4663. case BasicJsonType::value_t::null:
  4664. case BasicJsonType::value_t::discarded:
  4665. {
  4666. return combine(type, 0);
  4667. }
  4668. case BasicJsonType::value_t::object:
  4669. {
  4670. auto seed = combine(type, j.size());
  4671. for (const auto& element : j.items())
  4672. {
  4673. const auto h = std::hash<string_t> {}(element.key());
  4674. seed = combine(seed, h);
  4675. seed = combine(seed, hash(element.value()));
  4676. }
  4677. return seed;
  4678. }
  4679. case BasicJsonType::value_t::array:
  4680. {
  4681. auto seed = combine(type, j.size());
  4682. for (const auto& element : j)
  4683. {
  4684. seed = combine(seed, hash(element));
  4685. }
  4686. return seed;
  4687. }
  4688. case BasicJsonType::value_t::string:
  4689. {
  4690. const auto h = std::hash<string_t> {}(j.template get_ref<const string_t&>());
  4691. return combine(type, h);
  4692. }
  4693. case BasicJsonType::value_t::boolean:
  4694. {
  4695. const auto h = std::hash<bool> {}(j.template get<bool>());
  4696. return combine(type, h);
  4697. }
  4698. case BasicJsonType::value_t::number_integer:
  4699. {
  4700. const auto h = std::hash<number_integer_t> {}(j.template get<number_integer_t>());
  4701. return combine(type, h);
  4702. }
  4703. case BasicJsonType::value_t::number_unsigned:
  4704. {
  4705. const auto h = std::hash<number_unsigned_t> {}(j.template get<number_unsigned_t>());
  4706. return combine(type, h);
  4707. }
  4708. case BasicJsonType::value_t::number_float:
  4709. {
  4710. const auto h = std::hash<number_float_t> {}(j.template get<number_float_t>());
  4711. return combine(type, h);
  4712. }
  4713. case BasicJsonType::value_t::binary:
  4714. {
  4715. auto seed = combine(type, j.get_binary().size());
  4716. const auto h = std::hash<bool> {}(j.get_binary().has_subtype());
  4717. seed = combine(seed, h);
  4718. seed = combine(seed, static_cast<std::size_t>(j.get_binary().subtype()));
  4719. for (const auto byte : j.get_binary())
  4720. {
  4721. seed = combine(seed, std::hash<std::uint8_t> {}(byte));
  4722. }
  4723. return seed;
  4724. }
  4725. default: // LCOV_EXCL_LINE
  4726. JSON_ASSERT(false); // NOLINT(cert-dcl03-c,hicpp-static-assert,misc-static-assert) LCOV_EXCL_LINE
  4727. return 0; // LCOV_EXCL_LINE
  4728. }
  4729. }
  4730. } // namespace detail
  4731. } // namespace nlohmann
  4732. // #include <nlohmann/detail/input/binary_reader.hpp>
  4733. #include <algorithm> // generate_n
  4734. #include <array> // array
  4735. #include <cmath> // ldexp
  4736. #include <cstddef> // size_t
  4737. #include <cstdint> // uint8_t, uint16_t, uint32_t, uint64_t
  4738. #include <cstdio> // snprintf
  4739. #include <cstring> // memcpy
  4740. #include <iterator> // back_inserter
  4741. #include <limits> // numeric_limits
  4742. #include <string> // char_traits, string
  4743. #include <utility> // make_pair, move
  4744. #include <vector> // vector
  4745. // #include <nlohmann/detail/exceptions.hpp>
  4746. // #include <nlohmann/detail/input/input_adapters.hpp>
  4747. #include <array> // array
  4748. #include <cstddef> // size_t
  4749. #include <cstring> // strlen
  4750. #include <iterator> // begin, end, iterator_traits, random_access_iterator_tag, distance, next
  4751. #include <memory> // shared_ptr, make_shared, addressof
  4752. #include <numeric> // accumulate
  4753. #include <string> // string, char_traits
  4754. #include <type_traits> // enable_if, is_base_of, is_pointer, is_integral, remove_pointer
  4755. #include <utility> // pair, declval
  4756. #ifndef JSON_NO_IO
  4757. #include <cstdio> // FILE *
  4758. #include <istream> // istream
  4759. #endif // JSON_NO_IO
  4760. // #include <nlohmann/detail/iterators/iterator_traits.hpp>
  4761. // #include <nlohmann/detail/macro_scope.hpp>
  4762. namespace nlohmann
  4763. {
  4764. namespace detail
  4765. {
  4766. /// the supported input formats
  4767. enum class input_format_t { json, cbor, msgpack, ubjson, bson };
  4768. ////////////////////
  4769. // input adapters //
  4770. ////////////////////
  4771. #ifndef JSON_NO_IO
  4772. /*!
  4773. Input adapter for stdio file access. This adapter read only 1 byte and do not use any
  4774. buffer. This adapter is a very low level adapter.
  4775. */
  4776. class file_input_adapter
  4777. {
  4778. public:
  4779. using char_type = char;
  4780. JSON_HEDLEY_NON_NULL(2)
  4781. explicit file_input_adapter(std::FILE* f) noexcept
  4782. : m_file(f)
  4783. {}
  4784. // make class move-only
  4785. file_input_adapter(const file_input_adapter&) = delete;
  4786. file_input_adapter(file_input_adapter&&) noexcept = default;
  4787. file_input_adapter& operator=(const file_input_adapter&) = delete;
  4788. file_input_adapter& operator=(file_input_adapter&&) = delete;
  4789. ~file_input_adapter() = default;
  4790. std::char_traits<char>::int_type get_character() noexcept
  4791. {
  4792. return std::fgetc(m_file);
  4793. }
  4794. private:
  4795. /// the file pointer to read from
  4796. std::FILE* m_file;
  4797. };
  4798. /*!
  4799. Input adapter for a (caching) istream. Ignores a UFT Byte Order Mark at
  4800. beginning of input. Does not support changing the underlying std::streambuf
  4801. in mid-input. Maintains underlying std::istream and std::streambuf to support
  4802. subsequent use of standard std::istream operations to process any input
  4803. characters following those used in parsing the JSON input. Clears the
  4804. std::istream flags; any input errors (e.g., EOF) will be detected by the first
  4805. subsequent call for input from the std::istream.
  4806. */
  4807. class input_stream_adapter
  4808. {
  4809. public:
  4810. using char_type = char;
  4811. ~input_stream_adapter()
  4812. {
  4813. // clear stream flags; we use underlying streambuf I/O, do not
  4814. // maintain ifstream flags, except eof
  4815. if (is != nullptr)
  4816. {
  4817. is->clear(is->rdstate() & std::ios::eofbit);
  4818. }
  4819. }
  4820. explicit input_stream_adapter(std::istream& i)
  4821. : is(&i), sb(i.rdbuf())
  4822. {}
  4823. // delete because of pointer members
  4824. input_stream_adapter(const input_stream_adapter&) = delete;
  4825. input_stream_adapter& operator=(input_stream_adapter&) = delete;
  4826. input_stream_adapter& operator=(input_stream_adapter&&) = delete;
  4827. input_stream_adapter(input_stream_adapter&& rhs) noexcept
  4828. : is(rhs.is), sb(rhs.sb)
  4829. {
  4830. rhs.is = nullptr;
  4831. rhs.sb = nullptr;
  4832. }
  4833. // std::istream/std::streambuf use std::char_traits<char>::to_int_type, to
  4834. // ensure that std::char_traits<char>::eof() and the character 0xFF do not
  4835. // end up as the same value, eg. 0xFFFFFFFF.
  4836. std::char_traits<char>::int_type get_character()
  4837. {
  4838. auto res = sb->sbumpc();
  4839. // set eof manually, as we don't use the istream interface.
  4840. if (JSON_HEDLEY_UNLIKELY(res == std::char_traits<char>::eof()))
  4841. {
  4842. is->clear(is->rdstate() | std::ios::eofbit);
  4843. }
  4844. return res;
  4845. }
  4846. private:
  4847. /// the associated input stream
  4848. std::istream* is = nullptr;
  4849. std::streambuf* sb = nullptr;
  4850. };
  4851. #endif // JSON_NO_IO
  4852. // General-purpose iterator-based adapter. It might not be as fast as
  4853. // theoretically possible for some containers, but it is extremely versatile.
  4854. template<typename IteratorType>
  4855. class iterator_input_adapter
  4856. {
  4857. public:
  4858. using char_type = typename std::iterator_traits<IteratorType>::value_type;
  4859. iterator_input_adapter(IteratorType first, IteratorType last)
  4860. : current(std::move(first)), end(std::move(last))
  4861. {}
  4862. typename std::char_traits<char_type>::int_type get_character()
  4863. {
  4864. if (JSON_HEDLEY_LIKELY(current != end))
  4865. {
  4866. auto result = std::char_traits<char_type>::to_int_type(*current);
  4867. std::advance(current, 1);
  4868. return result;
  4869. }
  4870. return std::char_traits<char_type>::eof();
  4871. }
  4872. private:
  4873. IteratorType current;
  4874. IteratorType end;
  4875. template<typename BaseInputAdapter, size_t T>
  4876. friend struct wide_string_input_helper;
  4877. bool empty() const
  4878. {
  4879. return current == end;
  4880. }
  4881. };
  4882. template<typename BaseInputAdapter, size_t T>
  4883. struct wide_string_input_helper;
  4884. template<typename BaseInputAdapter>
  4885. struct wide_string_input_helper<BaseInputAdapter, 4>
  4886. {
  4887. // UTF-32
  4888. static void fill_buffer(BaseInputAdapter& input,
  4889. std::array<std::char_traits<char>::int_type, 4>& utf8_bytes,
  4890. size_t& utf8_bytes_index,
  4891. size_t& utf8_bytes_filled)
  4892. {
  4893. utf8_bytes_index = 0;
  4894. if (JSON_HEDLEY_UNLIKELY(input.empty()))
  4895. {
  4896. utf8_bytes[0] = std::char_traits<char>::eof();
  4897. utf8_bytes_filled = 1;
  4898. }
  4899. else
  4900. {
  4901. // get the current character
  4902. const auto wc = input.get_character();
  4903. // UTF-32 to UTF-8 encoding
  4904. if (wc < 0x80)
  4905. {
  4906. utf8_bytes[0] = static_cast<std::char_traits<char>::int_type>(wc);
  4907. utf8_bytes_filled = 1;
  4908. }
  4909. else if (wc <= 0x7FF)
  4910. {
  4911. utf8_bytes[0] = static_cast<std::char_traits<char>::int_type>(0xC0u | ((static_cast<unsigned int>(wc) >> 6u) & 0x1Fu));
  4912. utf8_bytes[1] = static_cast<std::char_traits<char>::int_type>(0x80u | (static_cast<unsigned int>(wc) & 0x3Fu));
  4913. utf8_bytes_filled = 2;
  4914. }
  4915. else if (wc <= 0xFFFF)
  4916. {
  4917. utf8_bytes[0] = static_cast<std::char_traits<char>::int_type>(0xE0u | ((static_cast<unsigned int>(wc) >> 12u) & 0x0Fu));
  4918. utf8_bytes[1] = static_cast<std::char_traits<char>::int_type>(0x80u | ((static_cast<unsigned int>(wc) >> 6u) & 0x3Fu));
  4919. utf8_bytes[2] = static_cast<std::char_traits<char>::int_type>(0x80u | (static_cast<unsigned int>(wc) & 0x3Fu));
  4920. utf8_bytes_filled = 3;
  4921. }
  4922. else if (wc <= 0x10FFFF)
  4923. {
  4924. utf8_bytes[0] = static_cast<std::char_traits<char>::int_type>(0xF0u | ((static_cast<unsigned int>(wc) >> 18u) & 0x07u));
  4925. utf8_bytes[1] = static_cast<std::char_traits<char>::int_type>(0x80u | ((static_cast<unsigned int>(wc) >> 12u) & 0x3Fu));
  4926. utf8_bytes[2] = static_cast<std::char_traits<char>::int_type>(0x80u | ((static_cast<unsigned int>(wc) >> 6u) & 0x3Fu));
  4927. utf8_bytes[3] = static_cast<std::char_traits<char>::int_type>(0x80u | (static_cast<unsigned int>(wc) & 0x3Fu));
  4928. utf8_bytes_filled = 4;
  4929. }
  4930. else
  4931. {
  4932. // unknown character
  4933. utf8_bytes[0] = static_cast<std::char_traits<char>::int_type>(wc);
  4934. utf8_bytes_filled = 1;
  4935. }
  4936. }
  4937. }
  4938. };
  4939. template<typename BaseInputAdapter>
  4940. struct wide_string_input_helper<BaseInputAdapter, 2>
  4941. {
  4942. // UTF-16
  4943. static void fill_buffer(BaseInputAdapter& input,
  4944. std::array<std::char_traits<char>::int_type, 4>& utf8_bytes,
  4945. size_t& utf8_bytes_index,
  4946. size_t& utf8_bytes_filled)
  4947. {
  4948. utf8_bytes_index = 0;
  4949. if (JSON_HEDLEY_UNLIKELY(input.empty()))
  4950. {
  4951. utf8_bytes[0] = std::char_traits<char>::eof();
  4952. utf8_bytes_filled = 1;
  4953. }
  4954. else
  4955. {
  4956. // get the current character
  4957. const auto wc = input.get_character();
  4958. // UTF-16 to UTF-8 encoding
  4959. if (wc < 0x80)
  4960. {
  4961. utf8_bytes[0] = static_cast<std::char_traits<char>::int_type>(wc);
  4962. utf8_bytes_filled = 1;
  4963. }
  4964. else if (wc <= 0x7FF)
  4965. {
  4966. utf8_bytes[0] = static_cast<std::char_traits<char>::int_type>(0xC0u | ((static_cast<unsigned int>(wc) >> 6u)));
  4967. utf8_bytes[1] = static_cast<std::char_traits<char>::int_type>(0x80u | (static_cast<unsigned int>(wc) & 0x3Fu));
  4968. utf8_bytes_filled = 2;
  4969. }
  4970. else if (0xD800 > wc || wc >= 0xE000)
  4971. {
  4972. utf8_bytes[0] = static_cast<std::char_traits<char>::int_type>(0xE0u | ((static_cast<unsigned int>(wc) >> 12u)));
  4973. utf8_bytes[1] = static_cast<std::char_traits<char>::int_type>(0x80u | ((static_cast<unsigned int>(wc) >> 6u) & 0x3Fu));
  4974. utf8_bytes[2] = static_cast<std::char_traits<char>::int_type>(0x80u | (static_cast<unsigned int>(wc) & 0x3Fu));
  4975. utf8_bytes_filled = 3;
  4976. }
  4977. else
  4978. {
  4979. if (JSON_HEDLEY_UNLIKELY(!input.empty()))
  4980. {
  4981. const auto wc2 = static_cast<unsigned int>(input.get_character());
  4982. const auto charcode = 0x10000u + (((static_cast<unsigned int>(wc) & 0x3FFu) << 10u) | (wc2 & 0x3FFu));
  4983. utf8_bytes[0] = static_cast<std::char_traits<char>::int_type>(0xF0u | (charcode >> 18u));
  4984. utf8_bytes[1] = static_cast<std::char_traits<char>::int_type>(0x80u | ((charcode >> 12u) & 0x3Fu));
  4985. utf8_bytes[2] = static_cast<std::char_traits<char>::int_type>(0x80u | ((charcode >> 6u) & 0x3Fu));
  4986. utf8_bytes[3] = static_cast<std::char_traits<char>::int_type>(0x80u | (charcode & 0x3Fu));
  4987. utf8_bytes_filled = 4;
  4988. }
  4989. else
  4990. {
  4991. utf8_bytes[0] = static_cast<std::char_traits<char>::int_type>(wc);
  4992. utf8_bytes_filled = 1;
  4993. }
  4994. }
  4995. }
  4996. }
  4997. };
  4998. // Wraps another input apdater to convert wide character types into individual bytes.
  4999. template<typename BaseInputAdapter, typename WideCharType>
  5000. class wide_string_input_adapter
  5001. {
  5002. public:
  5003. using char_type = char;
  5004. wide_string_input_adapter(BaseInputAdapter base)
  5005. : base_adapter(base) {}
  5006. typename std::char_traits<char>::int_type get_character() noexcept
  5007. {
  5008. // check if buffer needs to be filled
  5009. if (utf8_bytes_index == utf8_bytes_filled)
  5010. {
  5011. fill_buffer<sizeof(WideCharType)>();
  5012. JSON_ASSERT(utf8_bytes_filled > 0);
  5013. JSON_ASSERT(utf8_bytes_index == 0);
  5014. }
  5015. // use buffer
  5016. JSON_ASSERT(utf8_bytes_filled > 0);
  5017. JSON_ASSERT(utf8_bytes_index < utf8_bytes_filled);
  5018. return utf8_bytes[utf8_bytes_index++];
  5019. }
  5020. private:
  5021. BaseInputAdapter base_adapter;
  5022. template<size_t T>
  5023. void fill_buffer()
  5024. {
  5025. wide_string_input_helper<BaseInputAdapter, T>::fill_buffer(base_adapter, utf8_bytes, utf8_bytes_index, utf8_bytes_filled);
  5026. }
  5027. /// a buffer for UTF-8 bytes
  5028. std::array<std::char_traits<char>::int_type, 4> utf8_bytes = {{0, 0, 0, 0}};
  5029. /// index to the utf8_codes array for the next valid byte
  5030. std::size_t utf8_bytes_index = 0;
  5031. /// number of valid bytes in the utf8_codes array
  5032. std::size_t utf8_bytes_filled = 0;
  5033. };
  5034. template<typename IteratorType, typename Enable = void>
  5035. struct iterator_input_adapter_factory
  5036. {
  5037. using iterator_type = IteratorType;
  5038. using char_type = typename std::iterator_traits<iterator_type>::value_type;
  5039. using adapter_type = iterator_input_adapter<iterator_type>;
  5040. static adapter_type create(IteratorType first, IteratorType last)
  5041. {
  5042. return adapter_type(std::move(first), std::move(last));
  5043. }
  5044. };
  5045. template<typename T>
  5046. struct is_iterator_of_multibyte
  5047. {
  5048. using value_type = typename std::iterator_traits<T>::value_type;
  5049. enum
  5050. {
  5051. value = sizeof(value_type) > 1
  5052. };
  5053. };
  5054. template<typename IteratorType>
  5055. struct iterator_input_adapter_factory<IteratorType, enable_if_t<is_iterator_of_multibyte<IteratorType>::value>>
  5056. {
  5057. using iterator_type = IteratorType;
  5058. using char_type = typename std::iterator_traits<iterator_type>::value_type;
  5059. using base_adapter_type = iterator_input_adapter<iterator_type>;
  5060. using adapter_type = wide_string_input_adapter<base_adapter_type, char_type>;
  5061. static adapter_type create(IteratorType first, IteratorType last)
  5062. {
  5063. return adapter_type(base_adapter_type(std::move(first), std::move(last)));
  5064. }
  5065. };
  5066. // General purpose iterator-based input
  5067. template<typename IteratorType>
  5068. typename iterator_input_adapter_factory<IteratorType>::adapter_type input_adapter(IteratorType first, IteratorType last)
  5069. {
  5070. using factory_type = iterator_input_adapter_factory<IteratorType>;
  5071. return factory_type::create(first, last);
  5072. }
  5073. // Convenience shorthand from container to iterator
  5074. // Enables ADL on begin(container) and end(container)
  5075. // Encloses the using declarations in namespace for not to leak them to outside scope
  5076. namespace container_input_adapter_factory_impl
  5077. {
  5078. using std::begin;
  5079. using std::end;
  5080. template<typename ContainerType, typename Enable = void>
  5081. struct container_input_adapter_factory {};
  5082. template<typename ContainerType>
  5083. struct container_input_adapter_factory< ContainerType,
  5084. void_t<decltype(begin(std::declval<ContainerType>()), end(std::declval<ContainerType>()))>>
  5085. {
  5086. using adapter_type = decltype(input_adapter(begin(std::declval<ContainerType>()), end(std::declval<ContainerType>())));
  5087. static adapter_type create(const ContainerType& container)
  5088. {
  5089. return input_adapter(begin(container), end(container));
  5090. }
  5091. };
  5092. } // namespace container_input_adapter_factory_impl
  5093. template<typename ContainerType>
  5094. typename container_input_adapter_factory_impl::container_input_adapter_factory<ContainerType>::adapter_type input_adapter(const ContainerType& container)
  5095. {
  5096. return container_input_adapter_factory_impl::container_input_adapter_factory<ContainerType>::create(container);
  5097. }
  5098. #ifndef JSON_NO_IO
  5099. // Special cases with fast paths
  5100. inline file_input_adapter input_adapter(std::FILE* file)
  5101. {
  5102. return file_input_adapter(file);
  5103. }
  5104. inline input_stream_adapter input_adapter(std::istream& stream)
  5105. {
  5106. return input_stream_adapter(stream);
  5107. }
  5108. inline input_stream_adapter input_adapter(std::istream&& stream)
  5109. {
  5110. return input_stream_adapter(stream);
  5111. }
  5112. #endif // JSON_NO_IO
  5113. using contiguous_bytes_input_adapter = decltype(input_adapter(std::declval<const char*>(), std::declval<const char*>()));
  5114. // Null-delimited strings, and the like.
  5115. template < typename CharT,
  5116. typename std::enable_if <
  5117. std::is_pointer<CharT>::value&&
  5118. !std::is_array<CharT>::value&&
  5119. std::is_integral<typename std::remove_pointer<CharT>::type>::value&&
  5120. sizeof(typename std::remove_pointer<CharT>::type) == 1,
  5121. int >::type = 0 >
  5122. contiguous_bytes_input_adapter input_adapter(CharT b)
  5123. {
  5124. auto length = std::strlen(reinterpret_cast<const char*>(b));
  5125. const auto* ptr = reinterpret_cast<const char*>(b);
  5126. return input_adapter(ptr, ptr + length);
  5127. }
  5128. template<typename T, std::size_t N>
  5129. 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)
  5130. {
  5131. return input_adapter(array, array + N);
  5132. }
  5133. // This class only handles inputs of input_buffer_adapter type.
  5134. // It's required so that expressions like {ptr, len} can be implicitely casted
  5135. // to the correct adapter.
  5136. class span_input_adapter
  5137. {
  5138. public:
  5139. template < typename CharT,
  5140. typename std::enable_if <
  5141. std::is_pointer<CharT>::value&&
  5142. std::is_integral<typename std::remove_pointer<CharT>::type>::value&&
  5143. sizeof(typename std::remove_pointer<CharT>::type) == 1,
  5144. int >::type = 0 >
  5145. span_input_adapter(CharT b, std::size_t l)
  5146. : ia(reinterpret_cast<const char*>(b), reinterpret_cast<const char*>(b) + l) {}
  5147. template<class IteratorType,
  5148. typename std::enable_if<
  5149. std::is_same<typename iterator_traits<IteratorType>::iterator_category, std::random_access_iterator_tag>::value,
  5150. int>::type = 0>
  5151. span_input_adapter(IteratorType first, IteratorType last)
  5152. : ia(input_adapter(first, last)) {}
  5153. contiguous_bytes_input_adapter&& get()
  5154. {
  5155. return std::move(ia); // NOLINT(hicpp-move-const-arg,performance-move-const-arg)
  5156. }
  5157. private:
  5158. contiguous_bytes_input_adapter ia;
  5159. };
  5160. } // namespace detail
  5161. } // namespace nlohmann
  5162. // #include <nlohmann/detail/input/json_sax.hpp>
  5163. #include <cstddef>
  5164. #include <string> // string
  5165. #include <utility> // move
  5166. #include <vector> // vector
  5167. // #include <nlohmann/detail/exceptions.hpp>
  5168. // #include <nlohmann/detail/macro_scope.hpp>
  5169. namespace nlohmann
  5170. {
  5171. /*!
  5172. @brief SAX interface
  5173. This class describes the SAX interface used by @ref nlohmann::json::sax_parse.
  5174. Each function is called in different situations while the input is parsed. The
  5175. boolean return value informs the parser whether to continue processing the
  5176. input.
  5177. */
  5178. template<typename BasicJsonType>
  5179. struct json_sax
  5180. {
  5181. using number_integer_t = typename BasicJsonType::number_integer_t;
  5182. using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
  5183. using number_float_t = typename BasicJsonType::number_float_t;
  5184. using string_t = typename BasicJsonType::string_t;
  5185. using binary_t = typename BasicJsonType::binary_t;
  5186. /*!
  5187. @brief a null value was read
  5188. @return whether parsing should proceed
  5189. */
  5190. virtual bool null() = 0;
  5191. /*!
  5192. @brief a boolean value was read
  5193. @param[in] val boolean value
  5194. @return whether parsing should proceed
  5195. */
  5196. virtual bool boolean(bool val) = 0;
  5197. /*!
  5198. @brief an integer number was read
  5199. @param[in] val integer value
  5200. @return whether parsing should proceed
  5201. */
  5202. virtual bool number_integer(number_integer_t val) = 0;
  5203. /*!
  5204. @brief an unsigned integer number was read
  5205. @param[in] val unsigned integer value
  5206. @return whether parsing should proceed
  5207. */
  5208. virtual bool number_unsigned(number_unsigned_t val) = 0;
  5209. /*!
  5210. @brief an floating-point number was read
  5211. @param[in] val floating-point value
  5212. @param[in] s raw token value
  5213. @return whether parsing should proceed
  5214. */
  5215. virtual bool number_float(number_float_t val, const string_t& s) = 0;
  5216. /*!
  5217. @brief a string was read
  5218. @param[in] val string value
  5219. @return whether parsing should proceed
  5220. @note It is safe to move the passed string.
  5221. */
  5222. virtual bool string(string_t& val) = 0;
  5223. /*!
  5224. @brief a binary string was read
  5225. @param[in] val binary value
  5226. @return whether parsing should proceed
  5227. @note It is safe to move the passed binary.
  5228. */
  5229. virtual bool binary(binary_t& val) = 0;
  5230. /*!
  5231. @brief the beginning of an object was read
  5232. @param[in] elements number of object elements or -1 if unknown
  5233. @return whether parsing should proceed
  5234. @note binary formats may report the number of elements
  5235. */
  5236. virtual bool start_object(std::size_t elements) = 0;
  5237. /*!
  5238. @brief an object key was read
  5239. @param[in] val object key
  5240. @return whether parsing should proceed
  5241. @note It is safe to move the passed string.
  5242. */
  5243. virtual bool key(string_t& val) = 0;
  5244. /*!
  5245. @brief the end of an object was read
  5246. @return whether parsing should proceed
  5247. */
  5248. virtual bool end_object() = 0;
  5249. /*!
  5250. @brief the beginning of an array was read
  5251. @param[in] elements number of array elements or -1 if unknown
  5252. @return whether parsing should proceed
  5253. @note binary formats may report the number of elements
  5254. */
  5255. virtual bool start_array(std::size_t elements) = 0;
  5256. /*!
  5257. @brief the end of an array was read
  5258. @return whether parsing should proceed
  5259. */
  5260. virtual bool end_array() = 0;
  5261. /*!
  5262. @brief a parse error occurred
  5263. @param[in] position the position in the input where the error occurs
  5264. @param[in] last_token the last read token
  5265. @param[in] ex an exception object describing the error
  5266. @return whether parsing should proceed (must return false)
  5267. */
  5268. virtual bool parse_error(std::size_t position,
  5269. const std::string& last_token,
  5270. const detail::exception& ex) = 0;
  5271. json_sax() = default;
  5272. json_sax(const json_sax&) = default;
  5273. json_sax(json_sax&&) noexcept = default;
  5274. json_sax& operator=(const json_sax&) = default;
  5275. json_sax& operator=(json_sax&&) noexcept = default;
  5276. virtual ~json_sax() = default;
  5277. };
  5278. namespace detail
  5279. {
  5280. /*!
  5281. @brief SAX implementation to create a JSON value from SAX events
  5282. This class implements the @ref json_sax interface and processes the SAX events
  5283. to create a JSON value which makes it basically a DOM parser. The structure or
  5284. hierarchy of the JSON value is managed by the stack `ref_stack` which contains
  5285. a pointer to the respective array or object for each recursion depth.
  5286. After successful parsing, the value that is passed by reference to the
  5287. constructor contains the parsed value.
  5288. @tparam BasicJsonType the JSON type
  5289. */
  5290. template<typename BasicJsonType>
  5291. class json_sax_dom_parser
  5292. {
  5293. public:
  5294. using number_integer_t = typename BasicJsonType::number_integer_t;
  5295. using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
  5296. using number_float_t = typename BasicJsonType::number_float_t;
  5297. using string_t = typename BasicJsonType::string_t;
  5298. using binary_t = typename BasicJsonType::binary_t;
  5299. /*!
  5300. @param[in,out] r reference to a JSON value that is manipulated while
  5301. parsing
  5302. @param[in] allow_exceptions_ whether parse errors yield exceptions
  5303. */
  5304. explicit json_sax_dom_parser(BasicJsonType& r, const bool allow_exceptions_ = true)
  5305. : root(r), allow_exceptions(allow_exceptions_)
  5306. {}
  5307. // make class move-only
  5308. json_sax_dom_parser(const json_sax_dom_parser&) = delete;
  5309. json_sax_dom_parser(json_sax_dom_parser&&) = default; // NOLINT(hicpp-noexcept-move,performance-noexcept-move-constructor)
  5310. json_sax_dom_parser& operator=(const json_sax_dom_parser&) = delete;
  5311. json_sax_dom_parser& operator=(json_sax_dom_parser&&) = default; // NOLINT(hicpp-noexcept-move,performance-noexcept-move-constructor)
  5312. ~json_sax_dom_parser() = default;
  5313. bool null()
  5314. {
  5315. handle_value(nullptr);
  5316. return true;
  5317. }
  5318. bool boolean(bool val)
  5319. {
  5320. handle_value(val);
  5321. return true;
  5322. }
  5323. bool number_integer(number_integer_t val)
  5324. {
  5325. handle_value(val);
  5326. return true;
  5327. }
  5328. bool number_unsigned(number_unsigned_t val)
  5329. {
  5330. handle_value(val);
  5331. return true;
  5332. }
  5333. bool number_float(number_float_t val, const string_t& /*unused*/)
  5334. {
  5335. handle_value(val);
  5336. return true;
  5337. }
  5338. bool string(string_t& val)
  5339. {
  5340. handle_value(val);
  5341. return true;
  5342. }
  5343. bool binary(binary_t& val)
  5344. {
  5345. handle_value(std::move(val));
  5346. return true;
  5347. }
  5348. bool start_object(std::size_t len)
  5349. {
  5350. ref_stack.push_back(handle_value(BasicJsonType::value_t::object));
  5351. if (JSON_HEDLEY_UNLIKELY(len != std::size_t(-1) && len > ref_stack.back()->max_size()))
  5352. {
  5353. JSON_THROW(out_of_range::create(408, "excessive object size: " + std::to_string(len), *ref_stack.back()));
  5354. }
  5355. return true;
  5356. }
  5357. bool key(string_t& val)
  5358. {
  5359. // add null at given key and store the reference for later
  5360. object_element = &(ref_stack.back()->m_value.object->operator[](val));
  5361. return true;
  5362. }
  5363. bool end_object()
  5364. {
  5365. ref_stack.back()->set_parents();
  5366. ref_stack.pop_back();
  5367. return true;
  5368. }
  5369. bool start_array(std::size_t len)
  5370. {
  5371. ref_stack.push_back(handle_value(BasicJsonType::value_t::array));
  5372. if (JSON_HEDLEY_UNLIKELY(len != std::size_t(-1) && len > ref_stack.back()->max_size()))
  5373. {
  5374. JSON_THROW(out_of_range::create(408, "excessive array size: " + std::to_string(len), *ref_stack.back()));
  5375. }
  5376. return true;
  5377. }
  5378. bool end_array()
  5379. {
  5380. ref_stack.back()->set_parents();
  5381. ref_stack.pop_back();
  5382. return true;
  5383. }
  5384. template<class Exception>
  5385. bool parse_error(std::size_t /*unused*/, const std::string& /*unused*/,
  5386. const Exception& ex)
  5387. {
  5388. errored = true;
  5389. static_cast<void>(ex);
  5390. if (allow_exceptions)
  5391. {
  5392. JSON_THROW(ex);
  5393. }
  5394. return false;
  5395. }
  5396. constexpr bool is_errored() const
  5397. {
  5398. return errored;
  5399. }
  5400. private:
  5401. /*!
  5402. @invariant If the ref stack is empty, then the passed value will be the new
  5403. root.
  5404. @invariant If the ref stack contains a value, then it is an array or an
  5405. object to which we can add elements
  5406. */
  5407. template<typename Value>
  5408. JSON_HEDLEY_RETURNS_NON_NULL
  5409. BasicJsonType* handle_value(Value&& v)
  5410. {
  5411. if (ref_stack.empty())
  5412. {
  5413. root = BasicJsonType(std::forward<Value>(v));
  5414. return &root;
  5415. }
  5416. JSON_ASSERT(ref_stack.back()->is_array() || ref_stack.back()->is_object());
  5417. if (ref_stack.back()->is_array())
  5418. {
  5419. ref_stack.back()->m_value.array->emplace_back(std::forward<Value>(v));
  5420. return &(ref_stack.back()->m_value.array->back());
  5421. }
  5422. JSON_ASSERT(ref_stack.back()->is_object());
  5423. JSON_ASSERT(object_element);
  5424. *object_element = BasicJsonType(std::forward<Value>(v));
  5425. return object_element;
  5426. }
  5427. /// the parsed JSON value
  5428. BasicJsonType& root;
  5429. /// stack to model hierarchy of values
  5430. std::vector<BasicJsonType*> ref_stack {};
  5431. /// helper to hold the reference for the next object element
  5432. BasicJsonType* object_element = nullptr;
  5433. /// whether a syntax error occurred
  5434. bool errored = false;
  5435. /// whether to throw exceptions in case of errors
  5436. const bool allow_exceptions = true;
  5437. };
  5438. template<typename BasicJsonType>
  5439. class json_sax_dom_callback_parser
  5440. {
  5441. public:
  5442. using number_integer_t = typename BasicJsonType::number_integer_t;
  5443. using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
  5444. using number_float_t = typename BasicJsonType::number_float_t;
  5445. using string_t = typename BasicJsonType::string_t;
  5446. using binary_t = typename BasicJsonType::binary_t;
  5447. using parser_callback_t = typename BasicJsonType::parser_callback_t;
  5448. using parse_event_t = typename BasicJsonType::parse_event_t;
  5449. json_sax_dom_callback_parser(BasicJsonType& r,
  5450. const parser_callback_t cb,
  5451. const bool allow_exceptions_ = true)
  5452. : root(r), callback(cb), allow_exceptions(allow_exceptions_)
  5453. {
  5454. keep_stack.push_back(true);
  5455. }
  5456. // make class move-only
  5457. json_sax_dom_callback_parser(const json_sax_dom_callback_parser&) = delete;
  5458. json_sax_dom_callback_parser(json_sax_dom_callback_parser&&) = default; // NOLINT(hicpp-noexcept-move,performance-noexcept-move-constructor)
  5459. json_sax_dom_callback_parser& operator=(const json_sax_dom_callback_parser&) = delete;
  5460. json_sax_dom_callback_parser& operator=(json_sax_dom_callback_parser&&) = default; // NOLINT(hicpp-noexcept-move,performance-noexcept-move-constructor)
  5461. ~json_sax_dom_callback_parser() = default;
  5462. bool null()
  5463. {
  5464. handle_value(nullptr);
  5465. return true;
  5466. }
  5467. bool boolean(bool val)
  5468. {
  5469. handle_value(val);
  5470. return true;
  5471. }
  5472. bool number_integer(number_integer_t val)
  5473. {
  5474. handle_value(val);
  5475. return true;
  5476. }
  5477. bool number_unsigned(number_unsigned_t val)
  5478. {
  5479. handle_value(val);
  5480. return true;
  5481. }
  5482. bool number_float(number_float_t val, const string_t& /*unused*/)
  5483. {
  5484. handle_value(val);
  5485. return true;
  5486. }
  5487. bool string(string_t& val)
  5488. {
  5489. handle_value(val);
  5490. return true;
  5491. }
  5492. bool binary(binary_t& val)
  5493. {
  5494. handle_value(std::move(val));
  5495. return true;
  5496. }
  5497. bool start_object(std::size_t len)
  5498. {
  5499. // check callback for object start
  5500. const bool keep = callback(static_cast<int>(ref_stack.size()), parse_event_t::object_start, discarded);
  5501. keep_stack.push_back(keep);
  5502. auto val = handle_value(BasicJsonType::value_t::object, true);
  5503. ref_stack.push_back(val.second);
  5504. // check object limit
  5505. if (ref_stack.back() && JSON_HEDLEY_UNLIKELY(len != std::size_t(-1) && len > ref_stack.back()->max_size()))
  5506. {
  5507. JSON_THROW(out_of_range::create(408, "excessive object size: " + std::to_string(len), *ref_stack.back()));
  5508. }
  5509. return true;
  5510. }
  5511. bool key(string_t& val)
  5512. {
  5513. BasicJsonType k = BasicJsonType(val);
  5514. // check callback for key
  5515. const bool keep = callback(static_cast<int>(ref_stack.size()), parse_event_t::key, k);
  5516. key_keep_stack.push_back(keep);
  5517. // add discarded value at given key and store the reference for later
  5518. if (keep && ref_stack.back())
  5519. {
  5520. object_element = &(ref_stack.back()->m_value.object->operator[](val) = discarded);
  5521. }
  5522. return true;
  5523. }
  5524. bool end_object()
  5525. {
  5526. if (ref_stack.back())
  5527. {
  5528. if (!callback(static_cast<int>(ref_stack.size()) - 1, parse_event_t::object_end, *ref_stack.back()))
  5529. {
  5530. // discard object
  5531. *ref_stack.back() = discarded;
  5532. }
  5533. else
  5534. {
  5535. ref_stack.back()->set_parents();
  5536. }
  5537. }
  5538. JSON_ASSERT(!ref_stack.empty());
  5539. JSON_ASSERT(!keep_stack.empty());
  5540. ref_stack.pop_back();
  5541. keep_stack.pop_back();
  5542. if (!ref_stack.empty() && ref_stack.back() && ref_stack.back()->is_structured())
  5543. {
  5544. // remove discarded value
  5545. for (auto it = ref_stack.back()->begin(); it != ref_stack.back()->end(); ++it)
  5546. {
  5547. if (it->is_discarded())
  5548. {
  5549. ref_stack.back()->erase(it);
  5550. break;
  5551. }
  5552. }
  5553. }
  5554. return true;
  5555. }
  5556. bool start_array(std::size_t len)
  5557. {
  5558. const bool keep = callback(static_cast<int>(ref_stack.size()), parse_event_t::array_start, discarded);
  5559. keep_stack.push_back(keep);
  5560. auto val = handle_value(BasicJsonType::value_t::array, true);
  5561. ref_stack.push_back(val.second);
  5562. // check array limit
  5563. if (ref_stack.back() && JSON_HEDLEY_UNLIKELY(len != std::size_t(-1) && len > ref_stack.back()->max_size()))
  5564. {
  5565. JSON_THROW(out_of_range::create(408, "excessive array size: " + std::to_string(len), *ref_stack.back()));
  5566. }
  5567. return true;
  5568. }
  5569. bool end_array()
  5570. {
  5571. bool keep = true;
  5572. if (ref_stack.back())
  5573. {
  5574. keep = callback(static_cast<int>(ref_stack.size()) - 1, parse_event_t::array_end, *ref_stack.back());
  5575. if (keep)
  5576. {
  5577. ref_stack.back()->set_parents();
  5578. }
  5579. else
  5580. {
  5581. // discard array
  5582. *ref_stack.back() = discarded;
  5583. }
  5584. }
  5585. JSON_ASSERT(!ref_stack.empty());
  5586. JSON_ASSERT(!keep_stack.empty());
  5587. ref_stack.pop_back();
  5588. keep_stack.pop_back();
  5589. // remove discarded value
  5590. if (!keep && !ref_stack.empty() && ref_stack.back()->is_array())
  5591. {
  5592. ref_stack.back()->m_value.array->pop_back();
  5593. }
  5594. return true;
  5595. }
  5596. template<class Exception>
  5597. bool parse_error(std::size_t /*unused*/, const std::string& /*unused*/,
  5598. const Exception& ex)
  5599. {
  5600. errored = true;
  5601. static_cast<void>(ex);
  5602. if (allow_exceptions)
  5603. {
  5604. JSON_THROW(ex);
  5605. }
  5606. return false;
  5607. }
  5608. constexpr bool is_errored() const
  5609. {
  5610. return errored;
  5611. }
  5612. private:
  5613. /*!
  5614. @param[in] v value to add to the JSON value we build during parsing
  5615. @param[in] skip_callback whether we should skip calling the callback
  5616. function; this is required after start_array() and
  5617. start_object() SAX events, because otherwise we would call the
  5618. callback function with an empty array or object, respectively.
  5619. @invariant If the ref stack is empty, then the passed value will be the new
  5620. root.
  5621. @invariant If the ref stack contains a value, then it is an array or an
  5622. object to which we can add elements
  5623. @return pair of boolean (whether value should be kept) and pointer (to the
  5624. passed value in the ref_stack hierarchy; nullptr if not kept)
  5625. */
  5626. template<typename Value>
  5627. std::pair<bool, BasicJsonType*> handle_value(Value&& v, const bool skip_callback = false)
  5628. {
  5629. JSON_ASSERT(!keep_stack.empty());
  5630. // do not handle this value if we know it would be added to a discarded
  5631. // container
  5632. if (!keep_stack.back())
  5633. {
  5634. return {false, nullptr};
  5635. }
  5636. // create value
  5637. auto value = BasicJsonType(std::forward<Value>(v));
  5638. // check callback
  5639. const bool keep = skip_callback || callback(static_cast<int>(ref_stack.size()), parse_event_t::value, value);
  5640. // do not handle this value if we just learnt it shall be discarded
  5641. if (!keep)
  5642. {
  5643. return {false, nullptr};
  5644. }
  5645. if (ref_stack.empty())
  5646. {
  5647. root = std::move(value);
  5648. return {true, &root};
  5649. }
  5650. // skip this value if we already decided to skip the parent
  5651. // (https://github.com/nlohmann/json/issues/971#issuecomment-413678360)
  5652. if (!ref_stack.back())
  5653. {
  5654. return {false, nullptr};
  5655. }
  5656. // we now only expect arrays and objects
  5657. JSON_ASSERT(ref_stack.back()->is_array() || ref_stack.back()->is_object());
  5658. // array
  5659. if (ref_stack.back()->is_array())
  5660. {
  5661. ref_stack.back()->m_value.array->emplace_back(std::move(value));
  5662. return {true, &(ref_stack.back()->m_value.array->back())};
  5663. }
  5664. // object
  5665. JSON_ASSERT(ref_stack.back()->is_object());
  5666. // check if we should store an element for the current key
  5667. JSON_ASSERT(!key_keep_stack.empty());
  5668. const bool store_element = key_keep_stack.back();
  5669. key_keep_stack.pop_back();
  5670. if (!store_element)
  5671. {
  5672. return {false, nullptr};
  5673. }
  5674. JSON_ASSERT(object_element);
  5675. *object_element = std::move(value);
  5676. return {true, object_element};
  5677. }
  5678. /// the parsed JSON value
  5679. BasicJsonType& root;
  5680. /// stack to model hierarchy of values
  5681. std::vector<BasicJsonType*> ref_stack {};
  5682. /// stack to manage which values to keep
  5683. std::vector<bool> keep_stack {};
  5684. /// stack to manage which object keys to keep
  5685. std::vector<bool> key_keep_stack {};
  5686. /// helper to hold the reference for the next object element
  5687. BasicJsonType* object_element = nullptr;
  5688. /// whether a syntax error occurred
  5689. bool errored = false;
  5690. /// callback function
  5691. const parser_callback_t callback = nullptr;
  5692. /// whether to throw exceptions in case of errors
  5693. const bool allow_exceptions = true;
  5694. /// a discarded value for the callback
  5695. BasicJsonType discarded = BasicJsonType::value_t::discarded;
  5696. };
  5697. template<typename BasicJsonType>
  5698. class json_sax_acceptor
  5699. {
  5700. public:
  5701. using number_integer_t = typename BasicJsonType::number_integer_t;
  5702. using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
  5703. using number_float_t = typename BasicJsonType::number_float_t;
  5704. using string_t = typename BasicJsonType::string_t;
  5705. using binary_t = typename BasicJsonType::binary_t;
  5706. bool null()
  5707. {
  5708. return true;
  5709. }
  5710. bool boolean(bool /*unused*/)
  5711. {
  5712. return true;
  5713. }
  5714. bool number_integer(number_integer_t /*unused*/)
  5715. {
  5716. return true;
  5717. }
  5718. bool number_unsigned(number_unsigned_t /*unused*/)
  5719. {
  5720. return true;
  5721. }
  5722. bool number_float(number_float_t /*unused*/, const string_t& /*unused*/)
  5723. {
  5724. return true;
  5725. }
  5726. bool string(string_t& /*unused*/)
  5727. {
  5728. return true;
  5729. }
  5730. bool binary(binary_t& /*unused*/)
  5731. {
  5732. return true;
  5733. }
  5734. bool start_object(std::size_t /*unused*/ = std::size_t(-1))
  5735. {
  5736. return true;
  5737. }
  5738. bool key(string_t& /*unused*/)
  5739. {
  5740. return true;
  5741. }
  5742. bool end_object()
  5743. {
  5744. return true;
  5745. }
  5746. bool start_array(std::size_t /*unused*/ = std::size_t(-1))
  5747. {
  5748. return true;
  5749. }
  5750. bool end_array()
  5751. {
  5752. return true;
  5753. }
  5754. bool parse_error(std::size_t /*unused*/, const std::string& /*unused*/, const detail::exception& /*unused*/)
  5755. {
  5756. return false;
  5757. }
  5758. };
  5759. } // namespace detail
  5760. } // namespace nlohmann
  5761. // #include <nlohmann/detail/input/lexer.hpp>
  5762. #include <array> // array
  5763. #include <clocale> // localeconv
  5764. #include <cstddef> // size_t
  5765. #include <cstdio> // snprintf
  5766. #include <cstdlib> // strtof, strtod, strtold, strtoll, strtoull
  5767. #include <initializer_list> // initializer_list
  5768. #include <string> // char_traits, string
  5769. #include <utility> // move
  5770. #include <vector> // vector
  5771. // #include <nlohmann/detail/input/input_adapters.hpp>
  5772. // #include <nlohmann/detail/input/position_t.hpp>
  5773. // #include <nlohmann/detail/macro_scope.hpp>
  5774. namespace nlohmann
  5775. {
  5776. namespace detail
  5777. {
  5778. ///////////
  5779. // lexer //
  5780. ///////////
  5781. template<typename BasicJsonType>
  5782. class lexer_base
  5783. {
  5784. public:
  5785. /// token types for the parser
  5786. enum class token_type
  5787. {
  5788. uninitialized, ///< indicating the scanner is uninitialized
  5789. literal_true, ///< the `true` literal
  5790. literal_false, ///< the `false` literal
  5791. literal_null, ///< the `null` literal
  5792. value_string, ///< a string -- use get_string() for actual value
  5793. value_unsigned, ///< an unsigned integer -- use get_number_unsigned() for actual value
  5794. value_integer, ///< a signed integer -- use get_number_integer() for actual value
  5795. value_float, ///< an floating point number -- use get_number_float() for actual value
  5796. begin_array, ///< the character for array begin `[`
  5797. begin_object, ///< the character for object begin `{`
  5798. end_array, ///< the character for array end `]`
  5799. end_object, ///< the character for object end `}`
  5800. name_separator, ///< the name separator `:`
  5801. value_separator, ///< the value separator `,`
  5802. parse_error, ///< indicating a parse error
  5803. end_of_input, ///< indicating the end of the input buffer
  5804. literal_or_value ///< a literal or the begin of a value (only for diagnostics)
  5805. };
  5806. /// return name of values of type token_type (only used for errors)
  5807. JSON_HEDLEY_RETURNS_NON_NULL
  5808. JSON_HEDLEY_CONST
  5809. static const char* token_type_name(const token_type t) noexcept
  5810. {
  5811. switch (t)
  5812. {
  5813. case token_type::uninitialized:
  5814. return "<uninitialized>";
  5815. case token_type::literal_true:
  5816. return "true literal";
  5817. case token_type::literal_false:
  5818. return "false literal";
  5819. case token_type::literal_null:
  5820. return "null literal";
  5821. case token_type::value_string:
  5822. return "string literal";
  5823. case token_type::value_unsigned:
  5824. case token_type::value_integer:
  5825. case token_type::value_float:
  5826. return "number literal";
  5827. case token_type::begin_array:
  5828. return "'['";
  5829. case token_type::begin_object:
  5830. return "'{'";
  5831. case token_type::end_array:
  5832. return "']'";
  5833. case token_type::end_object:
  5834. return "'}'";
  5835. case token_type::name_separator:
  5836. return "':'";
  5837. case token_type::value_separator:
  5838. return "','";
  5839. case token_type::parse_error:
  5840. return "<parse error>";
  5841. case token_type::end_of_input:
  5842. return "end of input";
  5843. case token_type::literal_or_value:
  5844. return "'[', '{', or a literal";
  5845. // LCOV_EXCL_START
  5846. default: // catch non-enum values
  5847. return "unknown token";
  5848. // LCOV_EXCL_STOP
  5849. }
  5850. }
  5851. };
  5852. /*!
  5853. @brief lexical analysis
  5854. This class organizes the lexical analysis during JSON deserialization.
  5855. */
  5856. template<typename BasicJsonType, typename InputAdapterType>
  5857. class lexer : public lexer_base<BasicJsonType>
  5858. {
  5859. using number_integer_t = typename BasicJsonType::number_integer_t;
  5860. using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
  5861. using number_float_t = typename BasicJsonType::number_float_t;
  5862. using string_t = typename BasicJsonType::string_t;
  5863. using char_type = typename InputAdapterType::char_type;
  5864. using char_int_type = typename std::char_traits<char_type>::int_type;
  5865. public:
  5866. using token_type = typename lexer_base<BasicJsonType>::token_type;
  5867. explicit lexer(InputAdapterType&& adapter, bool ignore_comments_ = false) noexcept
  5868. : ia(std::move(adapter))
  5869. , ignore_comments(ignore_comments_)
  5870. , decimal_point_char(static_cast<char_int_type>(get_decimal_point()))
  5871. {}
  5872. // delete because of pointer members
  5873. lexer(const lexer&) = delete;
  5874. lexer(lexer&&) = default; // NOLINT(hicpp-noexcept-move,performance-noexcept-move-constructor)
  5875. lexer& operator=(lexer&) = delete;
  5876. lexer& operator=(lexer&&) = default; // NOLINT(hicpp-noexcept-move,performance-noexcept-move-constructor)
  5877. ~lexer() = default;
  5878. private:
  5879. /////////////////////
  5880. // locales
  5881. /////////////////////
  5882. /// return the locale-dependent decimal point
  5883. JSON_HEDLEY_PURE
  5884. static char get_decimal_point() noexcept
  5885. {
  5886. const auto* loc = localeconv();
  5887. JSON_ASSERT(loc != nullptr);
  5888. return (loc->decimal_point == nullptr) ? '.' : *(loc->decimal_point);
  5889. }
  5890. /////////////////////
  5891. // scan functions
  5892. /////////////////////
  5893. /*!
  5894. @brief get codepoint from 4 hex characters following `\u`
  5895. For input "\u c1 c2 c3 c4" the codepoint is:
  5896. (c1 * 0x1000) + (c2 * 0x0100) + (c3 * 0x0010) + c4
  5897. = (c1 << 12) + (c2 << 8) + (c3 << 4) + (c4 << 0)
  5898. Furthermore, the possible characters '0'..'9', 'A'..'F', and 'a'..'f'
  5899. must be converted to the integers 0x0..0x9, 0xA..0xF, 0xA..0xF, resp. The
  5900. conversion is done by subtracting the offset (0x30, 0x37, and 0x57)
  5901. between the ASCII value of the character and the desired integer value.
  5902. @return codepoint (0x0000..0xFFFF) or -1 in case of an error (e.g. EOF or
  5903. non-hex character)
  5904. */
  5905. int get_codepoint()
  5906. {
  5907. // this function only makes sense after reading `\u`
  5908. JSON_ASSERT(current == 'u');
  5909. int codepoint = 0;
  5910. const auto factors = { 12u, 8u, 4u, 0u };
  5911. for (const auto factor : factors)
  5912. {
  5913. get();
  5914. if (current >= '0' && current <= '9')
  5915. {
  5916. codepoint += static_cast<int>((static_cast<unsigned int>(current) - 0x30u) << factor);
  5917. }
  5918. else if (current >= 'A' && current <= 'F')
  5919. {
  5920. codepoint += static_cast<int>((static_cast<unsigned int>(current) - 0x37u) << factor);
  5921. }
  5922. else if (current >= 'a' && current <= 'f')
  5923. {
  5924. codepoint += static_cast<int>((static_cast<unsigned int>(current) - 0x57u) << factor);
  5925. }
  5926. else
  5927. {
  5928. return -1;
  5929. }
  5930. }
  5931. JSON_ASSERT(0x0000 <= codepoint && codepoint <= 0xFFFF);
  5932. return codepoint;
  5933. }
  5934. /*!
  5935. @brief check if the next byte(s) are inside a given range
  5936. Adds the current byte and, for each passed range, reads a new byte and
  5937. checks if it is inside the range. If a violation was detected, set up an
  5938. error message and return false. Otherwise, return true.
  5939. @param[in] ranges list of integers; interpreted as list of pairs of
  5940. inclusive lower and upper bound, respectively
  5941. @pre The passed list @a ranges must have 2, 4, or 6 elements; that is,
  5942. 1, 2, or 3 pairs. This precondition is enforced by an assertion.
  5943. @return true if and only if no range violation was detected
  5944. */
  5945. bool next_byte_in_range(std::initializer_list<char_int_type> ranges)
  5946. {
  5947. JSON_ASSERT(ranges.size() == 2 || ranges.size() == 4 || ranges.size() == 6);
  5948. add(current);
  5949. for (auto range = ranges.begin(); range != ranges.end(); ++range)
  5950. {
  5951. get();
  5952. if (JSON_HEDLEY_LIKELY(*range <= current && current <= *(++range)))
  5953. {
  5954. add(current);
  5955. }
  5956. else
  5957. {
  5958. error_message = "invalid string: ill-formed UTF-8 byte";
  5959. return false;
  5960. }
  5961. }
  5962. return true;
  5963. }
  5964. /*!
  5965. @brief scan a string literal
  5966. This function scans a string according to Sect. 7 of RFC 8259. While
  5967. scanning, bytes are escaped and copied into buffer token_buffer. Then the
  5968. function returns successfully, token_buffer is *not* null-terminated (as it
  5969. may contain \0 bytes), and token_buffer.size() is the number of bytes in the
  5970. string.
  5971. @return token_type::value_string if string could be successfully scanned,
  5972. token_type::parse_error otherwise
  5973. @note In case of errors, variable error_message contains a textual
  5974. description.
  5975. */
  5976. token_type scan_string()
  5977. {
  5978. // reset token_buffer (ignore opening quote)
  5979. reset();
  5980. // we entered the function by reading an open quote
  5981. JSON_ASSERT(current == '\"');
  5982. while (true)
  5983. {
  5984. // get next character
  5985. switch (get())
  5986. {
  5987. // end of file while parsing string
  5988. case std::char_traits<char_type>::eof():
  5989. {
  5990. error_message = "invalid string: missing closing quote";
  5991. return token_type::parse_error;
  5992. }
  5993. // closing quote
  5994. case '\"':
  5995. {
  5996. return token_type::value_string;
  5997. }
  5998. // escapes
  5999. case '\\':
  6000. {
  6001. switch (get())
  6002. {
  6003. // quotation mark
  6004. case '\"':
  6005. add('\"');
  6006. break;
  6007. // reverse solidus
  6008. case '\\':
  6009. add('\\');
  6010. break;
  6011. // solidus
  6012. case '/':
  6013. add('/');
  6014. break;
  6015. // backspace
  6016. case 'b':
  6017. add('\b');
  6018. break;
  6019. // form feed
  6020. case 'f':
  6021. add('\f');
  6022. break;
  6023. // line feed
  6024. case 'n':
  6025. add('\n');
  6026. break;
  6027. // carriage return
  6028. case 'r':
  6029. add('\r');
  6030. break;
  6031. // tab
  6032. case 't':
  6033. add('\t');
  6034. break;
  6035. // unicode escapes
  6036. case 'u':
  6037. {
  6038. const int codepoint1 = get_codepoint();
  6039. int codepoint = codepoint1; // start with codepoint1
  6040. if (JSON_HEDLEY_UNLIKELY(codepoint1 == -1))
  6041. {
  6042. error_message = "invalid string: '\\u' must be followed by 4 hex digits";
  6043. return token_type::parse_error;
  6044. }
  6045. // check if code point is a high surrogate
  6046. if (0xD800 <= codepoint1 && codepoint1 <= 0xDBFF)
  6047. {
  6048. // expect next \uxxxx entry
  6049. if (JSON_HEDLEY_LIKELY(get() == '\\' && get() == 'u'))
  6050. {
  6051. const int codepoint2 = get_codepoint();
  6052. if (JSON_HEDLEY_UNLIKELY(codepoint2 == -1))
  6053. {
  6054. error_message = "invalid string: '\\u' must be followed by 4 hex digits";
  6055. return token_type::parse_error;
  6056. }
  6057. // check if codepoint2 is a low surrogate
  6058. if (JSON_HEDLEY_LIKELY(0xDC00 <= codepoint2 && codepoint2 <= 0xDFFF))
  6059. {
  6060. // overwrite codepoint
  6061. codepoint = static_cast<int>(
  6062. // high surrogate occupies the most significant 22 bits
  6063. (static_cast<unsigned int>(codepoint1) << 10u)
  6064. // low surrogate occupies the least significant 15 bits
  6065. + static_cast<unsigned int>(codepoint2)
  6066. // there is still the 0xD800, 0xDC00 and 0x10000 noise
  6067. // in the result so we have to subtract with:
  6068. // (0xD800 << 10) + DC00 - 0x10000 = 0x35FDC00
  6069. - 0x35FDC00u);
  6070. }
  6071. else
  6072. {
  6073. error_message = "invalid string: surrogate U+D800..U+DBFF must be followed by U+DC00..U+DFFF";
  6074. return token_type::parse_error;
  6075. }
  6076. }
  6077. else
  6078. {
  6079. error_message = "invalid string: surrogate U+D800..U+DBFF must be followed by U+DC00..U+DFFF";
  6080. return token_type::parse_error;
  6081. }
  6082. }
  6083. else
  6084. {
  6085. if (JSON_HEDLEY_UNLIKELY(0xDC00 <= codepoint1 && codepoint1 <= 0xDFFF))
  6086. {
  6087. error_message = "invalid string: surrogate U+DC00..U+DFFF must follow U+D800..U+DBFF";
  6088. return token_type::parse_error;
  6089. }
  6090. }
  6091. // result of the above calculation yields a proper codepoint
  6092. JSON_ASSERT(0x00 <= codepoint && codepoint <= 0x10FFFF);
  6093. // translate codepoint into bytes
  6094. if (codepoint < 0x80)
  6095. {
  6096. // 1-byte characters: 0xxxxxxx (ASCII)
  6097. add(static_cast<char_int_type>(codepoint));
  6098. }
  6099. else if (codepoint <= 0x7FF)
  6100. {
  6101. // 2-byte characters: 110xxxxx 10xxxxxx
  6102. add(static_cast<char_int_type>(0xC0u | (static_cast<unsigned int>(codepoint) >> 6u)));
  6103. add(static_cast<char_int_type>(0x80u | (static_cast<unsigned int>(codepoint) & 0x3Fu)));
  6104. }
  6105. else if (codepoint <= 0xFFFF)
  6106. {
  6107. // 3-byte characters: 1110xxxx 10xxxxxx 10xxxxxx
  6108. add(static_cast<char_int_type>(0xE0u | (static_cast<unsigned int>(codepoint) >> 12u)));
  6109. add(static_cast<char_int_type>(0x80u | ((static_cast<unsigned int>(codepoint) >> 6u) & 0x3Fu)));
  6110. add(static_cast<char_int_type>(0x80u | (static_cast<unsigned int>(codepoint) & 0x3Fu)));
  6111. }
  6112. else
  6113. {
  6114. // 4-byte characters: 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
  6115. add(static_cast<char_int_type>(0xF0u | (static_cast<unsigned int>(codepoint) >> 18u)));
  6116. add(static_cast<char_int_type>(0x80u | ((static_cast<unsigned int>(codepoint) >> 12u) & 0x3Fu)));
  6117. add(static_cast<char_int_type>(0x80u | ((static_cast<unsigned int>(codepoint) >> 6u) & 0x3Fu)));
  6118. add(static_cast<char_int_type>(0x80u | (static_cast<unsigned int>(codepoint) & 0x3Fu)));
  6119. }
  6120. break;
  6121. }
  6122. // other characters after escape
  6123. default:
  6124. error_message = "invalid string: forbidden character after backslash";
  6125. return token_type::parse_error;
  6126. }
  6127. break;
  6128. }
  6129. // invalid control characters
  6130. case 0x00:
  6131. {
  6132. error_message = "invalid string: control character U+0000 (NUL) must be escaped to \\u0000";
  6133. return token_type::parse_error;
  6134. }
  6135. case 0x01:
  6136. {
  6137. error_message = "invalid string: control character U+0001 (SOH) must be escaped to \\u0001";
  6138. return token_type::parse_error;
  6139. }
  6140. case 0x02:
  6141. {
  6142. error_message = "invalid string: control character U+0002 (STX) must be escaped to \\u0002";
  6143. return token_type::parse_error;
  6144. }
  6145. case 0x03:
  6146. {
  6147. error_message = "invalid string: control character U+0003 (ETX) must be escaped to \\u0003";
  6148. return token_type::parse_error;
  6149. }
  6150. case 0x04:
  6151. {
  6152. error_message = "invalid string: control character U+0004 (EOT) must be escaped to \\u0004";
  6153. return token_type::parse_error;
  6154. }
  6155. case 0x05:
  6156. {
  6157. error_message = "invalid string: control character U+0005 (ENQ) must be escaped to \\u0005";
  6158. return token_type::parse_error;
  6159. }
  6160. case 0x06:
  6161. {
  6162. error_message = "invalid string: control character U+0006 (ACK) must be escaped to \\u0006";
  6163. return token_type::parse_error;
  6164. }
  6165. case 0x07:
  6166. {
  6167. error_message = "invalid string: control character U+0007 (BEL) must be escaped to \\u0007";
  6168. return token_type::parse_error;
  6169. }
  6170. case 0x08:
  6171. {
  6172. error_message = "invalid string: control character U+0008 (BS) must be escaped to \\u0008 or \\b";
  6173. return token_type::parse_error;
  6174. }
  6175. case 0x09:
  6176. {
  6177. error_message = "invalid string: control character U+0009 (HT) must be escaped to \\u0009 or \\t";
  6178. return token_type::parse_error;
  6179. }
  6180. case 0x0A:
  6181. {
  6182. error_message = "invalid string: control character U+000A (LF) must be escaped to \\u000A or \\n";
  6183. return token_type::parse_error;
  6184. }
  6185. case 0x0B:
  6186. {
  6187. error_message = "invalid string: control character U+000B (VT) must be escaped to \\u000B";
  6188. return token_type::parse_error;
  6189. }
  6190. case 0x0C:
  6191. {
  6192. error_message = "invalid string: control character U+000C (FF) must be escaped to \\u000C or \\f";
  6193. return token_type::parse_error;
  6194. }
  6195. case 0x0D:
  6196. {
  6197. error_message = "invalid string: control character U+000D (CR) must be escaped to \\u000D or \\r";
  6198. return token_type::parse_error;
  6199. }
  6200. case 0x0E:
  6201. {
  6202. error_message = "invalid string: control character U+000E (SO) must be escaped to \\u000E";
  6203. return token_type::parse_error;
  6204. }
  6205. case 0x0F:
  6206. {
  6207. error_message = "invalid string: control character U+000F (SI) must be escaped to \\u000F";
  6208. return token_type::parse_error;
  6209. }
  6210. case 0x10:
  6211. {
  6212. error_message = "invalid string: control character U+0010 (DLE) must be escaped to \\u0010";
  6213. return token_type::parse_error;
  6214. }
  6215. case 0x11:
  6216. {
  6217. error_message = "invalid string: control character U+0011 (DC1) must be escaped to \\u0011";
  6218. return token_type::parse_error;
  6219. }
  6220. case 0x12:
  6221. {
  6222. error_message = "invalid string: control character U+0012 (DC2) must be escaped to \\u0012";
  6223. return token_type::parse_error;
  6224. }
  6225. case 0x13:
  6226. {
  6227. error_message = "invalid string: control character U+0013 (DC3) must be escaped to \\u0013";
  6228. return token_type::parse_error;
  6229. }
  6230. case 0x14:
  6231. {
  6232. error_message = "invalid string: control character U+0014 (DC4) must be escaped to \\u0014";
  6233. return token_type::parse_error;
  6234. }
  6235. case 0x15:
  6236. {
  6237. error_message = "invalid string: control character U+0015 (NAK) must be escaped to \\u0015";
  6238. return token_type::parse_error;
  6239. }
  6240. case 0x16:
  6241. {
  6242. error_message = "invalid string: control character U+0016 (SYN) must be escaped to \\u0016";
  6243. return token_type::parse_error;
  6244. }
  6245. case 0x17:
  6246. {
  6247. error_message = "invalid string: control character U+0017 (ETB) must be escaped to \\u0017";
  6248. return token_type::parse_error;
  6249. }
  6250. case 0x18:
  6251. {
  6252. error_message = "invalid string: control character U+0018 (CAN) must be escaped to \\u0018";
  6253. return token_type::parse_error;
  6254. }
  6255. case 0x19:
  6256. {
  6257. error_message = "invalid string: control character U+0019 (EM) must be escaped to \\u0019";
  6258. return token_type::parse_error;
  6259. }
  6260. case 0x1A:
  6261. {
  6262. error_message = "invalid string: control character U+001A (SUB) must be escaped to \\u001A";
  6263. return token_type::parse_error;
  6264. }
  6265. case 0x1B:
  6266. {
  6267. error_message = "invalid string: control character U+001B (ESC) must be escaped to \\u001B";
  6268. return token_type::parse_error;
  6269. }
  6270. case 0x1C:
  6271. {
  6272. error_message = "invalid string: control character U+001C (FS) must be escaped to \\u001C";
  6273. return token_type::parse_error;
  6274. }
  6275. case 0x1D:
  6276. {
  6277. error_message = "invalid string: control character U+001D (GS) must be escaped to \\u001D";
  6278. return token_type::parse_error;
  6279. }
  6280. case 0x1E:
  6281. {
  6282. error_message = "invalid string: control character U+001E (RS) must be escaped to \\u001E";
  6283. return token_type::parse_error;
  6284. }
  6285. case 0x1F:
  6286. {
  6287. error_message = "invalid string: control character U+001F (US) must be escaped to \\u001F";
  6288. return token_type::parse_error;
  6289. }
  6290. // U+0020..U+007F (except U+0022 (quote) and U+005C (backspace))
  6291. case 0x20:
  6292. case 0x21:
  6293. case 0x23:
  6294. case 0x24:
  6295. case 0x25:
  6296. case 0x26:
  6297. case 0x27:
  6298. case 0x28:
  6299. case 0x29:
  6300. case 0x2A:
  6301. case 0x2B:
  6302. case 0x2C:
  6303. case 0x2D:
  6304. case 0x2E:
  6305. case 0x2F:
  6306. case 0x30:
  6307. case 0x31:
  6308. case 0x32:
  6309. case 0x33:
  6310. case 0x34:
  6311. case 0x35:
  6312. case 0x36:
  6313. case 0x37:
  6314. case 0x38:
  6315. case 0x39:
  6316. case 0x3A:
  6317. case 0x3B:
  6318. case 0x3C:
  6319. case 0x3D:
  6320. case 0x3E:
  6321. case 0x3F:
  6322. case 0x40:
  6323. case 0x41:
  6324. case 0x42:
  6325. case 0x43:
  6326. case 0x44:
  6327. case 0x45:
  6328. case 0x46:
  6329. case 0x47:
  6330. case 0x48:
  6331. case 0x49:
  6332. case 0x4A:
  6333. case 0x4B:
  6334. case 0x4C:
  6335. case 0x4D:
  6336. case 0x4E:
  6337. case 0x4F:
  6338. case 0x50:
  6339. case 0x51:
  6340. case 0x52:
  6341. case 0x53:
  6342. case 0x54:
  6343. case 0x55:
  6344. case 0x56:
  6345. case 0x57:
  6346. case 0x58:
  6347. case 0x59:
  6348. case 0x5A:
  6349. case 0x5B:
  6350. case 0x5D:
  6351. case 0x5E:
  6352. case 0x5F:
  6353. case 0x60:
  6354. case 0x61:
  6355. case 0x62:
  6356. case 0x63:
  6357. case 0x64:
  6358. case 0x65:
  6359. case 0x66:
  6360. case 0x67:
  6361. case 0x68:
  6362. case 0x69:
  6363. case 0x6A:
  6364. case 0x6B:
  6365. case 0x6C:
  6366. case 0x6D:
  6367. case 0x6E:
  6368. case 0x6F:
  6369. case 0x70:
  6370. case 0x71:
  6371. case 0x72:
  6372. case 0x73:
  6373. case 0x74:
  6374. case 0x75:
  6375. case 0x76:
  6376. case 0x77:
  6377. case 0x78:
  6378. case 0x79:
  6379. case 0x7A:
  6380. case 0x7B:
  6381. case 0x7C:
  6382. case 0x7D:
  6383. case 0x7E:
  6384. case 0x7F:
  6385. {
  6386. add(current);
  6387. break;
  6388. }
  6389. // U+0080..U+07FF: bytes C2..DF 80..BF
  6390. case 0xC2:
  6391. case 0xC3:
  6392. case 0xC4:
  6393. case 0xC5:
  6394. case 0xC6:
  6395. case 0xC7:
  6396. case 0xC8:
  6397. case 0xC9:
  6398. case 0xCA:
  6399. case 0xCB:
  6400. case 0xCC:
  6401. case 0xCD:
  6402. case 0xCE:
  6403. case 0xCF:
  6404. case 0xD0:
  6405. case 0xD1:
  6406. case 0xD2:
  6407. case 0xD3:
  6408. case 0xD4:
  6409. case 0xD5:
  6410. case 0xD6:
  6411. case 0xD7:
  6412. case 0xD8:
  6413. case 0xD9:
  6414. case 0xDA:
  6415. case 0xDB:
  6416. case 0xDC:
  6417. case 0xDD:
  6418. case 0xDE:
  6419. case 0xDF:
  6420. {
  6421. if (JSON_HEDLEY_UNLIKELY(!next_byte_in_range({0x80, 0xBF})))
  6422. {
  6423. return token_type::parse_error;
  6424. }
  6425. break;
  6426. }
  6427. // U+0800..U+0FFF: bytes E0 A0..BF 80..BF
  6428. case 0xE0:
  6429. {
  6430. if (JSON_HEDLEY_UNLIKELY(!(next_byte_in_range({0xA0, 0xBF, 0x80, 0xBF}))))
  6431. {
  6432. return token_type::parse_error;
  6433. }
  6434. break;
  6435. }
  6436. // U+1000..U+CFFF: bytes E1..EC 80..BF 80..BF
  6437. // U+E000..U+FFFF: bytes EE..EF 80..BF 80..BF
  6438. case 0xE1:
  6439. case 0xE2:
  6440. case 0xE3:
  6441. case 0xE4:
  6442. case 0xE5:
  6443. case 0xE6:
  6444. case 0xE7:
  6445. case 0xE8:
  6446. case 0xE9:
  6447. case 0xEA:
  6448. case 0xEB:
  6449. case 0xEC:
  6450. case 0xEE:
  6451. case 0xEF:
  6452. {
  6453. if (JSON_HEDLEY_UNLIKELY(!(next_byte_in_range({0x80, 0xBF, 0x80, 0xBF}))))
  6454. {
  6455. return token_type::parse_error;
  6456. }
  6457. break;
  6458. }
  6459. // U+D000..U+D7FF: bytes ED 80..9F 80..BF
  6460. case 0xED:
  6461. {
  6462. if (JSON_HEDLEY_UNLIKELY(!(next_byte_in_range({0x80, 0x9F, 0x80, 0xBF}))))
  6463. {
  6464. return token_type::parse_error;
  6465. }
  6466. break;
  6467. }
  6468. // U+10000..U+3FFFF F0 90..BF 80..BF 80..BF
  6469. case 0xF0:
  6470. {
  6471. if (JSON_HEDLEY_UNLIKELY(!(next_byte_in_range({0x90, 0xBF, 0x80, 0xBF, 0x80, 0xBF}))))
  6472. {
  6473. return token_type::parse_error;
  6474. }
  6475. break;
  6476. }
  6477. // U+40000..U+FFFFF F1..F3 80..BF 80..BF 80..BF
  6478. case 0xF1:
  6479. case 0xF2:
  6480. case 0xF3:
  6481. {
  6482. if (JSON_HEDLEY_UNLIKELY(!(next_byte_in_range({0x80, 0xBF, 0x80, 0xBF, 0x80, 0xBF}))))
  6483. {
  6484. return token_type::parse_error;
  6485. }
  6486. break;
  6487. }
  6488. // U+100000..U+10FFFF F4 80..8F 80..BF 80..BF
  6489. case 0xF4:
  6490. {
  6491. if (JSON_HEDLEY_UNLIKELY(!(next_byte_in_range({0x80, 0x8F, 0x80, 0xBF, 0x80, 0xBF}))))
  6492. {
  6493. return token_type::parse_error;
  6494. }
  6495. break;
  6496. }
  6497. // remaining bytes (80..C1 and F5..FF) are ill-formed
  6498. default:
  6499. {
  6500. error_message = "invalid string: ill-formed UTF-8 byte";
  6501. return token_type::parse_error;
  6502. }
  6503. }
  6504. }
  6505. }
  6506. /*!
  6507. * @brief scan a comment
  6508. * @return whether comment could be scanned successfully
  6509. */
  6510. bool scan_comment()
  6511. {
  6512. switch (get())
  6513. {
  6514. // single-line comments skip input until a newline or EOF is read
  6515. case '/':
  6516. {
  6517. while (true)
  6518. {
  6519. switch (get())
  6520. {
  6521. case '\n':
  6522. case '\r':
  6523. case std::char_traits<char_type>::eof():
  6524. case '\0':
  6525. return true;
  6526. default:
  6527. break;
  6528. }
  6529. }
  6530. }
  6531. // multi-line comments skip input until */ is read
  6532. case '*':
  6533. {
  6534. while (true)
  6535. {
  6536. switch (get())
  6537. {
  6538. case std::char_traits<char_type>::eof():
  6539. case '\0':
  6540. {
  6541. error_message = "invalid comment; missing closing '*/'";
  6542. return false;
  6543. }
  6544. case '*':
  6545. {
  6546. switch (get())
  6547. {
  6548. case '/':
  6549. return true;
  6550. default:
  6551. {
  6552. unget();
  6553. continue;
  6554. }
  6555. }
  6556. }
  6557. default:
  6558. continue;
  6559. }
  6560. }
  6561. }
  6562. // unexpected character after reading '/'
  6563. default:
  6564. {
  6565. error_message = "invalid comment; expecting '/' or '*' after '/'";
  6566. return false;
  6567. }
  6568. }
  6569. }
  6570. JSON_HEDLEY_NON_NULL(2)
  6571. static void strtof(float& f, const char* str, char** endptr) noexcept
  6572. {
  6573. f = std::strtof(str, endptr);
  6574. }
  6575. JSON_HEDLEY_NON_NULL(2)
  6576. static void strtof(double& f, const char* str, char** endptr) noexcept
  6577. {
  6578. f = std::strtod(str, endptr);
  6579. }
  6580. JSON_HEDLEY_NON_NULL(2)
  6581. static void strtof(long double& f, const char* str, char** endptr) noexcept
  6582. {
  6583. f = std::strtold(str, endptr);
  6584. }
  6585. /*!
  6586. @brief scan a number literal
  6587. This function scans a string according to Sect. 6 of RFC 8259.
  6588. The function is realized with a deterministic finite state machine derived
  6589. from the grammar described in RFC 8259. Starting in state "init", the
  6590. input is read and used to determined the next state. Only state "done"
  6591. accepts the number. State "error" is a trap state to model errors. In the
  6592. table below, "anything" means any character but the ones listed before.
  6593. state | 0 | 1-9 | e E | + | - | . | anything
  6594. ---------|----------|----------|----------|---------|---------|----------|-----------
  6595. init | zero | any1 | [error] | [error] | minus | [error] | [error]
  6596. minus | zero | any1 | [error] | [error] | [error] | [error] | [error]
  6597. zero | done | done | exponent | done | done | decimal1 | done
  6598. any1 | any1 | any1 | exponent | done | done | decimal1 | done
  6599. decimal1 | decimal2 | decimal2 | [error] | [error] | [error] | [error] | [error]
  6600. decimal2 | decimal2 | decimal2 | exponent | done | done | done | done
  6601. exponent | any2 | any2 | [error] | sign | sign | [error] | [error]
  6602. sign | any2 | any2 | [error] | [error] | [error] | [error] | [error]
  6603. any2 | any2 | any2 | done | done | done | done | done
  6604. The state machine is realized with one label per state (prefixed with
  6605. "scan_number_") and `goto` statements between them. The state machine
  6606. contains cycles, but any cycle can be left when EOF is read. Therefore,
  6607. the function is guaranteed to terminate.
  6608. During scanning, the read bytes are stored in token_buffer. This string is
  6609. then converted to a signed integer, an unsigned integer, or a
  6610. floating-point number.
  6611. @return token_type::value_unsigned, token_type::value_integer, or
  6612. token_type::value_float if number could be successfully scanned,
  6613. token_type::parse_error otherwise
  6614. @note The scanner is independent of the current locale. Internally, the
  6615. locale's decimal point is used instead of `.` to work with the
  6616. locale-dependent converters.
  6617. */
  6618. token_type scan_number() // lgtm [cpp/use-of-goto]
  6619. {
  6620. // reset token_buffer to store the number's bytes
  6621. reset();
  6622. // the type of the parsed number; initially set to unsigned; will be
  6623. // changed if minus sign, decimal point or exponent is read
  6624. token_type number_type = token_type::value_unsigned;
  6625. // state (init): we just found out we need to scan a number
  6626. switch (current)
  6627. {
  6628. case '-':
  6629. {
  6630. add(current);
  6631. goto scan_number_minus;
  6632. }
  6633. case '0':
  6634. {
  6635. add(current);
  6636. goto scan_number_zero;
  6637. }
  6638. case '1':
  6639. case '2':
  6640. case '3':
  6641. case '4':
  6642. case '5':
  6643. case '6':
  6644. case '7':
  6645. case '8':
  6646. case '9':
  6647. {
  6648. add(current);
  6649. goto scan_number_any1;
  6650. }
  6651. // all other characters are rejected outside scan_number()
  6652. default: // LCOV_EXCL_LINE
  6653. JSON_ASSERT(false); // NOLINT(cert-dcl03-c,hicpp-static-assert,misc-static-assert) LCOV_EXCL_LINE
  6654. }
  6655. scan_number_minus:
  6656. // state: we just parsed a leading minus sign
  6657. number_type = token_type::value_integer;
  6658. switch (get())
  6659. {
  6660. case '0':
  6661. {
  6662. add(current);
  6663. goto scan_number_zero;
  6664. }
  6665. case '1':
  6666. case '2':
  6667. case '3':
  6668. case '4':
  6669. case '5':
  6670. case '6':
  6671. case '7':
  6672. case '8':
  6673. case '9':
  6674. {
  6675. add(current);
  6676. goto scan_number_any1;
  6677. }
  6678. default:
  6679. {
  6680. error_message = "invalid number; expected digit after '-'";
  6681. return token_type::parse_error;
  6682. }
  6683. }
  6684. scan_number_zero:
  6685. // state: we just parse a zero (maybe with a leading minus sign)
  6686. switch (get())
  6687. {
  6688. case '.':
  6689. {
  6690. add(decimal_point_char);
  6691. goto scan_number_decimal1;
  6692. }
  6693. case 'e':
  6694. case 'E':
  6695. {
  6696. add(current);
  6697. goto scan_number_exponent;
  6698. }
  6699. default:
  6700. goto scan_number_done;
  6701. }
  6702. scan_number_any1:
  6703. // state: we just parsed a number 0-9 (maybe with a leading minus sign)
  6704. switch (get())
  6705. {
  6706. case '0':
  6707. case '1':
  6708. case '2':
  6709. case '3':
  6710. case '4':
  6711. case '5':
  6712. case '6':
  6713. case '7':
  6714. case '8':
  6715. case '9':
  6716. {
  6717. add(current);
  6718. goto scan_number_any1;
  6719. }
  6720. case '.':
  6721. {
  6722. add(decimal_point_char);
  6723. goto scan_number_decimal1;
  6724. }
  6725. case 'e':
  6726. case 'E':
  6727. {
  6728. add(current);
  6729. goto scan_number_exponent;
  6730. }
  6731. default:
  6732. goto scan_number_done;
  6733. }
  6734. scan_number_decimal1:
  6735. // state: we just parsed a decimal point
  6736. number_type = token_type::value_float;
  6737. switch (get())
  6738. {
  6739. case '0':
  6740. case '1':
  6741. case '2':
  6742. case '3':
  6743. case '4':
  6744. case '5':
  6745. case '6':
  6746. case '7':
  6747. case '8':
  6748. case '9':
  6749. {
  6750. add(current);
  6751. goto scan_number_decimal2;
  6752. }
  6753. default:
  6754. {
  6755. error_message = "invalid number; expected digit after '.'";
  6756. return token_type::parse_error;
  6757. }
  6758. }
  6759. scan_number_decimal2:
  6760. // we just parsed at least one number after a decimal point
  6761. switch (get())
  6762. {
  6763. case '0':
  6764. case '1':
  6765. case '2':
  6766. case '3':
  6767. case '4':
  6768. case '5':
  6769. case '6':
  6770. case '7':
  6771. case '8':
  6772. case '9':
  6773. {
  6774. add(current);
  6775. goto scan_number_decimal2;
  6776. }
  6777. case 'e':
  6778. case 'E':
  6779. {
  6780. add(current);
  6781. goto scan_number_exponent;
  6782. }
  6783. default:
  6784. goto scan_number_done;
  6785. }
  6786. scan_number_exponent:
  6787. // we just parsed an exponent
  6788. number_type = token_type::value_float;
  6789. switch (get())
  6790. {
  6791. case '+':
  6792. case '-':
  6793. {
  6794. add(current);
  6795. goto scan_number_sign;
  6796. }
  6797. case '0':
  6798. case '1':
  6799. case '2':
  6800. case '3':
  6801. case '4':
  6802. case '5':
  6803. case '6':
  6804. case '7':
  6805. case '8':
  6806. case '9':
  6807. {
  6808. add(current);
  6809. goto scan_number_any2;
  6810. }
  6811. default:
  6812. {
  6813. error_message =
  6814. "invalid number; expected '+', '-', or digit after exponent";
  6815. return token_type::parse_error;
  6816. }
  6817. }
  6818. scan_number_sign:
  6819. // we just parsed an exponent sign
  6820. switch (get())
  6821. {
  6822. case '0':
  6823. case '1':
  6824. case '2':
  6825. case '3':
  6826. case '4':
  6827. case '5':
  6828. case '6':
  6829. case '7':
  6830. case '8':
  6831. case '9':
  6832. {
  6833. add(current);
  6834. goto scan_number_any2;
  6835. }
  6836. default:
  6837. {
  6838. error_message = "invalid number; expected digit after exponent sign";
  6839. return token_type::parse_error;
  6840. }
  6841. }
  6842. scan_number_any2:
  6843. // we just parsed a number after the exponent or exponent sign
  6844. switch (get())
  6845. {
  6846. case '0':
  6847. case '1':
  6848. case '2':
  6849. case '3':
  6850. case '4':
  6851. case '5':
  6852. case '6':
  6853. case '7':
  6854. case '8':
  6855. case '9':
  6856. {
  6857. add(current);
  6858. goto scan_number_any2;
  6859. }
  6860. default:
  6861. goto scan_number_done;
  6862. }
  6863. scan_number_done:
  6864. // unget the character after the number (we only read it to know that
  6865. // we are done scanning a number)
  6866. unget();
  6867. char* endptr = nullptr; // NOLINT(cppcoreguidelines-pro-type-vararg,hicpp-vararg)
  6868. errno = 0;
  6869. // try to parse integers first and fall back to floats
  6870. if (number_type == token_type::value_unsigned)
  6871. {
  6872. const auto x = std::strtoull(token_buffer.data(), &endptr, 10);
  6873. // we checked the number format before
  6874. JSON_ASSERT(endptr == token_buffer.data() + token_buffer.size());
  6875. if (errno == 0)
  6876. {
  6877. value_unsigned = static_cast<number_unsigned_t>(x);
  6878. if (value_unsigned == x)
  6879. {
  6880. return token_type::value_unsigned;
  6881. }
  6882. }
  6883. }
  6884. else if (number_type == token_type::value_integer)
  6885. {
  6886. const auto x = std::strtoll(token_buffer.data(), &endptr, 10);
  6887. // we checked the number format before
  6888. JSON_ASSERT(endptr == token_buffer.data() + token_buffer.size());
  6889. if (errno == 0)
  6890. {
  6891. value_integer = static_cast<number_integer_t>(x);
  6892. if (value_integer == x)
  6893. {
  6894. return token_type::value_integer;
  6895. }
  6896. }
  6897. }
  6898. // this code is reached if we parse a floating-point number or if an
  6899. // integer conversion above failed
  6900. strtof(value_float, token_buffer.data(), &endptr);
  6901. // we checked the number format before
  6902. JSON_ASSERT(endptr == token_buffer.data() + token_buffer.size());
  6903. return token_type::value_float;
  6904. }
  6905. /*!
  6906. @param[in] literal_text the literal text to expect
  6907. @param[in] length the length of the passed literal text
  6908. @param[in] return_type the token type to return on success
  6909. */
  6910. JSON_HEDLEY_NON_NULL(2)
  6911. token_type scan_literal(const char_type* literal_text, const std::size_t length,
  6912. token_type return_type)
  6913. {
  6914. JSON_ASSERT(std::char_traits<char_type>::to_char_type(current) == literal_text[0]);
  6915. for (std::size_t i = 1; i < length; ++i)
  6916. {
  6917. if (JSON_HEDLEY_UNLIKELY(std::char_traits<char_type>::to_char_type(get()) != literal_text[i]))
  6918. {
  6919. error_message = "invalid literal";
  6920. return token_type::parse_error;
  6921. }
  6922. }
  6923. return return_type;
  6924. }
  6925. /////////////////////
  6926. // input management
  6927. /////////////////////
  6928. /// reset token_buffer; current character is beginning of token
  6929. void reset() noexcept
  6930. {
  6931. token_buffer.clear();
  6932. token_string.clear();
  6933. token_string.push_back(std::char_traits<char_type>::to_char_type(current));
  6934. }
  6935. /*
  6936. @brief get next character from the input
  6937. This function provides the interface to the used input adapter. It does
  6938. not throw in case the input reached EOF, but returns a
  6939. `std::char_traits<char>::eof()` in that case. Stores the scanned characters
  6940. for use in error messages.
  6941. @return character read from the input
  6942. */
  6943. char_int_type get()
  6944. {
  6945. ++position.chars_read_total;
  6946. ++position.chars_read_current_line;
  6947. if (next_unget)
  6948. {
  6949. // just reset the next_unget variable and work with current
  6950. next_unget = false;
  6951. }
  6952. else
  6953. {
  6954. current = ia.get_character();
  6955. }
  6956. if (JSON_HEDLEY_LIKELY(current != std::char_traits<char_type>::eof()))
  6957. {
  6958. token_string.push_back(std::char_traits<char_type>::to_char_type(current));
  6959. }
  6960. if (current == '\n')
  6961. {
  6962. ++position.lines_read;
  6963. position.chars_read_current_line = 0;
  6964. }
  6965. return current;
  6966. }
  6967. /*!
  6968. @brief unget current character (read it again on next get)
  6969. We implement unget by setting variable next_unget to true. The input is not
  6970. changed - we just simulate ungetting by modifying chars_read_total,
  6971. chars_read_current_line, and token_string. The next call to get() will
  6972. behave as if the unget character is read again.
  6973. */
  6974. void unget()
  6975. {
  6976. next_unget = true;
  6977. --position.chars_read_total;
  6978. // in case we "unget" a newline, we have to also decrement the lines_read
  6979. if (position.chars_read_current_line == 0)
  6980. {
  6981. if (position.lines_read > 0)
  6982. {
  6983. --position.lines_read;
  6984. }
  6985. }
  6986. else
  6987. {
  6988. --position.chars_read_current_line;
  6989. }
  6990. if (JSON_HEDLEY_LIKELY(current != std::char_traits<char_type>::eof()))
  6991. {
  6992. JSON_ASSERT(!token_string.empty());
  6993. token_string.pop_back();
  6994. }
  6995. }
  6996. /// add a character to token_buffer
  6997. void add(char_int_type c)
  6998. {
  6999. token_buffer.push_back(static_cast<typename string_t::value_type>(c));
  7000. }
  7001. public:
  7002. /////////////////////
  7003. // value getters
  7004. /////////////////////
  7005. /// return integer value
  7006. constexpr number_integer_t get_number_integer() const noexcept
  7007. {
  7008. return value_integer;
  7009. }
  7010. /// return unsigned integer value
  7011. constexpr number_unsigned_t get_number_unsigned() const noexcept
  7012. {
  7013. return value_unsigned;
  7014. }
  7015. /// return floating-point value
  7016. constexpr number_float_t get_number_float() const noexcept
  7017. {
  7018. return value_float;
  7019. }
  7020. /// return current string value (implicitly resets the token; useful only once)
  7021. string_t& get_string()
  7022. {
  7023. return token_buffer;
  7024. }
  7025. /////////////////////
  7026. // diagnostics
  7027. /////////////////////
  7028. /// return position of last read token
  7029. constexpr position_t get_position() const noexcept
  7030. {
  7031. return position;
  7032. }
  7033. /// return the last read token (for errors only). Will never contain EOF
  7034. /// (an arbitrary value that is not a valid char value, often -1), because
  7035. /// 255 may legitimately occur. May contain NUL, which should be escaped.
  7036. std::string get_token_string() const
  7037. {
  7038. // escape control characters
  7039. std::string result;
  7040. for (const auto c : token_string)
  7041. {
  7042. if (static_cast<unsigned char>(c) <= '\x1F')
  7043. {
  7044. // escape control characters
  7045. std::array<char, 9> cs{{}};
  7046. (std::snprintf)(cs.data(), cs.size(), "<U+%.4X>", static_cast<unsigned char>(c)); // NOLINT(cppcoreguidelines-pro-type-vararg,hicpp-vararg)
  7047. result += cs.data();
  7048. }
  7049. else
  7050. {
  7051. // add character as is
  7052. result.push_back(static_cast<std::string::value_type>(c));
  7053. }
  7054. }
  7055. return result;
  7056. }
  7057. /// return syntax error message
  7058. JSON_HEDLEY_RETURNS_NON_NULL
  7059. constexpr const char* get_error_message() const noexcept
  7060. {
  7061. return error_message;
  7062. }
  7063. /////////////////////
  7064. // actual scanner
  7065. /////////////////////
  7066. /*!
  7067. @brief skip the UTF-8 byte order mark
  7068. @return true iff there is no BOM or the correct BOM has been skipped
  7069. */
  7070. bool skip_bom()
  7071. {
  7072. if (get() == 0xEF)
  7073. {
  7074. // check if we completely parse the BOM
  7075. return get() == 0xBB && get() == 0xBF;
  7076. }
  7077. // the first character is not the beginning of the BOM; unget it to
  7078. // process is later
  7079. unget();
  7080. return true;
  7081. }
  7082. void skip_whitespace()
  7083. {
  7084. do
  7085. {
  7086. get();
  7087. }
  7088. while (current == ' ' || current == '\t' || current == '\n' || current == '\r');
  7089. }
  7090. token_type scan()
  7091. {
  7092. // initially, skip the BOM
  7093. if (position.chars_read_total == 0 && !skip_bom())
  7094. {
  7095. error_message = "invalid BOM; must be 0xEF 0xBB 0xBF if given";
  7096. return token_type::parse_error;
  7097. }
  7098. // read next character and ignore whitespace
  7099. skip_whitespace();
  7100. // ignore comments
  7101. while (ignore_comments && current == '/')
  7102. {
  7103. if (!scan_comment())
  7104. {
  7105. return token_type::parse_error;
  7106. }
  7107. // skip following whitespace
  7108. skip_whitespace();
  7109. }
  7110. switch (current)
  7111. {
  7112. // structural characters
  7113. case '[':
  7114. return token_type::begin_array;
  7115. case ']':
  7116. return token_type::end_array;
  7117. case '{':
  7118. return token_type::begin_object;
  7119. case '}':
  7120. return token_type::end_object;
  7121. case ':':
  7122. return token_type::name_separator;
  7123. case ',':
  7124. return token_type::value_separator;
  7125. // literals
  7126. case 't':
  7127. {
  7128. std::array<char_type, 4> true_literal = {{char_type('t'), char_type('r'), char_type('u'), char_type('e')}};
  7129. return scan_literal(true_literal.data(), true_literal.size(), token_type::literal_true);
  7130. }
  7131. case 'f':
  7132. {
  7133. std::array<char_type, 5> false_literal = {{char_type('f'), char_type('a'), char_type('l'), char_type('s'), char_type('e')}};
  7134. return scan_literal(false_literal.data(), false_literal.size(), token_type::literal_false);
  7135. }
  7136. case 'n':
  7137. {
  7138. std::array<char_type, 4> null_literal = {{char_type('n'), char_type('u'), char_type('l'), char_type('l')}};
  7139. return scan_literal(null_literal.data(), null_literal.size(), token_type::literal_null);
  7140. }
  7141. // string
  7142. case '\"':
  7143. return scan_string();
  7144. // number
  7145. case '-':
  7146. case '0':
  7147. case '1':
  7148. case '2':
  7149. case '3':
  7150. case '4':
  7151. case '5':
  7152. case '6':
  7153. case '7':
  7154. case '8':
  7155. case '9':
  7156. return scan_number();
  7157. // end of input (the null byte is needed when parsing from
  7158. // string literals)
  7159. case '\0':
  7160. case std::char_traits<char_type>::eof():
  7161. return token_type::end_of_input;
  7162. // error
  7163. default:
  7164. error_message = "invalid literal";
  7165. return token_type::parse_error;
  7166. }
  7167. }
  7168. private:
  7169. /// input adapter
  7170. InputAdapterType ia;
  7171. /// whether comments should be ignored (true) or signaled as errors (false)
  7172. const bool ignore_comments = false;
  7173. /// the current character
  7174. char_int_type current = std::char_traits<char_type>::eof();
  7175. /// whether the next get() call should just return current
  7176. bool next_unget = false;
  7177. /// the start position of the current token
  7178. position_t position {};
  7179. /// raw input token string (for error messages)
  7180. std::vector<char_type> token_string {};
  7181. /// buffer for variable-length tokens (numbers, strings)
  7182. string_t token_buffer {};
  7183. /// a description of occurred lexer errors
  7184. const char* error_message = "";
  7185. // number values
  7186. number_integer_t value_integer = 0;
  7187. number_unsigned_t value_unsigned = 0;
  7188. number_float_t value_float = 0;
  7189. /// the decimal point
  7190. const char_int_type decimal_point_char = '.';
  7191. };
  7192. } // namespace detail
  7193. } // namespace nlohmann
  7194. // #include <nlohmann/detail/macro_scope.hpp>
  7195. // #include <nlohmann/detail/meta/is_sax.hpp>
  7196. #include <cstdint> // size_t
  7197. #include <utility> // declval
  7198. #include <string> // string
  7199. // #include <nlohmann/detail/meta/detected.hpp>
  7200. // #include <nlohmann/detail/meta/type_traits.hpp>
  7201. namespace nlohmann
  7202. {
  7203. namespace detail
  7204. {
  7205. template<typename T>
  7206. using null_function_t = decltype(std::declval<T&>().null());
  7207. template<typename T>
  7208. using boolean_function_t =
  7209. decltype(std::declval<T&>().boolean(std::declval<bool>()));
  7210. template<typename T, typename Integer>
  7211. using number_integer_function_t =
  7212. decltype(std::declval<T&>().number_integer(std::declval<Integer>()));
  7213. template<typename T, typename Unsigned>
  7214. using number_unsigned_function_t =
  7215. decltype(std::declval<T&>().number_unsigned(std::declval<Unsigned>()));
  7216. template<typename T, typename Float, typename String>
  7217. using number_float_function_t = decltype(std::declval<T&>().number_float(
  7218. std::declval<Float>(), std::declval<const String&>()));
  7219. template<typename T, typename String>
  7220. using string_function_t =
  7221. decltype(std::declval<T&>().string(std::declval<String&>()));
  7222. template<typename T, typename Binary>
  7223. using binary_function_t =
  7224. decltype(std::declval<T&>().binary(std::declval<Binary&>()));
  7225. template<typename T>
  7226. using start_object_function_t =
  7227. decltype(std::declval<T&>().start_object(std::declval<std::size_t>()));
  7228. template<typename T, typename String>
  7229. using key_function_t =
  7230. decltype(std::declval<T&>().key(std::declval<String&>()));
  7231. template<typename T>
  7232. using end_object_function_t = decltype(std::declval<T&>().end_object());
  7233. template<typename T>
  7234. using start_array_function_t =
  7235. decltype(std::declval<T&>().start_array(std::declval<std::size_t>()));
  7236. template<typename T>
  7237. using end_array_function_t = decltype(std::declval<T&>().end_array());
  7238. template<typename T, typename Exception>
  7239. using parse_error_function_t = decltype(std::declval<T&>().parse_error(
  7240. std::declval<std::size_t>(), std::declval<const std::string&>(),
  7241. std::declval<const Exception&>()));
  7242. template<typename SAX, typename BasicJsonType>
  7243. struct is_sax
  7244. {
  7245. private:
  7246. static_assert(is_basic_json<BasicJsonType>::value,
  7247. "BasicJsonType must be of type basic_json<...>");
  7248. using number_integer_t = typename BasicJsonType::number_integer_t;
  7249. using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
  7250. using number_float_t = typename BasicJsonType::number_float_t;
  7251. using string_t = typename BasicJsonType::string_t;
  7252. using binary_t = typename BasicJsonType::binary_t;
  7253. using exception_t = typename BasicJsonType::exception;
  7254. public:
  7255. static constexpr bool value =
  7256. is_detected_exact<bool, null_function_t, SAX>::value &&
  7257. is_detected_exact<bool, boolean_function_t, SAX>::value &&
  7258. is_detected_exact<bool, number_integer_function_t, SAX, number_integer_t>::value &&
  7259. is_detected_exact<bool, number_unsigned_function_t, SAX, number_unsigned_t>::value &&
  7260. is_detected_exact<bool, number_float_function_t, SAX, number_float_t, string_t>::value &&
  7261. is_detected_exact<bool, string_function_t, SAX, string_t>::value &&
  7262. is_detected_exact<bool, binary_function_t, SAX, binary_t>::value &&
  7263. is_detected_exact<bool, start_object_function_t, SAX>::value &&
  7264. is_detected_exact<bool, key_function_t, SAX, string_t>::value &&
  7265. is_detected_exact<bool, end_object_function_t, SAX>::value &&
  7266. is_detected_exact<bool, start_array_function_t, SAX>::value &&
  7267. is_detected_exact<bool, end_array_function_t, SAX>::value &&
  7268. is_detected_exact<bool, parse_error_function_t, SAX, exception_t>::value;
  7269. };
  7270. template<typename SAX, typename BasicJsonType>
  7271. struct is_sax_static_asserts
  7272. {
  7273. private:
  7274. static_assert(is_basic_json<BasicJsonType>::value,
  7275. "BasicJsonType must be of type basic_json<...>");
  7276. using number_integer_t = typename BasicJsonType::number_integer_t;
  7277. using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
  7278. using number_float_t = typename BasicJsonType::number_float_t;
  7279. using string_t = typename BasicJsonType::string_t;
  7280. using binary_t = typename BasicJsonType::binary_t;
  7281. using exception_t = typename BasicJsonType::exception;
  7282. public:
  7283. static_assert(is_detected_exact<bool, null_function_t, SAX>::value,
  7284. "Missing/invalid function: bool null()");
  7285. static_assert(is_detected_exact<bool, boolean_function_t, SAX>::value,
  7286. "Missing/invalid function: bool boolean(bool)");
  7287. static_assert(is_detected_exact<bool, boolean_function_t, SAX>::value,
  7288. "Missing/invalid function: bool boolean(bool)");
  7289. static_assert(
  7290. is_detected_exact<bool, number_integer_function_t, SAX,
  7291. number_integer_t>::value,
  7292. "Missing/invalid function: bool number_integer(number_integer_t)");
  7293. static_assert(
  7294. is_detected_exact<bool, number_unsigned_function_t, SAX,
  7295. number_unsigned_t>::value,
  7296. "Missing/invalid function: bool number_unsigned(number_unsigned_t)");
  7297. static_assert(is_detected_exact<bool, number_float_function_t, SAX,
  7298. number_float_t, string_t>::value,
  7299. "Missing/invalid function: bool number_float(number_float_t, const string_t&)");
  7300. static_assert(
  7301. is_detected_exact<bool, string_function_t, SAX, string_t>::value,
  7302. "Missing/invalid function: bool string(string_t&)");
  7303. static_assert(
  7304. is_detected_exact<bool, binary_function_t, SAX, binary_t>::value,
  7305. "Missing/invalid function: bool binary(binary_t&)");
  7306. static_assert(is_detected_exact<bool, start_object_function_t, SAX>::value,
  7307. "Missing/invalid function: bool start_object(std::size_t)");
  7308. static_assert(is_detected_exact<bool, key_function_t, SAX, string_t>::value,
  7309. "Missing/invalid function: bool key(string_t&)");
  7310. static_assert(is_detected_exact<bool, end_object_function_t, SAX>::value,
  7311. "Missing/invalid function: bool end_object()");
  7312. static_assert(is_detected_exact<bool, start_array_function_t, SAX>::value,
  7313. "Missing/invalid function: bool start_array(std::size_t)");
  7314. static_assert(is_detected_exact<bool, end_array_function_t, SAX>::value,
  7315. "Missing/invalid function: bool end_array()");
  7316. static_assert(
  7317. is_detected_exact<bool, parse_error_function_t, SAX, exception_t>::value,
  7318. "Missing/invalid function: bool parse_error(std::size_t, const "
  7319. "std::string&, const exception&)");
  7320. };
  7321. } // namespace detail
  7322. } // namespace nlohmann
  7323. // #include <nlohmann/detail/meta/type_traits.hpp>
  7324. // #include <nlohmann/detail/value_t.hpp>
  7325. namespace nlohmann
  7326. {
  7327. namespace detail
  7328. {
  7329. /// how to treat CBOR tags
  7330. enum class cbor_tag_handler_t
  7331. {
  7332. error, ///< throw a parse_error exception in case of a tag
  7333. ignore, ///< ignore tags
  7334. store ///< store tags as binary type
  7335. };
  7336. /*!
  7337. @brief determine system byte order
  7338. @return true if and only if system's byte order is little endian
  7339. @note from https://stackoverflow.com/a/1001328/266378
  7340. */
  7341. static inline bool little_endianess(int num = 1) noexcept
  7342. {
  7343. return *reinterpret_cast<char*>(&num) == 1;
  7344. }
  7345. ///////////////////
  7346. // binary reader //
  7347. ///////////////////
  7348. /*!
  7349. @brief deserialization of CBOR, MessagePack, and UBJSON values
  7350. */
  7351. template<typename BasicJsonType, typename InputAdapterType, typename SAX = json_sax_dom_parser<BasicJsonType>>
  7352. class binary_reader
  7353. {
  7354. using number_integer_t = typename BasicJsonType::number_integer_t;
  7355. using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
  7356. using number_float_t = typename BasicJsonType::number_float_t;
  7357. using string_t = typename BasicJsonType::string_t;
  7358. using binary_t = typename BasicJsonType::binary_t;
  7359. using json_sax_t = SAX;
  7360. using char_type = typename InputAdapterType::char_type;
  7361. using char_int_type = typename std::char_traits<char_type>::int_type;
  7362. public:
  7363. /*!
  7364. @brief create a binary reader
  7365. @param[in] adapter input adapter to read from
  7366. */
  7367. explicit binary_reader(InputAdapterType&& adapter) noexcept : ia(std::move(adapter))
  7368. {
  7369. (void)detail::is_sax_static_asserts<SAX, BasicJsonType> {};
  7370. }
  7371. // make class move-only
  7372. binary_reader(const binary_reader&) = delete;
  7373. binary_reader(binary_reader&&) = default; // NOLINT(hicpp-noexcept-move,performance-noexcept-move-constructor)
  7374. binary_reader& operator=(const binary_reader&) = delete;
  7375. binary_reader& operator=(binary_reader&&) = default; // NOLINT(hicpp-noexcept-move,performance-noexcept-move-constructor)
  7376. ~binary_reader() = default;
  7377. /*!
  7378. @param[in] format the binary format to parse
  7379. @param[in] sax_ a SAX event processor
  7380. @param[in] strict whether to expect the input to be consumed completed
  7381. @param[in] tag_handler how to treat CBOR tags
  7382. @return whether parsing was successful
  7383. */
  7384. JSON_HEDLEY_NON_NULL(3)
  7385. bool sax_parse(const input_format_t format,
  7386. json_sax_t* sax_,
  7387. const bool strict = true,
  7388. const cbor_tag_handler_t tag_handler = cbor_tag_handler_t::error)
  7389. {
  7390. sax = sax_;
  7391. bool result = false;
  7392. switch (format)
  7393. {
  7394. case input_format_t::bson:
  7395. result = parse_bson_internal();
  7396. break;
  7397. case input_format_t::cbor:
  7398. result = parse_cbor_internal(true, tag_handler);
  7399. break;
  7400. case input_format_t::msgpack:
  7401. result = parse_msgpack_internal();
  7402. break;
  7403. case input_format_t::ubjson:
  7404. result = parse_ubjson_internal();
  7405. break;
  7406. case input_format_t::json: // LCOV_EXCL_LINE
  7407. default: // LCOV_EXCL_LINE
  7408. JSON_ASSERT(false); // NOLINT(cert-dcl03-c,hicpp-static-assert,misc-static-assert) LCOV_EXCL_LINE
  7409. }
  7410. // strict mode: next byte must be EOF
  7411. if (result && strict)
  7412. {
  7413. if (format == input_format_t::ubjson)
  7414. {
  7415. get_ignore_noop();
  7416. }
  7417. else
  7418. {
  7419. get();
  7420. }
  7421. if (JSON_HEDLEY_UNLIKELY(current != std::char_traits<char_type>::eof()))
  7422. {
  7423. return sax->parse_error(chars_read, get_token_string(),
  7424. parse_error::create(110, chars_read, exception_message(format, "expected end of input; last byte: 0x" + get_token_string(), "value"), BasicJsonType()));
  7425. }
  7426. }
  7427. return result;
  7428. }
  7429. private:
  7430. //////////
  7431. // BSON //
  7432. //////////
  7433. /*!
  7434. @brief Reads in a BSON-object and passes it to the SAX-parser.
  7435. @return whether a valid BSON-value was passed to the SAX parser
  7436. */
  7437. bool parse_bson_internal()
  7438. {
  7439. std::int32_t document_size{};
  7440. get_number<std::int32_t, true>(input_format_t::bson, document_size);
  7441. if (JSON_HEDLEY_UNLIKELY(!sax->start_object(std::size_t(-1))))
  7442. {
  7443. return false;
  7444. }
  7445. if (JSON_HEDLEY_UNLIKELY(!parse_bson_element_list(/*is_array*/false)))
  7446. {
  7447. return false;
  7448. }
  7449. return sax->end_object();
  7450. }
  7451. /*!
  7452. @brief Parses a C-style string from the BSON input.
  7453. @param[in,out] result A reference to the string variable where the read
  7454. string is to be stored.
  7455. @return `true` if the \x00-byte indicating the end of the string was
  7456. encountered before the EOF; false` indicates an unexpected EOF.
  7457. */
  7458. bool get_bson_cstr(string_t& result)
  7459. {
  7460. auto out = std::back_inserter(result);
  7461. while (true)
  7462. {
  7463. get();
  7464. if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(input_format_t::bson, "cstring")))
  7465. {
  7466. return false;
  7467. }
  7468. if (current == 0x00)
  7469. {
  7470. return true;
  7471. }
  7472. *out++ = static_cast<typename string_t::value_type>(current);
  7473. }
  7474. }
  7475. /*!
  7476. @brief Parses a zero-terminated string of length @a len from the BSON
  7477. input.
  7478. @param[in] len The length (including the zero-byte at the end) of the
  7479. string to be read.
  7480. @param[in,out] result A reference to the string variable where the read
  7481. string is to be stored.
  7482. @tparam NumberType The type of the length @a len
  7483. @pre len >= 1
  7484. @return `true` if the string was successfully parsed
  7485. */
  7486. template<typename NumberType>
  7487. bool get_bson_string(const NumberType len, string_t& result)
  7488. {
  7489. if (JSON_HEDLEY_UNLIKELY(len < 1))
  7490. {
  7491. auto last_token = get_token_string();
  7492. 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()));
  7493. }
  7494. return get_string(input_format_t::bson, len - static_cast<NumberType>(1), result) && get() != std::char_traits<char_type>::eof();
  7495. }
  7496. /*!
  7497. @brief Parses a byte array input of length @a len from the BSON input.
  7498. @param[in] len The length of the byte array to be read.
  7499. @param[in,out] result A reference to the binary variable where the read
  7500. array is to be stored.
  7501. @tparam NumberType The type of the length @a len
  7502. @pre len >= 0
  7503. @return `true` if the byte array was successfully parsed
  7504. */
  7505. template<typename NumberType>
  7506. bool get_bson_binary(const NumberType len, binary_t& result)
  7507. {
  7508. if (JSON_HEDLEY_UNLIKELY(len < 0))
  7509. {
  7510. auto last_token = get_token_string();
  7511. 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()));
  7512. }
  7513. // All BSON binary values have a subtype
  7514. std::uint8_t subtype{};
  7515. get_number<std::uint8_t>(input_format_t::bson, subtype);
  7516. result.set_subtype(subtype);
  7517. return get_binary(input_format_t::bson, len, result);
  7518. }
  7519. /*!
  7520. @brief Read a BSON document element of the given @a element_type.
  7521. @param[in] element_type The BSON element type, c.f. http://bsonspec.org/spec.html
  7522. @param[in] element_type_parse_position The position in the input stream,
  7523. where the `element_type` was read.
  7524. @warning Not all BSON element types are supported yet. An unsupported
  7525. @a element_type will give rise to a parse_error.114:
  7526. Unsupported BSON record type 0x...
  7527. @return whether a valid BSON-object/array was passed to the SAX parser
  7528. */
  7529. bool parse_bson_element_internal(const char_int_type element_type,
  7530. const std::size_t element_type_parse_position)
  7531. {
  7532. switch (element_type)
  7533. {
  7534. case 0x01: // double
  7535. {
  7536. double number{};
  7537. return get_number<double, true>(input_format_t::bson, number) && sax->number_float(static_cast<number_float_t>(number), "");
  7538. }
  7539. case 0x02: // string
  7540. {
  7541. std::int32_t len{};
  7542. string_t value;
  7543. return get_number<std::int32_t, true>(input_format_t::bson, len) && get_bson_string(len, value) && sax->string(value);
  7544. }
  7545. case 0x03: // object
  7546. {
  7547. return parse_bson_internal();
  7548. }
  7549. case 0x04: // array
  7550. {
  7551. return parse_bson_array();
  7552. }
  7553. case 0x05: // binary
  7554. {
  7555. std::int32_t len{};
  7556. binary_t value;
  7557. return get_number<std::int32_t, true>(input_format_t::bson, len) && get_bson_binary(len, value) && sax->binary(value);
  7558. }
  7559. case 0x08: // boolean
  7560. {
  7561. return sax->boolean(get() != 0);
  7562. }
  7563. case 0x0A: // null
  7564. {
  7565. return sax->null();
  7566. }
  7567. case 0x10: // int32
  7568. {
  7569. std::int32_t value{};
  7570. return get_number<std::int32_t, true>(input_format_t::bson, value) && sax->number_integer(value);
  7571. }
  7572. case 0x12: // int64
  7573. {
  7574. std::int64_t value{};
  7575. return get_number<std::int64_t, true>(input_format_t::bson, value) && sax->number_integer(value);
  7576. }
  7577. default: // anything else not supported (yet)
  7578. {
  7579. std::array<char, 3> cr{{}};
  7580. (std::snprintf)(cr.data(), cr.size(), "%.2hhX", static_cast<unsigned char>(element_type)); // NOLINT(cppcoreguidelines-pro-type-vararg,hicpp-vararg)
  7581. 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()));
  7582. }
  7583. }
  7584. }
  7585. /*!
  7586. @brief Read a BSON element list (as specified in the BSON-spec)
  7587. The same binary layout is used for objects and arrays, hence it must be
  7588. indicated with the argument @a is_array which one is expected
  7589. (true --> array, false --> object).
  7590. @param[in] is_array Determines if the element list being read is to be
  7591. treated as an object (@a is_array == false), or as an
  7592. array (@a is_array == true).
  7593. @return whether a valid BSON-object/array was passed to the SAX parser
  7594. */
  7595. bool parse_bson_element_list(const bool is_array)
  7596. {
  7597. string_t key;
  7598. while (auto element_type = get())
  7599. {
  7600. if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(input_format_t::bson, "element list")))
  7601. {
  7602. return false;
  7603. }
  7604. const std::size_t element_type_parse_position = chars_read;
  7605. if (JSON_HEDLEY_UNLIKELY(!get_bson_cstr(key)))
  7606. {
  7607. return false;
  7608. }
  7609. if (!is_array && !sax->key(key))
  7610. {
  7611. return false;
  7612. }
  7613. if (JSON_HEDLEY_UNLIKELY(!parse_bson_element_internal(element_type, element_type_parse_position)))
  7614. {
  7615. return false;
  7616. }
  7617. // get_bson_cstr only appends
  7618. key.clear();
  7619. }
  7620. return true;
  7621. }
  7622. /*!
  7623. @brief Reads an array from the BSON input and passes it to the SAX-parser.
  7624. @return whether a valid BSON-array was passed to the SAX parser
  7625. */
  7626. bool parse_bson_array()
  7627. {
  7628. std::int32_t document_size{};
  7629. get_number<std::int32_t, true>(input_format_t::bson, document_size);
  7630. if (JSON_HEDLEY_UNLIKELY(!sax->start_array(std::size_t(-1))))
  7631. {
  7632. return false;
  7633. }
  7634. if (JSON_HEDLEY_UNLIKELY(!parse_bson_element_list(/*is_array*/true)))
  7635. {
  7636. return false;
  7637. }
  7638. return sax->end_array();
  7639. }
  7640. //////////
  7641. // CBOR //
  7642. //////////
  7643. /*!
  7644. @param[in] get_char whether a new character should be retrieved from the
  7645. input (true) or whether the last read character should
  7646. be considered instead (false)
  7647. @param[in] tag_handler how CBOR tags should be treated
  7648. @return whether a valid CBOR value was passed to the SAX parser
  7649. */
  7650. bool parse_cbor_internal(const bool get_char,
  7651. const cbor_tag_handler_t tag_handler)
  7652. {
  7653. switch (get_char ? get() : current)
  7654. {
  7655. // EOF
  7656. case std::char_traits<char_type>::eof():
  7657. return unexpect_eof(input_format_t::cbor, "value");
  7658. // Integer 0x00..0x17 (0..23)
  7659. case 0x00:
  7660. case 0x01:
  7661. case 0x02:
  7662. case 0x03:
  7663. case 0x04:
  7664. case 0x05:
  7665. case 0x06:
  7666. case 0x07:
  7667. case 0x08:
  7668. case 0x09:
  7669. case 0x0A:
  7670. case 0x0B:
  7671. case 0x0C:
  7672. case 0x0D:
  7673. case 0x0E:
  7674. case 0x0F:
  7675. case 0x10:
  7676. case 0x11:
  7677. case 0x12:
  7678. case 0x13:
  7679. case 0x14:
  7680. case 0x15:
  7681. case 0x16:
  7682. case 0x17:
  7683. return sax->number_unsigned(static_cast<number_unsigned_t>(current));
  7684. case 0x18: // Unsigned integer (one-byte uint8_t follows)
  7685. {
  7686. std::uint8_t number{};
  7687. return get_number(input_format_t::cbor, number) && sax->number_unsigned(number);
  7688. }
  7689. case 0x19: // Unsigned integer (two-byte uint16_t follows)
  7690. {
  7691. std::uint16_t number{};
  7692. return get_number(input_format_t::cbor, number) && sax->number_unsigned(number);
  7693. }
  7694. case 0x1A: // Unsigned integer (four-byte uint32_t follows)
  7695. {
  7696. std::uint32_t number{};
  7697. return get_number(input_format_t::cbor, number) && sax->number_unsigned(number);
  7698. }
  7699. case 0x1B: // Unsigned integer (eight-byte uint64_t follows)
  7700. {
  7701. std::uint64_t number{};
  7702. return get_number(input_format_t::cbor, number) && sax->number_unsigned(number);
  7703. }
  7704. // Negative integer -1-0x00..-1-0x17 (-1..-24)
  7705. case 0x20:
  7706. case 0x21:
  7707. case 0x22:
  7708. case 0x23:
  7709. case 0x24:
  7710. case 0x25:
  7711. case 0x26:
  7712. case 0x27:
  7713. case 0x28:
  7714. case 0x29:
  7715. case 0x2A:
  7716. case 0x2B:
  7717. case 0x2C:
  7718. case 0x2D:
  7719. case 0x2E:
  7720. case 0x2F:
  7721. case 0x30:
  7722. case 0x31:
  7723. case 0x32:
  7724. case 0x33:
  7725. case 0x34:
  7726. case 0x35:
  7727. case 0x36:
  7728. case 0x37:
  7729. return sax->number_integer(static_cast<std::int8_t>(0x20 - 1 - current));
  7730. case 0x38: // Negative integer (one-byte uint8_t follows)
  7731. {
  7732. std::uint8_t number{};
  7733. return get_number(input_format_t::cbor, number) && sax->number_integer(static_cast<number_integer_t>(-1) - number);
  7734. }
  7735. case 0x39: // Negative integer -1-n (two-byte uint16_t follows)
  7736. {
  7737. std::uint16_t number{};
  7738. return get_number(input_format_t::cbor, number) && sax->number_integer(static_cast<number_integer_t>(-1) - number);
  7739. }
  7740. case 0x3A: // Negative integer -1-n (four-byte uint32_t follows)
  7741. {
  7742. std::uint32_t number{};
  7743. return get_number(input_format_t::cbor, number) && sax->number_integer(static_cast<number_integer_t>(-1) - number);
  7744. }
  7745. case 0x3B: // Negative integer -1-n (eight-byte uint64_t follows)
  7746. {
  7747. std::uint64_t number{};
  7748. return get_number(input_format_t::cbor, number) && sax->number_integer(static_cast<number_integer_t>(-1)
  7749. - static_cast<number_integer_t>(number));
  7750. }
  7751. // Binary data (0x00..0x17 bytes follow)
  7752. case 0x40:
  7753. case 0x41:
  7754. case 0x42:
  7755. case 0x43:
  7756. case 0x44:
  7757. case 0x45:
  7758. case 0x46:
  7759. case 0x47:
  7760. case 0x48:
  7761. case 0x49:
  7762. case 0x4A:
  7763. case 0x4B:
  7764. case 0x4C:
  7765. case 0x4D:
  7766. case 0x4E:
  7767. case 0x4F:
  7768. case 0x50:
  7769. case 0x51:
  7770. case 0x52:
  7771. case 0x53:
  7772. case 0x54:
  7773. case 0x55:
  7774. case 0x56:
  7775. case 0x57:
  7776. case 0x58: // Binary data (one-byte uint8_t for n follows)
  7777. case 0x59: // Binary data (two-byte uint16_t for n follow)
  7778. case 0x5A: // Binary data (four-byte uint32_t for n follow)
  7779. case 0x5B: // Binary data (eight-byte uint64_t for n follow)
  7780. case 0x5F: // Binary data (indefinite length)
  7781. {
  7782. binary_t b;
  7783. return get_cbor_binary(b) && sax->binary(b);
  7784. }
  7785. // UTF-8 string (0x00..0x17 bytes follow)
  7786. case 0x60:
  7787. case 0x61:
  7788. case 0x62:
  7789. case 0x63:
  7790. case 0x64:
  7791. case 0x65:
  7792. case 0x66:
  7793. case 0x67:
  7794. case 0x68:
  7795. case 0x69:
  7796. case 0x6A:
  7797. case 0x6B:
  7798. case 0x6C:
  7799. case 0x6D:
  7800. case 0x6E:
  7801. case 0x6F:
  7802. case 0x70:
  7803. case 0x71:
  7804. case 0x72:
  7805. case 0x73:
  7806. case 0x74:
  7807. case 0x75:
  7808. case 0x76:
  7809. case 0x77:
  7810. case 0x78: // UTF-8 string (one-byte uint8_t for n follows)
  7811. case 0x79: // UTF-8 string (two-byte uint16_t for n follow)
  7812. case 0x7A: // UTF-8 string (four-byte uint32_t for n follow)
  7813. case 0x7B: // UTF-8 string (eight-byte uint64_t for n follow)
  7814. case 0x7F: // UTF-8 string (indefinite length)
  7815. {
  7816. string_t s;
  7817. return get_cbor_string(s) && sax->string(s);
  7818. }
  7819. // array (0x00..0x17 data items follow)
  7820. case 0x80:
  7821. case 0x81:
  7822. case 0x82:
  7823. case 0x83:
  7824. case 0x84:
  7825. case 0x85:
  7826. case 0x86:
  7827. case 0x87:
  7828. case 0x88:
  7829. case 0x89:
  7830. case 0x8A:
  7831. case 0x8B:
  7832. case 0x8C:
  7833. case 0x8D:
  7834. case 0x8E:
  7835. case 0x8F:
  7836. case 0x90:
  7837. case 0x91:
  7838. case 0x92:
  7839. case 0x93:
  7840. case 0x94:
  7841. case 0x95:
  7842. case 0x96:
  7843. case 0x97:
  7844. return get_cbor_array(static_cast<std::size_t>(static_cast<unsigned int>(current) & 0x1Fu), tag_handler);
  7845. case 0x98: // array (one-byte uint8_t for n follows)
  7846. {
  7847. std::uint8_t len{};
  7848. return get_number(input_format_t::cbor, len) && get_cbor_array(static_cast<std::size_t>(len), tag_handler);
  7849. }
  7850. case 0x99: // array (two-byte uint16_t for n follow)
  7851. {
  7852. std::uint16_t len{};
  7853. return get_number(input_format_t::cbor, len) && get_cbor_array(static_cast<std::size_t>(len), tag_handler);
  7854. }
  7855. case 0x9A: // array (four-byte uint32_t for n follow)
  7856. {
  7857. std::uint32_t len{};
  7858. return get_number(input_format_t::cbor, len) && get_cbor_array(static_cast<std::size_t>(len), tag_handler);
  7859. }
  7860. case 0x9B: // array (eight-byte uint64_t for n follow)
  7861. {
  7862. std::uint64_t len{};
  7863. return get_number(input_format_t::cbor, len) && get_cbor_array(detail::conditional_static_cast<std::size_t>(len), tag_handler);
  7864. }
  7865. case 0x9F: // array (indefinite length)
  7866. return get_cbor_array(std::size_t(-1), tag_handler);
  7867. // map (0x00..0x17 pairs of data items follow)
  7868. case 0xA0:
  7869. case 0xA1:
  7870. case 0xA2:
  7871. case 0xA3:
  7872. case 0xA4:
  7873. case 0xA5:
  7874. case 0xA6:
  7875. case 0xA7:
  7876. case 0xA8:
  7877. case 0xA9:
  7878. case 0xAA:
  7879. case 0xAB:
  7880. case 0xAC:
  7881. case 0xAD:
  7882. case 0xAE:
  7883. case 0xAF:
  7884. case 0xB0:
  7885. case 0xB1:
  7886. case 0xB2:
  7887. case 0xB3:
  7888. case 0xB4:
  7889. case 0xB5:
  7890. case 0xB6:
  7891. case 0xB7:
  7892. return get_cbor_object(static_cast<std::size_t>(static_cast<unsigned int>(current) & 0x1Fu), tag_handler);
  7893. case 0xB8: // map (one-byte uint8_t for n follows)
  7894. {
  7895. std::uint8_t len{};
  7896. return get_number(input_format_t::cbor, len) && get_cbor_object(static_cast<std::size_t>(len), tag_handler);
  7897. }
  7898. case 0xB9: // map (two-byte uint16_t for n follow)
  7899. {
  7900. std::uint16_t len{};
  7901. return get_number(input_format_t::cbor, len) && get_cbor_object(static_cast<std::size_t>(len), tag_handler);
  7902. }
  7903. case 0xBA: // map (four-byte uint32_t for n follow)
  7904. {
  7905. std::uint32_t len{};
  7906. return get_number(input_format_t::cbor, len) && get_cbor_object(static_cast<std::size_t>(len), tag_handler);
  7907. }
  7908. case 0xBB: // map (eight-byte uint64_t for n follow)
  7909. {
  7910. std::uint64_t len{};
  7911. return get_number(input_format_t::cbor, len) && get_cbor_object(detail::conditional_static_cast<std::size_t>(len), tag_handler);
  7912. }
  7913. case 0xBF: // map (indefinite length)
  7914. return get_cbor_object(std::size_t(-1), tag_handler);
  7915. case 0xC6: // tagged item
  7916. case 0xC7:
  7917. case 0xC8:
  7918. case 0xC9:
  7919. case 0xCA:
  7920. case 0xCB:
  7921. case 0xCC:
  7922. case 0xCD:
  7923. case 0xCE:
  7924. case 0xCF:
  7925. case 0xD0:
  7926. case 0xD1:
  7927. case 0xD2:
  7928. case 0xD3:
  7929. case 0xD4:
  7930. case 0xD8: // tagged item (1 bytes follow)
  7931. case 0xD9: // tagged item (2 bytes follow)
  7932. case 0xDA: // tagged item (4 bytes follow)
  7933. case 0xDB: // tagged item (8 bytes follow)
  7934. {
  7935. switch (tag_handler)
  7936. {
  7937. case cbor_tag_handler_t::error:
  7938. {
  7939. auto last_token = get_token_string();
  7940. 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()));
  7941. }
  7942. case cbor_tag_handler_t::ignore:
  7943. {
  7944. // ignore binary subtype
  7945. switch (current)
  7946. {
  7947. case 0xD8:
  7948. {
  7949. std::uint8_t subtype_to_ignore{};
  7950. get_number(input_format_t::cbor, subtype_to_ignore);
  7951. break;
  7952. }
  7953. case 0xD9:
  7954. {
  7955. std::uint16_t subtype_to_ignore{};
  7956. get_number(input_format_t::cbor, subtype_to_ignore);
  7957. break;
  7958. }
  7959. case 0xDA:
  7960. {
  7961. std::uint32_t subtype_to_ignore{};
  7962. get_number(input_format_t::cbor, subtype_to_ignore);
  7963. break;
  7964. }
  7965. case 0xDB:
  7966. {
  7967. std::uint64_t subtype_to_ignore{};
  7968. get_number(input_format_t::cbor, subtype_to_ignore);
  7969. break;
  7970. }
  7971. default:
  7972. break;
  7973. }
  7974. return parse_cbor_internal(true, tag_handler);
  7975. }
  7976. case cbor_tag_handler_t::store:
  7977. {
  7978. binary_t b;
  7979. // use binary subtype and store in binary container
  7980. switch (current)
  7981. {
  7982. case 0xD8:
  7983. {
  7984. std::uint8_t subtype{};
  7985. get_number(input_format_t::cbor, subtype);
  7986. b.set_subtype(detail::conditional_static_cast<typename binary_t::subtype_type>(subtype));
  7987. break;
  7988. }
  7989. case 0xD9:
  7990. {
  7991. std::uint16_t subtype{};
  7992. get_number(input_format_t::cbor, subtype);
  7993. b.set_subtype(detail::conditional_static_cast<typename binary_t::subtype_type>(subtype));
  7994. break;
  7995. }
  7996. case 0xDA:
  7997. {
  7998. std::uint32_t subtype{};
  7999. get_number(input_format_t::cbor, subtype);
  8000. b.set_subtype(detail::conditional_static_cast<typename binary_t::subtype_type>(subtype));
  8001. break;
  8002. }
  8003. case 0xDB:
  8004. {
  8005. std::uint64_t subtype{};
  8006. get_number(input_format_t::cbor, subtype);
  8007. b.set_subtype(detail::conditional_static_cast<typename binary_t::subtype_type>(subtype));
  8008. break;
  8009. }
  8010. default:
  8011. return parse_cbor_internal(true, tag_handler);
  8012. }
  8013. get();
  8014. return get_cbor_binary(b) && sax->binary(b);
  8015. }
  8016. default: // LCOV_EXCL_LINE
  8017. JSON_ASSERT(false); // NOLINT(cert-dcl03-c,hicpp-static-assert,misc-static-assert) LCOV_EXCL_LINE
  8018. return false; // LCOV_EXCL_LINE
  8019. }
  8020. }
  8021. case 0xF4: // false
  8022. return sax->boolean(false);
  8023. case 0xF5: // true
  8024. return sax->boolean(true);
  8025. case 0xF6: // null
  8026. return sax->null();
  8027. case 0xF9: // Half-Precision Float (two-byte IEEE 754)
  8028. {
  8029. const auto byte1_raw = get();
  8030. if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(input_format_t::cbor, "number")))
  8031. {
  8032. return false;
  8033. }
  8034. const auto byte2_raw = get();
  8035. if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(input_format_t::cbor, "number")))
  8036. {
  8037. return false;
  8038. }
  8039. const auto byte1 = static_cast<unsigned char>(byte1_raw);
  8040. const auto byte2 = static_cast<unsigned char>(byte2_raw);
  8041. // code from RFC 7049, Appendix D, Figure 3:
  8042. // As half-precision floating-point numbers were only added
  8043. // to IEEE 754 in 2008, today's programming platforms often
  8044. // still only have limited support for them. It is very
  8045. // easy to include at least decoding support for them even
  8046. // without such support. An example of a small decoder for
  8047. // half-precision floating-point numbers in the C language
  8048. // is shown in Fig. 3.
  8049. const auto half = static_cast<unsigned int>((byte1 << 8u) + byte2);
  8050. const double val = [&half]
  8051. {
  8052. const int exp = (half >> 10u) & 0x1Fu;
  8053. const unsigned int mant = half & 0x3FFu;
  8054. JSON_ASSERT(0 <= exp&& exp <= 32);
  8055. JSON_ASSERT(mant <= 1024);
  8056. switch (exp)
  8057. {
  8058. case 0:
  8059. return std::ldexp(mant, -24);
  8060. case 31:
  8061. return (mant == 0)
  8062. ? std::numeric_limits<double>::infinity()
  8063. : std::numeric_limits<double>::quiet_NaN();
  8064. default:
  8065. return std::ldexp(mant + 1024, exp - 25);
  8066. }
  8067. }();
  8068. return sax->number_float((half & 0x8000u) != 0
  8069. ? static_cast<number_float_t>(-val)
  8070. : static_cast<number_float_t>(val), "");
  8071. }
  8072. case 0xFA: // Single-Precision Float (four-byte IEEE 754)
  8073. {
  8074. float number{};
  8075. return get_number(input_format_t::cbor, number) && sax->number_float(static_cast<number_float_t>(number), "");
  8076. }
  8077. case 0xFB: // Double-Precision Float (eight-byte IEEE 754)
  8078. {
  8079. double number{};
  8080. return get_number(input_format_t::cbor, number) && sax->number_float(static_cast<number_float_t>(number), "");
  8081. }
  8082. default: // anything else (0xFF is handled inside the other types)
  8083. {
  8084. auto last_token = get_token_string();
  8085. 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()));
  8086. }
  8087. }
  8088. }
  8089. /*!
  8090. @brief reads a CBOR string
  8091. This function first reads starting bytes to determine the expected
  8092. string length and then copies this number of bytes into a string.
  8093. Additionally, CBOR's strings with indefinite lengths are supported.
  8094. @param[out] result created string
  8095. @return whether string creation completed
  8096. */
  8097. bool get_cbor_string(string_t& result)
  8098. {
  8099. if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(input_format_t::cbor, "string")))
  8100. {
  8101. return false;
  8102. }
  8103. switch (current)
  8104. {
  8105. // UTF-8 string (0x00..0x17 bytes follow)
  8106. case 0x60:
  8107. case 0x61:
  8108. case 0x62:
  8109. case 0x63:
  8110. case 0x64:
  8111. case 0x65:
  8112. case 0x66:
  8113. case 0x67:
  8114. case 0x68:
  8115. case 0x69:
  8116. case 0x6A:
  8117. case 0x6B:
  8118. case 0x6C:
  8119. case 0x6D:
  8120. case 0x6E:
  8121. case 0x6F:
  8122. case 0x70:
  8123. case 0x71:
  8124. case 0x72:
  8125. case 0x73:
  8126. case 0x74:
  8127. case 0x75:
  8128. case 0x76:
  8129. case 0x77:
  8130. {
  8131. return get_string(input_format_t::cbor, static_cast<unsigned int>(current) & 0x1Fu, result);
  8132. }
  8133. case 0x78: // UTF-8 string (one-byte uint8_t for n follows)
  8134. {
  8135. std::uint8_t len{};
  8136. return get_number(input_format_t::cbor, len) && get_string(input_format_t::cbor, len, result);
  8137. }
  8138. case 0x79: // UTF-8 string (two-byte uint16_t for n follow)
  8139. {
  8140. std::uint16_t len{};
  8141. return get_number(input_format_t::cbor, len) && get_string(input_format_t::cbor, len, result);
  8142. }
  8143. case 0x7A: // UTF-8 string (four-byte uint32_t for n follow)
  8144. {
  8145. std::uint32_t len{};
  8146. return get_number(input_format_t::cbor, len) && get_string(input_format_t::cbor, len, result);
  8147. }
  8148. case 0x7B: // UTF-8 string (eight-byte uint64_t for n follow)
  8149. {
  8150. std::uint64_t len{};
  8151. return get_number(input_format_t::cbor, len) && get_string(input_format_t::cbor, len, result);
  8152. }
  8153. case 0x7F: // UTF-8 string (indefinite length)
  8154. {
  8155. while (get() != 0xFF)
  8156. {
  8157. string_t chunk;
  8158. if (!get_cbor_string(chunk))
  8159. {
  8160. return false;
  8161. }
  8162. result.append(chunk);
  8163. }
  8164. return true;
  8165. }
  8166. default:
  8167. {
  8168. auto last_token = get_token_string();
  8169. 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()));
  8170. }
  8171. }
  8172. }
  8173. /*!
  8174. @brief reads a CBOR byte array
  8175. This function first reads starting bytes to determine the expected
  8176. byte array length and then copies this number of bytes into the byte array.
  8177. Additionally, CBOR's byte arrays with indefinite lengths are supported.
  8178. @param[out] result created byte array
  8179. @return whether byte array creation completed
  8180. */
  8181. bool get_cbor_binary(binary_t& result)
  8182. {
  8183. if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(input_format_t::cbor, "binary")))
  8184. {
  8185. return false;
  8186. }
  8187. switch (current)
  8188. {
  8189. // Binary data (0x00..0x17 bytes follow)
  8190. case 0x40:
  8191. case 0x41:
  8192. case 0x42:
  8193. case 0x43:
  8194. case 0x44:
  8195. case 0x45:
  8196. case 0x46:
  8197. case 0x47:
  8198. case 0x48:
  8199. case 0x49:
  8200. case 0x4A:
  8201. case 0x4B:
  8202. case 0x4C:
  8203. case 0x4D:
  8204. case 0x4E:
  8205. case 0x4F:
  8206. case 0x50:
  8207. case 0x51:
  8208. case 0x52:
  8209. case 0x53:
  8210. case 0x54:
  8211. case 0x55:
  8212. case 0x56:
  8213. case 0x57:
  8214. {
  8215. return get_binary(input_format_t::cbor, static_cast<unsigned int>(current) & 0x1Fu, result);
  8216. }
  8217. case 0x58: // Binary data (one-byte uint8_t for n follows)
  8218. {
  8219. std::uint8_t len{};
  8220. return get_number(input_format_t::cbor, len) &&
  8221. get_binary(input_format_t::cbor, len, result);
  8222. }
  8223. case 0x59: // Binary data (two-byte uint16_t for n follow)
  8224. {
  8225. std::uint16_t len{};
  8226. return get_number(input_format_t::cbor, len) &&
  8227. get_binary(input_format_t::cbor, len, result);
  8228. }
  8229. case 0x5A: // Binary data (four-byte uint32_t for n follow)
  8230. {
  8231. std::uint32_t len{};
  8232. return get_number(input_format_t::cbor, len) &&
  8233. get_binary(input_format_t::cbor, len, result);
  8234. }
  8235. case 0x5B: // Binary data (eight-byte uint64_t for n follow)
  8236. {
  8237. std::uint64_t len{};
  8238. return get_number(input_format_t::cbor, len) &&
  8239. get_binary(input_format_t::cbor, len, result);
  8240. }
  8241. case 0x5F: // Binary data (indefinite length)
  8242. {
  8243. while (get() != 0xFF)
  8244. {
  8245. binary_t chunk;
  8246. if (!get_cbor_binary(chunk))
  8247. {
  8248. return false;
  8249. }
  8250. result.insert(result.end(), chunk.begin(), chunk.end());
  8251. }
  8252. return true;
  8253. }
  8254. default:
  8255. {
  8256. auto last_token = get_token_string();
  8257. 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()));
  8258. }
  8259. }
  8260. }
  8261. /*!
  8262. @param[in] len the length of the array or std::size_t(-1) for an
  8263. array of indefinite size
  8264. @param[in] tag_handler how CBOR tags should be treated
  8265. @return whether array creation completed
  8266. */
  8267. bool get_cbor_array(const std::size_t len,
  8268. const cbor_tag_handler_t tag_handler)
  8269. {
  8270. if (JSON_HEDLEY_UNLIKELY(!sax->start_array(len)))
  8271. {
  8272. return false;
  8273. }
  8274. if (len != std::size_t(-1))
  8275. {
  8276. for (std::size_t i = 0; i < len; ++i)
  8277. {
  8278. if (JSON_HEDLEY_UNLIKELY(!parse_cbor_internal(true, tag_handler)))
  8279. {
  8280. return false;
  8281. }
  8282. }
  8283. }
  8284. else
  8285. {
  8286. while (get() != 0xFF)
  8287. {
  8288. if (JSON_HEDLEY_UNLIKELY(!parse_cbor_internal(false, tag_handler)))
  8289. {
  8290. return false;
  8291. }
  8292. }
  8293. }
  8294. return sax->end_array();
  8295. }
  8296. /*!
  8297. @param[in] len the length of the object or std::size_t(-1) for an
  8298. object of indefinite size
  8299. @param[in] tag_handler how CBOR tags should be treated
  8300. @return whether object creation completed
  8301. */
  8302. bool get_cbor_object(const std::size_t len,
  8303. const cbor_tag_handler_t tag_handler)
  8304. {
  8305. if (JSON_HEDLEY_UNLIKELY(!sax->start_object(len)))
  8306. {
  8307. return false;
  8308. }
  8309. if (len != 0)
  8310. {
  8311. string_t key;
  8312. if (len != std::size_t(-1))
  8313. {
  8314. for (std::size_t i = 0; i < len; ++i)
  8315. {
  8316. get();
  8317. if (JSON_HEDLEY_UNLIKELY(!get_cbor_string(key) || !sax->key(key)))
  8318. {
  8319. return false;
  8320. }
  8321. if (JSON_HEDLEY_UNLIKELY(!parse_cbor_internal(true, tag_handler)))
  8322. {
  8323. return false;
  8324. }
  8325. key.clear();
  8326. }
  8327. }
  8328. else
  8329. {
  8330. while (get() != 0xFF)
  8331. {
  8332. if (JSON_HEDLEY_UNLIKELY(!get_cbor_string(key) || !sax->key(key)))
  8333. {
  8334. return false;
  8335. }
  8336. if (JSON_HEDLEY_UNLIKELY(!parse_cbor_internal(true, tag_handler)))
  8337. {
  8338. return false;
  8339. }
  8340. key.clear();
  8341. }
  8342. }
  8343. }
  8344. return sax->end_object();
  8345. }
  8346. /////////////
  8347. // MsgPack //
  8348. /////////////
  8349. /*!
  8350. @return whether a valid MessagePack value was passed to the SAX parser
  8351. */
  8352. bool parse_msgpack_internal()
  8353. {
  8354. switch (get())
  8355. {
  8356. // EOF
  8357. case std::char_traits<char_type>::eof():
  8358. return unexpect_eof(input_format_t::msgpack, "value");
  8359. // positive fixint
  8360. case 0x00:
  8361. case 0x01:
  8362. case 0x02:
  8363. case 0x03:
  8364. case 0x04:
  8365. case 0x05:
  8366. case 0x06:
  8367. case 0x07:
  8368. case 0x08:
  8369. case 0x09:
  8370. case 0x0A:
  8371. case 0x0B:
  8372. case 0x0C:
  8373. case 0x0D:
  8374. case 0x0E:
  8375. case 0x0F:
  8376. case 0x10:
  8377. case 0x11:
  8378. case 0x12:
  8379. case 0x13:
  8380. case 0x14:
  8381. case 0x15:
  8382. case 0x16:
  8383. case 0x17:
  8384. case 0x18:
  8385. case 0x19:
  8386. case 0x1A:
  8387. case 0x1B:
  8388. case 0x1C:
  8389. case 0x1D:
  8390. case 0x1E:
  8391. case 0x1F:
  8392. case 0x20:
  8393. case 0x21:
  8394. case 0x22:
  8395. case 0x23:
  8396. case 0x24:
  8397. case 0x25:
  8398. case 0x26:
  8399. case 0x27:
  8400. case 0x28:
  8401. case 0x29:
  8402. case 0x2A:
  8403. case 0x2B:
  8404. case 0x2C:
  8405. case 0x2D:
  8406. case 0x2E:
  8407. case 0x2F:
  8408. case 0x30:
  8409. case 0x31:
  8410. case 0x32:
  8411. case 0x33:
  8412. case 0x34:
  8413. case 0x35:
  8414. case 0x36:
  8415. case 0x37:
  8416. case 0x38:
  8417. case 0x39:
  8418. case 0x3A:
  8419. case 0x3B:
  8420. case 0x3C:
  8421. case 0x3D:
  8422. case 0x3E:
  8423. case 0x3F:
  8424. case 0x40:
  8425. case 0x41:
  8426. case 0x42:
  8427. case 0x43:
  8428. case 0x44:
  8429. case 0x45:
  8430. case 0x46:
  8431. case 0x47:
  8432. case 0x48:
  8433. case 0x49:
  8434. case 0x4A:
  8435. case 0x4B:
  8436. case 0x4C:
  8437. case 0x4D:
  8438. case 0x4E:
  8439. case 0x4F:
  8440. case 0x50:
  8441. case 0x51:
  8442. case 0x52:
  8443. case 0x53:
  8444. case 0x54:
  8445. case 0x55:
  8446. case 0x56:
  8447. case 0x57:
  8448. case 0x58:
  8449. case 0x59:
  8450. case 0x5A:
  8451. case 0x5B:
  8452. case 0x5C:
  8453. case 0x5D:
  8454. case 0x5E:
  8455. case 0x5F:
  8456. case 0x60:
  8457. case 0x61:
  8458. case 0x62:
  8459. case 0x63:
  8460. case 0x64:
  8461. case 0x65:
  8462. case 0x66:
  8463. case 0x67:
  8464. case 0x68:
  8465. case 0x69:
  8466. case 0x6A:
  8467. case 0x6B:
  8468. case 0x6C:
  8469. case 0x6D:
  8470. case 0x6E:
  8471. case 0x6F:
  8472. case 0x70:
  8473. case 0x71:
  8474. case 0x72:
  8475. case 0x73:
  8476. case 0x74:
  8477. case 0x75:
  8478. case 0x76:
  8479. case 0x77:
  8480. case 0x78:
  8481. case 0x79:
  8482. case 0x7A:
  8483. case 0x7B:
  8484. case 0x7C:
  8485. case 0x7D:
  8486. case 0x7E:
  8487. case 0x7F:
  8488. return sax->number_unsigned(static_cast<number_unsigned_t>(current));
  8489. // fixmap
  8490. case 0x80:
  8491. case 0x81:
  8492. case 0x82:
  8493. case 0x83:
  8494. case 0x84:
  8495. case 0x85:
  8496. case 0x86:
  8497. case 0x87:
  8498. case 0x88:
  8499. case 0x89:
  8500. case 0x8A:
  8501. case 0x8B:
  8502. case 0x8C:
  8503. case 0x8D:
  8504. case 0x8E:
  8505. case 0x8F:
  8506. return get_msgpack_object(static_cast<std::size_t>(static_cast<unsigned int>(current) & 0x0Fu));
  8507. // fixarray
  8508. case 0x90:
  8509. case 0x91:
  8510. case 0x92:
  8511. case 0x93:
  8512. case 0x94:
  8513. case 0x95:
  8514. case 0x96:
  8515. case 0x97:
  8516. case 0x98:
  8517. case 0x99:
  8518. case 0x9A:
  8519. case 0x9B:
  8520. case 0x9C:
  8521. case 0x9D:
  8522. case 0x9E:
  8523. case 0x9F:
  8524. return get_msgpack_array(static_cast<std::size_t>(static_cast<unsigned int>(current) & 0x0Fu));
  8525. // fixstr
  8526. case 0xA0:
  8527. case 0xA1:
  8528. case 0xA2:
  8529. case 0xA3:
  8530. case 0xA4:
  8531. case 0xA5:
  8532. case 0xA6:
  8533. case 0xA7:
  8534. case 0xA8:
  8535. case 0xA9:
  8536. case 0xAA:
  8537. case 0xAB:
  8538. case 0xAC:
  8539. case 0xAD:
  8540. case 0xAE:
  8541. case 0xAF:
  8542. case 0xB0:
  8543. case 0xB1:
  8544. case 0xB2:
  8545. case 0xB3:
  8546. case 0xB4:
  8547. case 0xB5:
  8548. case 0xB6:
  8549. case 0xB7:
  8550. case 0xB8:
  8551. case 0xB9:
  8552. case 0xBA:
  8553. case 0xBB:
  8554. case 0xBC:
  8555. case 0xBD:
  8556. case 0xBE:
  8557. case 0xBF:
  8558. case 0xD9: // str 8
  8559. case 0xDA: // str 16
  8560. case 0xDB: // str 32
  8561. {
  8562. string_t s;
  8563. return get_msgpack_string(s) && sax->string(s);
  8564. }
  8565. case 0xC0: // nil
  8566. return sax->null();
  8567. case 0xC2: // false
  8568. return sax->boolean(false);
  8569. case 0xC3: // true
  8570. return sax->boolean(true);
  8571. case 0xC4: // bin 8
  8572. case 0xC5: // bin 16
  8573. case 0xC6: // bin 32
  8574. case 0xC7: // ext 8
  8575. case 0xC8: // ext 16
  8576. case 0xC9: // ext 32
  8577. case 0xD4: // fixext 1
  8578. case 0xD5: // fixext 2
  8579. case 0xD6: // fixext 4
  8580. case 0xD7: // fixext 8
  8581. case 0xD8: // fixext 16
  8582. {
  8583. binary_t b;
  8584. return get_msgpack_binary(b) && sax->binary(b);
  8585. }
  8586. case 0xCA: // float 32
  8587. {
  8588. float number{};
  8589. return get_number(input_format_t::msgpack, number) && sax->number_float(static_cast<number_float_t>(number), "");
  8590. }
  8591. case 0xCB: // float 64
  8592. {
  8593. double number{};
  8594. return get_number(input_format_t::msgpack, number) && sax->number_float(static_cast<number_float_t>(number), "");
  8595. }
  8596. case 0xCC: // uint 8
  8597. {
  8598. std::uint8_t number{};
  8599. return get_number(input_format_t::msgpack, number) && sax->number_unsigned(number);
  8600. }
  8601. case 0xCD: // uint 16
  8602. {
  8603. std::uint16_t number{};
  8604. return get_number(input_format_t::msgpack, number) && sax->number_unsigned(number);
  8605. }
  8606. case 0xCE: // uint 32
  8607. {
  8608. std::uint32_t number{};
  8609. return get_number(input_format_t::msgpack, number) && sax->number_unsigned(number);
  8610. }
  8611. case 0xCF: // uint 64
  8612. {
  8613. std::uint64_t number{};
  8614. return get_number(input_format_t::msgpack, number) && sax->number_unsigned(number);
  8615. }
  8616. case 0xD0: // int 8
  8617. {
  8618. std::int8_t number{};
  8619. return get_number(input_format_t::msgpack, number) && sax->number_integer(number);
  8620. }
  8621. case 0xD1: // int 16
  8622. {
  8623. std::int16_t number{};
  8624. return get_number(input_format_t::msgpack, number) && sax->number_integer(number);
  8625. }
  8626. case 0xD2: // int 32
  8627. {
  8628. std::int32_t number{};
  8629. return get_number(input_format_t::msgpack, number) && sax->number_integer(number);
  8630. }
  8631. case 0xD3: // int 64
  8632. {
  8633. std::int64_t number{};
  8634. return get_number(input_format_t::msgpack, number) && sax->number_integer(number);
  8635. }
  8636. case 0xDC: // array 16
  8637. {
  8638. std::uint16_t len{};
  8639. return get_number(input_format_t::msgpack, len) && get_msgpack_array(static_cast<std::size_t>(len));
  8640. }
  8641. case 0xDD: // array 32
  8642. {
  8643. std::uint32_t len{};
  8644. return get_number(input_format_t::msgpack, len) && get_msgpack_array(static_cast<std::size_t>(len));
  8645. }
  8646. case 0xDE: // map 16
  8647. {
  8648. std::uint16_t len{};
  8649. return get_number(input_format_t::msgpack, len) && get_msgpack_object(static_cast<std::size_t>(len));
  8650. }
  8651. case 0xDF: // map 32
  8652. {
  8653. std::uint32_t len{};
  8654. return get_number(input_format_t::msgpack, len) && get_msgpack_object(static_cast<std::size_t>(len));
  8655. }
  8656. // negative fixint
  8657. case 0xE0:
  8658. case 0xE1:
  8659. case 0xE2:
  8660. case 0xE3:
  8661. case 0xE4:
  8662. case 0xE5:
  8663. case 0xE6:
  8664. case 0xE7:
  8665. case 0xE8:
  8666. case 0xE9:
  8667. case 0xEA:
  8668. case 0xEB:
  8669. case 0xEC:
  8670. case 0xED:
  8671. case 0xEE:
  8672. case 0xEF:
  8673. case 0xF0:
  8674. case 0xF1:
  8675. case 0xF2:
  8676. case 0xF3:
  8677. case 0xF4:
  8678. case 0xF5:
  8679. case 0xF6:
  8680. case 0xF7:
  8681. case 0xF8:
  8682. case 0xF9:
  8683. case 0xFA:
  8684. case 0xFB:
  8685. case 0xFC:
  8686. case 0xFD:
  8687. case 0xFE:
  8688. case 0xFF:
  8689. return sax->number_integer(static_cast<std::int8_t>(current));
  8690. default: // anything else
  8691. {
  8692. auto last_token = get_token_string();
  8693. 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()));
  8694. }
  8695. }
  8696. }
  8697. /*!
  8698. @brief reads a MessagePack string
  8699. This function first reads starting bytes to determine the expected
  8700. string length and then copies this number of bytes into a string.
  8701. @param[out] result created string
  8702. @return whether string creation completed
  8703. */
  8704. bool get_msgpack_string(string_t& result)
  8705. {
  8706. if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(input_format_t::msgpack, "string")))
  8707. {
  8708. return false;
  8709. }
  8710. switch (current)
  8711. {
  8712. // fixstr
  8713. case 0xA0:
  8714. case 0xA1:
  8715. case 0xA2:
  8716. case 0xA3:
  8717. case 0xA4:
  8718. case 0xA5:
  8719. case 0xA6:
  8720. case 0xA7:
  8721. case 0xA8:
  8722. case 0xA9:
  8723. case 0xAA:
  8724. case 0xAB:
  8725. case 0xAC:
  8726. case 0xAD:
  8727. case 0xAE:
  8728. case 0xAF:
  8729. case 0xB0:
  8730. case 0xB1:
  8731. case 0xB2:
  8732. case 0xB3:
  8733. case 0xB4:
  8734. case 0xB5:
  8735. case 0xB6:
  8736. case 0xB7:
  8737. case 0xB8:
  8738. case 0xB9:
  8739. case 0xBA:
  8740. case 0xBB:
  8741. case 0xBC:
  8742. case 0xBD:
  8743. case 0xBE:
  8744. case 0xBF:
  8745. {
  8746. return get_string(input_format_t::msgpack, static_cast<unsigned int>(current) & 0x1Fu, result);
  8747. }
  8748. case 0xD9: // str 8
  8749. {
  8750. std::uint8_t len{};
  8751. return get_number(input_format_t::msgpack, len) && get_string(input_format_t::msgpack, len, result);
  8752. }
  8753. case 0xDA: // str 16
  8754. {
  8755. std::uint16_t len{};
  8756. return get_number(input_format_t::msgpack, len) && get_string(input_format_t::msgpack, len, result);
  8757. }
  8758. case 0xDB: // str 32
  8759. {
  8760. std::uint32_t len{};
  8761. return get_number(input_format_t::msgpack, len) && get_string(input_format_t::msgpack, len, result);
  8762. }
  8763. default:
  8764. {
  8765. auto last_token = get_token_string();
  8766. 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()));
  8767. }
  8768. }
  8769. }
  8770. /*!
  8771. @brief reads a MessagePack byte array
  8772. This function first reads starting bytes to determine the expected
  8773. byte array length and then copies this number of bytes into a byte array.
  8774. @param[out] result created byte array
  8775. @return whether byte array creation completed
  8776. */
  8777. bool get_msgpack_binary(binary_t& result)
  8778. {
  8779. // helper function to set the subtype
  8780. auto assign_and_return_true = [&result](std::int8_t subtype)
  8781. {
  8782. result.set_subtype(static_cast<std::uint8_t>(subtype));
  8783. return true;
  8784. };
  8785. switch (current)
  8786. {
  8787. case 0xC4: // bin 8
  8788. {
  8789. std::uint8_t len{};
  8790. return get_number(input_format_t::msgpack, len) &&
  8791. get_binary(input_format_t::msgpack, len, result);
  8792. }
  8793. case 0xC5: // bin 16
  8794. {
  8795. std::uint16_t len{};
  8796. return get_number(input_format_t::msgpack, len) &&
  8797. get_binary(input_format_t::msgpack, len, result);
  8798. }
  8799. case 0xC6: // bin 32
  8800. {
  8801. std::uint32_t len{};
  8802. return get_number(input_format_t::msgpack, len) &&
  8803. get_binary(input_format_t::msgpack, len, result);
  8804. }
  8805. case 0xC7: // ext 8
  8806. {
  8807. std::uint8_t len{};
  8808. std::int8_t subtype{};
  8809. return get_number(input_format_t::msgpack, len) &&
  8810. get_number(input_format_t::msgpack, subtype) &&
  8811. get_binary(input_format_t::msgpack, len, result) &&
  8812. assign_and_return_true(subtype);
  8813. }
  8814. case 0xC8: // ext 16
  8815. {
  8816. std::uint16_t len{};
  8817. std::int8_t subtype{};
  8818. return get_number(input_format_t::msgpack, len) &&
  8819. get_number(input_format_t::msgpack, subtype) &&
  8820. get_binary(input_format_t::msgpack, len, result) &&
  8821. assign_and_return_true(subtype);
  8822. }
  8823. case 0xC9: // ext 32
  8824. {
  8825. std::uint32_t len{};
  8826. std::int8_t subtype{};
  8827. return get_number(input_format_t::msgpack, len) &&
  8828. get_number(input_format_t::msgpack, subtype) &&
  8829. get_binary(input_format_t::msgpack, len, result) &&
  8830. assign_and_return_true(subtype);
  8831. }
  8832. case 0xD4: // fixext 1
  8833. {
  8834. std::int8_t subtype{};
  8835. return get_number(input_format_t::msgpack, subtype) &&
  8836. get_binary(input_format_t::msgpack, 1, result) &&
  8837. assign_and_return_true(subtype);
  8838. }
  8839. case 0xD5: // fixext 2
  8840. {
  8841. std::int8_t subtype{};
  8842. return get_number(input_format_t::msgpack, subtype) &&
  8843. get_binary(input_format_t::msgpack, 2, result) &&
  8844. assign_and_return_true(subtype);
  8845. }
  8846. case 0xD6: // fixext 4
  8847. {
  8848. std::int8_t subtype{};
  8849. return get_number(input_format_t::msgpack, subtype) &&
  8850. get_binary(input_format_t::msgpack, 4, result) &&
  8851. assign_and_return_true(subtype);
  8852. }
  8853. case 0xD7: // fixext 8
  8854. {
  8855. std::int8_t subtype{};
  8856. return get_number(input_format_t::msgpack, subtype) &&
  8857. get_binary(input_format_t::msgpack, 8, result) &&
  8858. assign_and_return_true(subtype);
  8859. }
  8860. case 0xD8: // fixext 16
  8861. {
  8862. std::int8_t subtype{};
  8863. return get_number(input_format_t::msgpack, subtype) &&
  8864. get_binary(input_format_t::msgpack, 16, result) &&
  8865. assign_and_return_true(subtype);
  8866. }
  8867. default: // LCOV_EXCL_LINE
  8868. return false; // LCOV_EXCL_LINE
  8869. }
  8870. }
  8871. /*!
  8872. @param[in] len the length of the array
  8873. @return whether array creation completed
  8874. */
  8875. bool get_msgpack_array(const std::size_t len)
  8876. {
  8877. if (JSON_HEDLEY_UNLIKELY(!sax->start_array(len)))
  8878. {
  8879. return false;
  8880. }
  8881. for (std::size_t i = 0; i < len; ++i)
  8882. {
  8883. if (JSON_HEDLEY_UNLIKELY(!parse_msgpack_internal()))
  8884. {
  8885. return false;
  8886. }
  8887. }
  8888. return sax->end_array();
  8889. }
  8890. /*!
  8891. @param[in] len the length of the object
  8892. @return whether object creation completed
  8893. */
  8894. bool get_msgpack_object(const std::size_t len)
  8895. {
  8896. if (JSON_HEDLEY_UNLIKELY(!sax->start_object(len)))
  8897. {
  8898. return false;
  8899. }
  8900. string_t key;
  8901. for (std::size_t i = 0; i < len; ++i)
  8902. {
  8903. get();
  8904. if (JSON_HEDLEY_UNLIKELY(!get_msgpack_string(key) || !sax->key(key)))
  8905. {
  8906. return false;
  8907. }
  8908. if (JSON_HEDLEY_UNLIKELY(!parse_msgpack_internal()))
  8909. {
  8910. return false;
  8911. }
  8912. key.clear();
  8913. }
  8914. return sax->end_object();
  8915. }
  8916. ////////////
  8917. // UBJSON //
  8918. ////////////
  8919. /*!
  8920. @param[in] get_char whether a new character should be retrieved from the
  8921. input (true, default) or whether the last read
  8922. character should be considered instead
  8923. @return whether a valid UBJSON value was passed to the SAX parser
  8924. */
  8925. bool parse_ubjson_internal(const bool get_char = true)
  8926. {
  8927. return get_ubjson_value(get_char ? get_ignore_noop() : current);
  8928. }
  8929. /*!
  8930. @brief reads a UBJSON string
  8931. This function is either called after reading the 'S' byte explicitly
  8932. indicating a string, or in case of an object key where the 'S' byte can be
  8933. left out.
  8934. @param[out] result created string
  8935. @param[in] get_char whether a new character should be retrieved from the
  8936. input (true, default) or whether the last read
  8937. character should be considered instead
  8938. @return whether string creation completed
  8939. */
  8940. bool get_ubjson_string(string_t& result, const bool get_char = true)
  8941. {
  8942. if (get_char)
  8943. {
  8944. get(); // TODO(niels): may we ignore N here?
  8945. }
  8946. if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(input_format_t::ubjson, "value")))
  8947. {
  8948. return false;
  8949. }
  8950. switch (current)
  8951. {
  8952. case 'U':
  8953. {
  8954. std::uint8_t len{};
  8955. return get_number(input_format_t::ubjson, len) && get_string(input_format_t::ubjson, len, result);
  8956. }
  8957. case 'i':
  8958. {
  8959. std::int8_t len{};
  8960. return get_number(input_format_t::ubjson, len) && get_string(input_format_t::ubjson, len, result);
  8961. }
  8962. case 'I':
  8963. {
  8964. std::int16_t len{};
  8965. return get_number(input_format_t::ubjson, len) && get_string(input_format_t::ubjson, len, result);
  8966. }
  8967. case 'l':
  8968. {
  8969. std::int32_t len{};
  8970. return get_number(input_format_t::ubjson, len) && get_string(input_format_t::ubjson, len, result);
  8971. }
  8972. case 'L':
  8973. {
  8974. std::int64_t len{};
  8975. return get_number(input_format_t::ubjson, len) && get_string(input_format_t::ubjson, len, result);
  8976. }
  8977. default:
  8978. auto last_token = get_token_string();
  8979. 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()));
  8980. }
  8981. }
  8982. /*!
  8983. @param[out] result determined size
  8984. @return whether size determination completed
  8985. */
  8986. bool get_ubjson_size_value(std::size_t& result)
  8987. {
  8988. switch (get_ignore_noop())
  8989. {
  8990. case 'U':
  8991. {
  8992. std::uint8_t number{};
  8993. if (JSON_HEDLEY_UNLIKELY(!get_number(input_format_t::ubjson, number)))
  8994. {
  8995. return false;
  8996. }
  8997. result = static_cast<std::size_t>(number);
  8998. return true;
  8999. }
  9000. case 'i':
  9001. {
  9002. std::int8_t number{};
  9003. if (JSON_HEDLEY_UNLIKELY(!get_number(input_format_t::ubjson, number)))
  9004. {
  9005. return false;
  9006. }
  9007. result = static_cast<std::size_t>(number); // NOLINT(bugprone-signed-char-misuse,cert-str34-c): number is not a char
  9008. return true;
  9009. }
  9010. case 'I':
  9011. {
  9012. std::int16_t number{};
  9013. if (JSON_HEDLEY_UNLIKELY(!get_number(input_format_t::ubjson, number)))
  9014. {
  9015. return false;
  9016. }
  9017. result = static_cast<std::size_t>(number);
  9018. return true;
  9019. }
  9020. case 'l':
  9021. {
  9022. std::int32_t number{};
  9023. if (JSON_HEDLEY_UNLIKELY(!get_number(input_format_t::ubjson, number)))
  9024. {
  9025. return false;
  9026. }
  9027. result = static_cast<std::size_t>(number);
  9028. return true;
  9029. }
  9030. case 'L':
  9031. {
  9032. std::int64_t number{};
  9033. if (JSON_HEDLEY_UNLIKELY(!get_number(input_format_t::ubjson, number)))
  9034. {
  9035. return false;
  9036. }
  9037. result = static_cast<std::size_t>(number);
  9038. return true;
  9039. }
  9040. default:
  9041. {
  9042. auto last_token = get_token_string();
  9043. 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()));
  9044. }
  9045. }
  9046. }
  9047. /*!
  9048. @brief determine the type and size for a container
  9049. In the optimized UBJSON format, a type and a size can be provided to allow
  9050. for a more compact representation.
  9051. @param[out] result pair of the size and the type
  9052. @return whether pair creation completed
  9053. */
  9054. bool get_ubjson_size_type(std::pair<std::size_t, char_int_type>& result)
  9055. {
  9056. result.first = string_t::npos; // size
  9057. result.second = 0; // type
  9058. get_ignore_noop();
  9059. if (current == '$')
  9060. {
  9061. result.second = get(); // must not ignore 'N', because 'N' maybe the type
  9062. if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(input_format_t::ubjson, "type")))
  9063. {
  9064. return false;
  9065. }
  9066. get_ignore_noop();
  9067. if (JSON_HEDLEY_UNLIKELY(current != '#'))
  9068. {
  9069. if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(input_format_t::ubjson, "value")))
  9070. {
  9071. return false;
  9072. }
  9073. auto last_token = get_token_string();
  9074. 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()));
  9075. }
  9076. return get_ubjson_size_value(result.first);
  9077. }
  9078. if (current == '#')
  9079. {
  9080. return get_ubjson_size_value(result.first);
  9081. }
  9082. return true;
  9083. }
  9084. /*!
  9085. @param prefix the previously read or set type prefix
  9086. @return whether value creation completed
  9087. */
  9088. bool get_ubjson_value(const char_int_type prefix)
  9089. {
  9090. switch (prefix)
  9091. {
  9092. case std::char_traits<char_type>::eof(): // EOF
  9093. return unexpect_eof(input_format_t::ubjson, "value");
  9094. case 'T': // true
  9095. return sax->boolean(true);
  9096. case 'F': // false
  9097. return sax->boolean(false);
  9098. case 'Z': // null
  9099. return sax->null();
  9100. case 'U':
  9101. {
  9102. std::uint8_t number{};
  9103. return get_number(input_format_t::ubjson, number) && sax->number_unsigned(number);
  9104. }
  9105. case 'i':
  9106. {
  9107. std::int8_t number{};
  9108. return get_number(input_format_t::ubjson, number) && sax->number_integer(number);
  9109. }
  9110. case 'I':
  9111. {
  9112. std::int16_t number{};
  9113. return get_number(input_format_t::ubjson, number) && sax->number_integer(number);
  9114. }
  9115. case 'l':
  9116. {
  9117. std::int32_t number{};
  9118. return get_number(input_format_t::ubjson, number) && sax->number_integer(number);
  9119. }
  9120. case 'L':
  9121. {
  9122. std::int64_t number{};
  9123. return get_number(input_format_t::ubjson, number) && sax->number_integer(number);
  9124. }
  9125. case 'd':
  9126. {
  9127. float number{};
  9128. return get_number(input_format_t::ubjson, number) && sax->number_float(static_cast<number_float_t>(number), "");
  9129. }
  9130. case 'D':
  9131. {
  9132. double number{};
  9133. return get_number(input_format_t::ubjson, number) && sax->number_float(static_cast<number_float_t>(number), "");
  9134. }
  9135. case 'H':
  9136. {
  9137. return get_ubjson_high_precision_number();
  9138. }
  9139. case 'C': // char
  9140. {
  9141. get();
  9142. if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(input_format_t::ubjson, "char")))
  9143. {
  9144. return false;
  9145. }
  9146. if (JSON_HEDLEY_UNLIKELY(current > 127))
  9147. {
  9148. auto last_token = get_token_string();
  9149. 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()));
  9150. }
  9151. string_t s(1, static_cast<typename string_t::value_type>(current));
  9152. return sax->string(s);
  9153. }
  9154. case 'S': // string
  9155. {
  9156. string_t s;
  9157. return get_ubjson_string(s) && sax->string(s);
  9158. }
  9159. case '[': // array
  9160. return get_ubjson_array();
  9161. case '{': // object
  9162. return get_ubjson_object();
  9163. default: // anything else
  9164. {
  9165. auto last_token = get_token_string();
  9166. 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()));
  9167. }
  9168. }
  9169. }
  9170. /*!
  9171. @return whether array creation completed
  9172. */
  9173. bool get_ubjson_array()
  9174. {
  9175. std::pair<std::size_t, char_int_type> size_and_type;
  9176. if (JSON_HEDLEY_UNLIKELY(!get_ubjson_size_type(size_and_type)))
  9177. {
  9178. return false;
  9179. }
  9180. if (size_and_type.first != string_t::npos)
  9181. {
  9182. if (JSON_HEDLEY_UNLIKELY(!sax->start_array(size_and_type.first)))
  9183. {
  9184. return false;
  9185. }
  9186. if (size_and_type.second != 0)
  9187. {
  9188. if (size_and_type.second != 'N')
  9189. {
  9190. for (std::size_t i = 0; i < size_and_type.first; ++i)
  9191. {
  9192. if (JSON_HEDLEY_UNLIKELY(!get_ubjson_value(size_and_type.second)))
  9193. {
  9194. return false;
  9195. }
  9196. }
  9197. }
  9198. }
  9199. else
  9200. {
  9201. for (std::size_t i = 0; i < size_and_type.first; ++i)
  9202. {
  9203. if (JSON_HEDLEY_UNLIKELY(!parse_ubjson_internal()))
  9204. {
  9205. return false;
  9206. }
  9207. }
  9208. }
  9209. }
  9210. else
  9211. {
  9212. if (JSON_HEDLEY_UNLIKELY(!sax->start_array(std::size_t(-1))))
  9213. {
  9214. return false;
  9215. }
  9216. while (current != ']')
  9217. {
  9218. if (JSON_HEDLEY_UNLIKELY(!parse_ubjson_internal(false)))
  9219. {
  9220. return false;
  9221. }
  9222. get_ignore_noop();
  9223. }
  9224. }
  9225. return sax->end_array();
  9226. }
  9227. /*!
  9228. @return whether object creation completed
  9229. */
  9230. bool get_ubjson_object()
  9231. {
  9232. std::pair<std::size_t, char_int_type> size_and_type;
  9233. if (JSON_HEDLEY_UNLIKELY(!get_ubjson_size_type(size_and_type)))
  9234. {
  9235. return false;
  9236. }
  9237. string_t key;
  9238. if (size_and_type.first != string_t::npos)
  9239. {
  9240. if (JSON_HEDLEY_UNLIKELY(!sax->start_object(size_and_type.first)))
  9241. {
  9242. return false;
  9243. }
  9244. if (size_and_type.second != 0)
  9245. {
  9246. for (std::size_t i = 0; i < size_and_type.first; ++i)
  9247. {
  9248. if (JSON_HEDLEY_UNLIKELY(!get_ubjson_string(key) || !sax->key(key)))
  9249. {
  9250. return false;
  9251. }
  9252. if (JSON_HEDLEY_UNLIKELY(!get_ubjson_value(size_and_type.second)))
  9253. {
  9254. return false;
  9255. }
  9256. key.clear();
  9257. }
  9258. }
  9259. else
  9260. {
  9261. for (std::size_t i = 0; i < size_and_type.first; ++i)
  9262. {
  9263. if (JSON_HEDLEY_UNLIKELY(!get_ubjson_string(key) || !sax->key(key)))
  9264. {
  9265. return false;
  9266. }
  9267. if (JSON_HEDLEY_UNLIKELY(!parse_ubjson_internal()))
  9268. {
  9269. return false;
  9270. }
  9271. key.clear();
  9272. }
  9273. }
  9274. }
  9275. else
  9276. {
  9277. if (JSON_HEDLEY_UNLIKELY(!sax->start_object(std::size_t(-1))))
  9278. {
  9279. return false;
  9280. }
  9281. while (current != '}')
  9282. {
  9283. if (JSON_HEDLEY_UNLIKELY(!get_ubjson_string(key, false) || !sax->key(key)))
  9284. {
  9285. return false;
  9286. }
  9287. if (JSON_HEDLEY_UNLIKELY(!parse_ubjson_internal()))
  9288. {
  9289. return false;
  9290. }
  9291. get_ignore_noop();
  9292. key.clear();
  9293. }
  9294. }
  9295. return sax->end_object();
  9296. }
  9297. // Note, no reader for UBJSON binary types is implemented because they do
  9298. // not exist
  9299. bool get_ubjson_high_precision_number()
  9300. {
  9301. // get size of following number string
  9302. std::size_t size{};
  9303. auto res = get_ubjson_size_value(size);
  9304. if (JSON_HEDLEY_UNLIKELY(!res))
  9305. {
  9306. return res;
  9307. }
  9308. // get number string
  9309. std::vector<char> number_vector;
  9310. for (std::size_t i = 0; i < size; ++i)
  9311. {
  9312. get();
  9313. if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(input_format_t::ubjson, "number")))
  9314. {
  9315. return false;
  9316. }
  9317. number_vector.push_back(static_cast<char>(current));
  9318. }
  9319. // parse number string
  9320. using ia_type = decltype(detail::input_adapter(number_vector));
  9321. auto number_lexer = detail::lexer<BasicJsonType, ia_type>(detail::input_adapter(number_vector), false);
  9322. const auto result_number = number_lexer.scan();
  9323. const auto number_string = number_lexer.get_token_string();
  9324. const auto result_remainder = number_lexer.scan();
  9325. using token_type = typename detail::lexer_base<BasicJsonType>::token_type;
  9326. if (JSON_HEDLEY_UNLIKELY(result_remainder != token_type::end_of_input))
  9327. {
  9328. 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()));
  9329. }
  9330. switch (result_number)
  9331. {
  9332. case token_type::value_integer:
  9333. return sax->number_integer(number_lexer.get_number_integer());
  9334. case token_type::value_unsigned:
  9335. return sax->number_unsigned(number_lexer.get_number_unsigned());
  9336. case token_type::value_float:
  9337. return sax->number_float(number_lexer.get_number_float(), std::move(number_string));
  9338. case token_type::uninitialized:
  9339. case token_type::literal_true:
  9340. case token_type::literal_false:
  9341. case token_type::literal_null:
  9342. case token_type::value_string:
  9343. case token_type::begin_array:
  9344. case token_type::begin_object:
  9345. case token_type::end_array:
  9346. case token_type::end_object:
  9347. case token_type::name_separator:
  9348. case token_type::value_separator:
  9349. case token_type::parse_error:
  9350. case token_type::end_of_input:
  9351. case token_type::literal_or_value:
  9352. default:
  9353. 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()));
  9354. }
  9355. }
  9356. ///////////////////////
  9357. // Utility functions //
  9358. ///////////////////////
  9359. /*!
  9360. @brief get next character from the input
  9361. This function provides the interface to the used input adapter. It does
  9362. not throw in case the input reached EOF, but returns a -'ve valued
  9363. `std::char_traits<char_type>::eof()` in that case.
  9364. @return character read from the input
  9365. */
  9366. char_int_type get()
  9367. {
  9368. ++chars_read;
  9369. return current = ia.get_character();
  9370. }
  9371. /*!
  9372. @return character read from the input after ignoring all 'N' entries
  9373. */
  9374. char_int_type get_ignore_noop()
  9375. {
  9376. do
  9377. {
  9378. get();
  9379. }
  9380. while (current == 'N');
  9381. return current;
  9382. }
  9383. /*
  9384. @brief read a number from the input
  9385. @tparam NumberType the type of the number
  9386. @param[in] format the current format (for diagnostics)
  9387. @param[out] result number of type @a NumberType
  9388. @return whether conversion completed
  9389. @note This function needs to respect the system's endianess, because
  9390. bytes in CBOR, MessagePack, and UBJSON are stored in network order
  9391. (big endian) and therefore need reordering on little endian systems.
  9392. */
  9393. template<typename NumberType, bool InputIsLittleEndian = false>
  9394. bool get_number(const input_format_t format, NumberType& result)
  9395. {
  9396. // step 1: read input into array with system's byte order
  9397. std::array<std::uint8_t, sizeof(NumberType)> vec{};
  9398. for (std::size_t i = 0; i < sizeof(NumberType); ++i)
  9399. {
  9400. get();
  9401. if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(format, "number")))
  9402. {
  9403. return false;
  9404. }
  9405. // reverse byte order prior to conversion if necessary
  9406. if (is_little_endian != InputIsLittleEndian)
  9407. {
  9408. vec[sizeof(NumberType) - i - 1] = static_cast<std::uint8_t>(current);
  9409. }
  9410. else
  9411. {
  9412. vec[i] = static_cast<std::uint8_t>(current); // LCOV_EXCL_LINE
  9413. }
  9414. }
  9415. // step 2: convert array into number of type T and return
  9416. std::memcpy(&result, vec.data(), sizeof(NumberType));
  9417. return true;
  9418. }
  9419. /*!
  9420. @brief create a string by reading characters from the input
  9421. @tparam NumberType the type of the number
  9422. @param[in] format the current format (for diagnostics)
  9423. @param[in] len number of characters to read
  9424. @param[out] result string created by reading @a len bytes
  9425. @return whether string creation completed
  9426. @note We can not reserve @a len bytes for the result, because @a len
  9427. may be too large. Usually, @ref unexpect_eof() detects the end of
  9428. the input before we run out of string memory.
  9429. */
  9430. template<typename NumberType>
  9431. bool get_string(const input_format_t format,
  9432. const NumberType len,
  9433. string_t& result)
  9434. {
  9435. bool success = true;
  9436. for (NumberType i = 0; i < len; i++)
  9437. {
  9438. get();
  9439. if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(format, "string")))
  9440. {
  9441. success = false;
  9442. break;
  9443. }
  9444. result.push_back(static_cast<typename string_t::value_type>(current));
  9445. }
  9446. return success;
  9447. }
  9448. /*!
  9449. @brief create a byte array by reading bytes from the input
  9450. @tparam NumberType the type of the number
  9451. @param[in] format the current format (for diagnostics)
  9452. @param[in] len number of bytes to read
  9453. @param[out] result byte array created by reading @a len bytes
  9454. @return whether byte array creation completed
  9455. @note We can not reserve @a len bytes for the result, because @a len
  9456. may be too large. Usually, @ref unexpect_eof() detects the end of
  9457. the input before we run out of memory.
  9458. */
  9459. template<typename NumberType>
  9460. bool get_binary(const input_format_t format,
  9461. const NumberType len,
  9462. binary_t& result)
  9463. {
  9464. bool success = true;
  9465. for (NumberType i = 0; i < len; i++)
  9466. {
  9467. get();
  9468. if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(format, "binary")))
  9469. {
  9470. success = false;
  9471. break;
  9472. }
  9473. result.push_back(static_cast<std::uint8_t>(current));
  9474. }
  9475. return success;
  9476. }
  9477. /*!
  9478. @param[in] format the current format (for diagnostics)
  9479. @param[in] context further context information (for diagnostics)
  9480. @return whether the last read character is not EOF
  9481. */
  9482. JSON_HEDLEY_NON_NULL(3)
  9483. bool unexpect_eof(const input_format_t format, const char* context) const
  9484. {
  9485. if (JSON_HEDLEY_UNLIKELY(current == std::char_traits<char_type>::eof()))
  9486. {
  9487. return sax->parse_error(chars_read, "<end of file>",
  9488. parse_error::create(110, chars_read, exception_message(format, "unexpected end of input", context), BasicJsonType()));
  9489. }
  9490. return true;
  9491. }
  9492. /*!
  9493. @return a string representation of the last read byte
  9494. */
  9495. std::string get_token_string() const
  9496. {
  9497. std::array<char, 3> cr{{}};
  9498. (std::snprintf)(cr.data(), cr.size(), "%.2hhX", static_cast<unsigned char>(current)); // NOLINT(cppcoreguidelines-pro-type-vararg,hicpp-vararg)
  9499. return std::string{cr.data()};
  9500. }
  9501. /*!
  9502. @param[in] format the current format
  9503. @param[in] detail a detailed error message
  9504. @param[in] context further context information
  9505. @return a message string to use in the parse_error exceptions
  9506. */
  9507. std::string exception_message(const input_format_t format,
  9508. const std::string& detail,
  9509. const std::string& context) const
  9510. {
  9511. std::string error_msg = "syntax error while parsing ";
  9512. switch (format)
  9513. {
  9514. case input_format_t::cbor:
  9515. error_msg += "CBOR";
  9516. break;
  9517. case input_format_t::msgpack:
  9518. error_msg += "MessagePack";
  9519. break;
  9520. case input_format_t::ubjson:
  9521. error_msg += "UBJSON";
  9522. break;
  9523. case input_format_t::bson:
  9524. error_msg += "BSON";
  9525. break;
  9526. case input_format_t::json: // LCOV_EXCL_LINE
  9527. default: // LCOV_EXCL_LINE
  9528. JSON_ASSERT(false); // NOLINT(cert-dcl03-c,hicpp-static-assert,misc-static-assert) LCOV_EXCL_LINE
  9529. }
  9530. return error_msg + " " + context + ": " + detail;
  9531. }
  9532. private:
  9533. /// input adapter
  9534. InputAdapterType ia;
  9535. /// the current character
  9536. char_int_type current = std::char_traits<char_type>::eof();
  9537. /// the number of characters read
  9538. std::size_t chars_read = 0;
  9539. /// whether we can assume little endianess
  9540. const bool is_little_endian = little_endianess();
  9541. /// the SAX parser
  9542. json_sax_t* sax = nullptr;
  9543. };
  9544. } // namespace detail
  9545. } // namespace nlohmann
  9546. // #include <nlohmann/detail/input/input_adapters.hpp>
  9547. // #include <nlohmann/detail/input/lexer.hpp>
  9548. // #include <nlohmann/detail/input/parser.hpp>
  9549. #include <cmath> // isfinite
  9550. #include <cstdint> // uint8_t
  9551. #include <functional> // function
  9552. #include <string> // string
  9553. #include <utility> // move
  9554. #include <vector> // vector
  9555. // #include <nlohmann/detail/exceptions.hpp>
  9556. // #include <nlohmann/detail/input/input_adapters.hpp>
  9557. // #include <nlohmann/detail/input/json_sax.hpp>
  9558. // #include <nlohmann/detail/input/lexer.hpp>
  9559. // #include <nlohmann/detail/macro_scope.hpp>
  9560. // #include <nlohmann/detail/meta/is_sax.hpp>
  9561. // #include <nlohmann/detail/value_t.hpp>
  9562. namespace nlohmann
  9563. {
  9564. namespace detail
  9565. {
  9566. ////////////
  9567. // parser //
  9568. ////////////
  9569. enum class parse_event_t : std::uint8_t
  9570. {
  9571. /// the parser read `{` and started to process a JSON object
  9572. object_start,
  9573. /// the parser read `}` and finished processing a JSON object
  9574. object_end,
  9575. /// the parser read `[` and started to process a JSON array
  9576. array_start,
  9577. /// the parser read `]` and finished processing a JSON array
  9578. array_end,
  9579. /// the parser read a key of a value in an object
  9580. key,
  9581. /// the parser finished reading a JSON value
  9582. value
  9583. };
  9584. template<typename BasicJsonType>
  9585. using parser_callback_t =
  9586. std::function<bool(int /*depth*/, parse_event_t /*event*/, BasicJsonType& /*parsed*/)>;
  9587. /*!
  9588. @brief syntax analysis
  9589. This class implements a recursive descent parser.
  9590. */
  9591. template<typename BasicJsonType, typename InputAdapterType>
  9592. class parser
  9593. {
  9594. using number_integer_t = typename BasicJsonType::number_integer_t;
  9595. using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
  9596. using number_float_t = typename BasicJsonType::number_float_t;
  9597. using string_t = typename BasicJsonType::string_t;
  9598. using lexer_t = lexer<BasicJsonType, InputAdapterType>;
  9599. using token_type = typename lexer_t::token_type;
  9600. public:
  9601. /// a parser reading from an input adapter
  9602. explicit parser(InputAdapterType&& adapter,
  9603. const parser_callback_t<BasicJsonType> cb = nullptr,
  9604. const bool allow_exceptions_ = true,
  9605. const bool skip_comments = false)
  9606. : callback(cb)
  9607. , m_lexer(std::move(adapter), skip_comments)
  9608. , allow_exceptions(allow_exceptions_)
  9609. {
  9610. // read first token
  9611. get_token();
  9612. }
  9613. /*!
  9614. @brief public parser interface
  9615. @param[in] strict whether to expect the last token to be EOF
  9616. @param[in,out] result parsed JSON value
  9617. @throw parse_error.101 in case of an unexpected token
  9618. @throw parse_error.102 if to_unicode fails or surrogate error
  9619. @throw parse_error.103 if to_unicode fails
  9620. */
  9621. void parse(const bool strict, BasicJsonType& result)
  9622. {
  9623. if (callback)
  9624. {
  9625. json_sax_dom_callback_parser<BasicJsonType> sdp(result, callback, allow_exceptions);
  9626. sax_parse_internal(&sdp);
  9627. // in strict mode, input must be completely read
  9628. if (strict && (get_token() != token_type::end_of_input))
  9629. {
  9630. sdp.parse_error(m_lexer.get_position(),
  9631. m_lexer.get_token_string(),
  9632. parse_error::create(101, m_lexer.get_position(),
  9633. exception_message(token_type::end_of_input, "value"), BasicJsonType()));
  9634. }
  9635. // in case of an error, return discarded value
  9636. if (sdp.is_errored())
  9637. {
  9638. result = value_t::discarded;
  9639. return;
  9640. }
  9641. // set top-level value to null if it was discarded by the callback
  9642. // function
  9643. if (result.is_discarded())
  9644. {
  9645. result = nullptr;
  9646. }
  9647. }
  9648. else
  9649. {
  9650. json_sax_dom_parser<BasicJsonType> sdp(result, allow_exceptions);
  9651. sax_parse_internal(&sdp);
  9652. // in strict mode, input must be completely read
  9653. if (strict && (get_token() != token_type::end_of_input))
  9654. {
  9655. sdp.parse_error(m_lexer.get_position(),
  9656. m_lexer.get_token_string(),
  9657. parse_error::create(101, m_lexer.get_position(), exception_message(token_type::end_of_input, "value"), BasicJsonType()));
  9658. }
  9659. // in case of an error, return discarded value
  9660. if (sdp.is_errored())
  9661. {
  9662. result = value_t::discarded;
  9663. return;
  9664. }
  9665. }
  9666. result.assert_invariant();
  9667. }
  9668. /*!
  9669. @brief public accept interface
  9670. @param[in] strict whether to expect the last token to be EOF
  9671. @return whether the input is a proper JSON text
  9672. */
  9673. bool accept(const bool strict = true)
  9674. {
  9675. json_sax_acceptor<BasicJsonType> sax_acceptor;
  9676. return sax_parse(&sax_acceptor, strict);
  9677. }
  9678. template<typename SAX>
  9679. JSON_HEDLEY_NON_NULL(2)
  9680. bool sax_parse(SAX* sax, const bool strict = true)
  9681. {
  9682. (void)detail::is_sax_static_asserts<SAX, BasicJsonType> {};
  9683. const bool result = sax_parse_internal(sax);
  9684. // strict mode: next byte must be EOF
  9685. if (result && strict && (get_token() != token_type::end_of_input))
  9686. {
  9687. return sax->parse_error(m_lexer.get_position(),
  9688. m_lexer.get_token_string(),
  9689. parse_error::create(101, m_lexer.get_position(), exception_message(token_type::end_of_input, "value"), BasicJsonType()));
  9690. }
  9691. return result;
  9692. }
  9693. private:
  9694. template<typename SAX>
  9695. JSON_HEDLEY_NON_NULL(2)
  9696. bool sax_parse_internal(SAX* sax)
  9697. {
  9698. // stack to remember the hierarchy of structured values we are parsing
  9699. // true = array; false = object
  9700. std::vector<bool> states;
  9701. // value to avoid a goto (see comment where set to true)
  9702. bool skip_to_state_evaluation = false;
  9703. while (true)
  9704. {
  9705. if (!skip_to_state_evaluation)
  9706. {
  9707. // invariant: get_token() was called before each iteration
  9708. switch (last_token)
  9709. {
  9710. case token_type::begin_object:
  9711. {
  9712. if (JSON_HEDLEY_UNLIKELY(!sax->start_object(std::size_t(-1))))
  9713. {
  9714. return false;
  9715. }
  9716. // closing } -> we are done
  9717. if (get_token() == token_type::end_object)
  9718. {
  9719. if (JSON_HEDLEY_UNLIKELY(!sax->end_object()))
  9720. {
  9721. return false;
  9722. }
  9723. break;
  9724. }
  9725. // parse key
  9726. if (JSON_HEDLEY_UNLIKELY(last_token != token_type::value_string))
  9727. {
  9728. return sax->parse_error(m_lexer.get_position(),
  9729. m_lexer.get_token_string(),
  9730. parse_error::create(101, m_lexer.get_position(), exception_message(token_type::value_string, "object key"), BasicJsonType()));
  9731. }
  9732. if (JSON_HEDLEY_UNLIKELY(!sax->key(m_lexer.get_string())))
  9733. {
  9734. return false;
  9735. }
  9736. // parse separator (:)
  9737. if (JSON_HEDLEY_UNLIKELY(get_token() != token_type::name_separator))
  9738. {
  9739. return sax->parse_error(m_lexer.get_position(),
  9740. m_lexer.get_token_string(),
  9741. parse_error::create(101, m_lexer.get_position(), exception_message(token_type::name_separator, "object separator"), BasicJsonType()));
  9742. }
  9743. // remember we are now inside an object
  9744. states.push_back(false);
  9745. // parse values
  9746. get_token();
  9747. continue;
  9748. }
  9749. case token_type::begin_array:
  9750. {
  9751. if (JSON_HEDLEY_UNLIKELY(!sax->start_array(std::size_t(-1))))
  9752. {
  9753. return false;
  9754. }
  9755. // closing ] -> we are done
  9756. if (get_token() == token_type::end_array)
  9757. {
  9758. if (JSON_HEDLEY_UNLIKELY(!sax->end_array()))
  9759. {
  9760. return false;
  9761. }
  9762. break;
  9763. }
  9764. // remember we are now inside an array
  9765. states.push_back(true);
  9766. // parse values (no need to call get_token)
  9767. continue;
  9768. }
  9769. case token_type::value_float:
  9770. {
  9771. const auto res = m_lexer.get_number_float();
  9772. if (JSON_HEDLEY_UNLIKELY(!std::isfinite(res)))
  9773. {
  9774. return sax->parse_error(m_lexer.get_position(),
  9775. m_lexer.get_token_string(),
  9776. out_of_range::create(406, "number overflow parsing '" + m_lexer.get_token_string() + "'", BasicJsonType()));
  9777. }
  9778. if (JSON_HEDLEY_UNLIKELY(!sax->number_float(res, m_lexer.get_string())))
  9779. {
  9780. return false;
  9781. }
  9782. break;
  9783. }
  9784. case token_type::literal_false:
  9785. {
  9786. if (JSON_HEDLEY_UNLIKELY(!sax->boolean(false)))
  9787. {
  9788. return false;
  9789. }
  9790. break;
  9791. }
  9792. case token_type::literal_null:
  9793. {
  9794. if (JSON_HEDLEY_UNLIKELY(!sax->null()))
  9795. {
  9796. return false;
  9797. }
  9798. break;
  9799. }
  9800. case token_type::literal_true:
  9801. {
  9802. if (JSON_HEDLEY_UNLIKELY(!sax->boolean(true)))
  9803. {
  9804. return false;
  9805. }
  9806. break;
  9807. }
  9808. case token_type::value_integer:
  9809. {
  9810. if (JSON_HEDLEY_UNLIKELY(!sax->number_integer(m_lexer.get_number_integer())))
  9811. {
  9812. return false;
  9813. }
  9814. break;
  9815. }
  9816. case token_type::value_string:
  9817. {
  9818. if (JSON_HEDLEY_UNLIKELY(!sax->string(m_lexer.get_string())))
  9819. {
  9820. return false;
  9821. }
  9822. break;
  9823. }
  9824. case token_type::value_unsigned:
  9825. {
  9826. if (JSON_HEDLEY_UNLIKELY(!sax->number_unsigned(m_lexer.get_number_unsigned())))
  9827. {
  9828. return false;
  9829. }
  9830. break;
  9831. }
  9832. case token_type::parse_error:
  9833. {
  9834. // using "uninitialized" to avoid "expected" message
  9835. return sax->parse_error(m_lexer.get_position(),
  9836. m_lexer.get_token_string(),
  9837. parse_error::create(101, m_lexer.get_position(), exception_message(token_type::uninitialized, "value"), BasicJsonType()));
  9838. }
  9839. case token_type::uninitialized:
  9840. case token_type::end_array:
  9841. case token_type::end_object:
  9842. case token_type::name_separator:
  9843. case token_type::value_separator:
  9844. case token_type::end_of_input:
  9845. case token_type::literal_or_value:
  9846. default: // the last token was unexpected
  9847. {
  9848. return sax->parse_error(m_lexer.get_position(),
  9849. m_lexer.get_token_string(),
  9850. parse_error::create(101, m_lexer.get_position(), exception_message(token_type::literal_or_value, "value"), BasicJsonType()));
  9851. }
  9852. }
  9853. }
  9854. else
  9855. {
  9856. skip_to_state_evaluation = false;
  9857. }
  9858. // we reached this line after we successfully parsed a value
  9859. if (states.empty())
  9860. {
  9861. // empty stack: we reached the end of the hierarchy: done
  9862. return true;
  9863. }
  9864. if (states.back()) // array
  9865. {
  9866. // comma -> next value
  9867. if (get_token() == token_type::value_separator)
  9868. {
  9869. // parse a new value
  9870. get_token();
  9871. continue;
  9872. }
  9873. // closing ]
  9874. if (JSON_HEDLEY_LIKELY(last_token == token_type::end_array))
  9875. {
  9876. if (JSON_HEDLEY_UNLIKELY(!sax->end_array()))
  9877. {
  9878. return false;
  9879. }
  9880. // We are done with this array. Before we can parse a
  9881. // new value, we need to evaluate the new state first.
  9882. // By setting skip_to_state_evaluation to false, we
  9883. // are effectively jumping to the beginning of this if.
  9884. JSON_ASSERT(!states.empty());
  9885. states.pop_back();
  9886. skip_to_state_evaluation = true;
  9887. continue;
  9888. }
  9889. return sax->parse_error(m_lexer.get_position(),
  9890. m_lexer.get_token_string(),
  9891. parse_error::create(101, m_lexer.get_position(), exception_message(token_type::end_array, "array"), BasicJsonType()));
  9892. }
  9893. // states.back() is false -> object
  9894. // comma -> next value
  9895. if (get_token() == token_type::value_separator)
  9896. {
  9897. // parse key
  9898. if (JSON_HEDLEY_UNLIKELY(get_token() != token_type::value_string))
  9899. {
  9900. return sax->parse_error(m_lexer.get_position(),
  9901. m_lexer.get_token_string(),
  9902. parse_error::create(101, m_lexer.get_position(), exception_message(token_type::value_string, "object key"), BasicJsonType()));
  9903. }
  9904. if (JSON_HEDLEY_UNLIKELY(!sax->key(m_lexer.get_string())))
  9905. {
  9906. return false;
  9907. }
  9908. // parse separator (:)
  9909. if (JSON_HEDLEY_UNLIKELY(get_token() != token_type::name_separator))
  9910. {
  9911. return sax->parse_error(m_lexer.get_position(),
  9912. m_lexer.get_token_string(),
  9913. parse_error::create(101, m_lexer.get_position(), exception_message(token_type::name_separator, "object separator"), BasicJsonType()));
  9914. }
  9915. // parse values
  9916. get_token();
  9917. continue;
  9918. }
  9919. // closing }
  9920. if (JSON_HEDLEY_LIKELY(last_token == token_type::end_object))
  9921. {
  9922. if (JSON_HEDLEY_UNLIKELY(!sax->end_object()))
  9923. {
  9924. return false;
  9925. }
  9926. // We are done with this object. Before we can parse a
  9927. // new value, we need to evaluate the new state first.
  9928. // By setting skip_to_state_evaluation to false, we
  9929. // are effectively jumping to the beginning of this if.
  9930. JSON_ASSERT(!states.empty());
  9931. states.pop_back();
  9932. skip_to_state_evaluation = true;
  9933. continue;
  9934. }
  9935. return sax->parse_error(m_lexer.get_position(),
  9936. m_lexer.get_token_string(),
  9937. parse_error::create(101, m_lexer.get_position(), exception_message(token_type::end_object, "object"), BasicJsonType()));
  9938. }
  9939. }
  9940. /// get next token from lexer
  9941. token_type get_token()
  9942. {
  9943. return last_token = m_lexer.scan();
  9944. }
  9945. std::string exception_message(const token_type expected, const std::string& context)
  9946. {
  9947. std::string error_msg = "syntax error ";
  9948. if (!context.empty())
  9949. {
  9950. error_msg += "while parsing " + context + " ";
  9951. }
  9952. error_msg += "- ";
  9953. if (last_token == token_type::parse_error)
  9954. {
  9955. error_msg += std::string(m_lexer.get_error_message()) + "; last read: '" +
  9956. m_lexer.get_token_string() + "'";
  9957. }
  9958. else
  9959. {
  9960. error_msg += "unexpected " + std::string(lexer_t::token_type_name(last_token));
  9961. }
  9962. if (expected != token_type::uninitialized)
  9963. {
  9964. error_msg += "; expected " + std::string(lexer_t::token_type_name(expected));
  9965. }
  9966. return error_msg;
  9967. }
  9968. private:
  9969. /// callback function
  9970. const parser_callback_t<BasicJsonType> callback = nullptr;
  9971. /// the type of the last read token
  9972. token_type last_token = token_type::uninitialized;
  9973. /// the lexer
  9974. lexer_t m_lexer;
  9975. /// whether to throw exceptions in case of errors
  9976. const bool allow_exceptions = true;
  9977. };
  9978. } // namespace detail
  9979. } // namespace nlohmann
  9980. // #include <nlohmann/detail/iterators/internal_iterator.hpp>
  9981. // #include <nlohmann/detail/iterators/primitive_iterator.hpp>
  9982. #include <cstddef> // ptrdiff_t
  9983. #include <limits> // numeric_limits
  9984. // #include <nlohmann/detail/macro_scope.hpp>
  9985. namespace nlohmann
  9986. {
  9987. namespace detail
  9988. {
  9989. /*
  9990. @brief an iterator for primitive JSON types
  9991. This class models an iterator for primitive JSON types (boolean, number,
  9992. string). It's only purpose is to allow the iterator/const_iterator classes
  9993. to "iterate" over primitive values. Internally, the iterator is modeled by
  9994. a `difference_type` variable. Value begin_value (`0`) models the begin,
  9995. end_value (`1`) models past the end.
  9996. */
  9997. class primitive_iterator_t
  9998. {
  9999. private:
  10000. using difference_type = std::ptrdiff_t;
  10001. static constexpr difference_type begin_value = 0;
  10002. static constexpr difference_type end_value = begin_value + 1;
  10003. JSON_PRIVATE_UNLESS_TESTED:
  10004. /// iterator as signed integer type
  10005. difference_type m_it = (std::numeric_limits<std::ptrdiff_t>::min)();
  10006. public:
  10007. constexpr difference_type get_value() const noexcept
  10008. {
  10009. return m_it;
  10010. }
  10011. /// set iterator to a defined beginning
  10012. void set_begin() noexcept
  10013. {
  10014. m_it = begin_value;
  10015. }
  10016. /// set iterator to a defined past the end
  10017. void set_end() noexcept
  10018. {
  10019. m_it = end_value;
  10020. }
  10021. /// return whether the iterator can be dereferenced
  10022. constexpr bool is_begin() const noexcept
  10023. {
  10024. return m_it == begin_value;
  10025. }
  10026. /// return whether the iterator is at end
  10027. constexpr bool is_end() const noexcept
  10028. {
  10029. return m_it == end_value;
  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. friend constexpr bool operator<(primitive_iterator_t lhs, primitive_iterator_t rhs) noexcept
  10036. {
  10037. return lhs.m_it < rhs.m_it;
  10038. }
  10039. primitive_iterator_t operator+(difference_type n) noexcept
  10040. {
  10041. auto result = *this;
  10042. result += n;
  10043. return result;
  10044. }
  10045. friend constexpr difference_type operator-(primitive_iterator_t lhs, primitive_iterator_t rhs) noexcept
  10046. {
  10047. return lhs.m_it - rhs.m_it;
  10048. }
  10049. primitive_iterator_t& operator++() noexcept
  10050. {
  10051. ++m_it;
  10052. return *this;
  10053. }
  10054. primitive_iterator_t const operator++(int) noexcept // NOLINT(readability-const-return-type)
  10055. {
  10056. auto result = *this;
  10057. ++m_it;
  10058. return result;
  10059. }
  10060. primitive_iterator_t& operator--() noexcept
  10061. {
  10062. --m_it;
  10063. return *this;
  10064. }
  10065. primitive_iterator_t const operator--(int) noexcept // NOLINT(readability-const-return-type)
  10066. {
  10067. auto result = *this;
  10068. --m_it;
  10069. return result;
  10070. }
  10071. primitive_iterator_t& operator+=(difference_type n) noexcept
  10072. {
  10073. m_it += n;
  10074. return *this;
  10075. }
  10076. primitive_iterator_t& operator-=(difference_type n) noexcept
  10077. {
  10078. m_it -= n;
  10079. return *this;
  10080. }
  10081. };
  10082. } // namespace detail
  10083. } // namespace nlohmann
  10084. namespace nlohmann
  10085. {
  10086. namespace detail
  10087. {
  10088. /*!
  10089. @brief an iterator value
  10090. @note This structure could easily be a union, but MSVC currently does not allow
  10091. unions members with complex constructors, see https://github.com/nlohmann/json/pull/105.
  10092. */
  10093. template<typename BasicJsonType> struct internal_iterator
  10094. {
  10095. /// iterator for JSON objects
  10096. typename BasicJsonType::object_t::iterator object_iterator {};
  10097. /// iterator for JSON arrays
  10098. typename BasicJsonType::array_t::iterator array_iterator {};
  10099. /// generic iterator for all other types
  10100. primitive_iterator_t primitive_iterator {};
  10101. };
  10102. } // namespace detail
  10103. } // namespace nlohmann
  10104. // #include <nlohmann/detail/iterators/iter_impl.hpp>
  10105. #include <iterator> // iterator, random_access_iterator_tag, bidirectional_iterator_tag, advance, next
  10106. #include <type_traits> // conditional, is_const, remove_const
  10107. // #include <nlohmann/detail/exceptions.hpp>
  10108. // #include <nlohmann/detail/iterators/internal_iterator.hpp>
  10109. // #include <nlohmann/detail/iterators/primitive_iterator.hpp>
  10110. // #include <nlohmann/detail/macro_scope.hpp>
  10111. // #include <nlohmann/detail/meta/cpp_future.hpp>
  10112. // #include <nlohmann/detail/meta/type_traits.hpp>
  10113. // #include <nlohmann/detail/value_t.hpp>
  10114. namespace nlohmann
  10115. {
  10116. namespace detail
  10117. {
  10118. // forward declare, to be able to friend it later on
  10119. template<typename IteratorType> class iteration_proxy;
  10120. template<typename IteratorType> class iteration_proxy_value;
  10121. /*!
  10122. @brief a template for a bidirectional iterator for the @ref basic_json class
  10123. This class implements a both iterators (iterator and const_iterator) for the
  10124. @ref basic_json class.
  10125. @note An iterator is called *initialized* when a pointer to a JSON value has
  10126. been set (e.g., by a constructor or a copy assignment). If the iterator is
  10127. default-constructed, it is *uninitialized* and most methods are undefined.
  10128. **The library uses assertions to detect calls on uninitialized iterators.**
  10129. @requirement The class satisfies the following concept requirements:
  10130. -
  10131. [BidirectionalIterator](https://en.cppreference.com/w/cpp/named_req/BidirectionalIterator):
  10132. The iterator that can be moved can be moved in both directions (i.e.
  10133. incremented and decremented).
  10134. @since version 1.0.0, simplified in version 2.0.9, change to bidirectional
  10135. iterators in version 3.0.0 (see https://github.com/nlohmann/json/issues/593)
  10136. */
  10137. template<typename BasicJsonType>
  10138. class iter_impl
  10139. {
  10140. /// the iterator with BasicJsonType of different const-ness
  10141. using other_iter_impl = iter_impl<typename std::conditional<std::is_const<BasicJsonType>::value, typename std::remove_const<BasicJsonType>::type, const BasicJsonType>::type>;
  10142. /// allow basic_json to access private members
  10143. friend other_iter_impl;
  10144. friend BasicJsonType;
  10145. friend iteration_proxy<iter_impl>;
  10146. friend iteration_proxy_value<iter_impl>;
  10147. using object_t = typename BasicJsonType::object_t;
  10148. using array_t = typename BasicJsonType::array_t;
  10149. // make sure BasicJsonType is basic_json or const basic_json
  10150. static_assert(is_basic_json<typename std::remove_const<BasicJsonType>::type>::value,
  10151. "iter_impl only accepts (const) basic_json");
  10152. public:
  10153. /// The std::iterator class template (used as a base class to provide typedefs) is deprecated in C++17.
  10154. /// The C++ Standard has never required user-defined iterators to derive from std::iterator.
  10155. /// A user-defined iterator should provide publicly accessible typedefs named
  10156. /// iterator_category, value_type, difference_type, pointer, and reference.
  10157. /// Note that value_type is required to be non-const, even for constant iterators.
  10158. using iterator_category = std::bidirectional_iterator_tag;
  10159. /// the type of the values when the iterator is dereferenced
  10160. using value_type = typename BasicJsonType::value_type;
  10161. /// a type to represent differences between iterators
  10162. using difference_type = typename BasicJsonType::difference_type;
  10163. /// defines a pointer to the type iterated over (value_type)
  10164. using pointer = typename std::conditional<std::is_const<BasicJsonType>::value,
  10165. typename BasicJsonType::const_pointer,
  10166. typename BasicJsonType::pointer>::type;
  10167. /// defines a reference to the type iterated over (value_type)
  10168. using reference =
  10169. typename std::conditional<std::is_const<BasicJsonType>::value,
  10170. typename BasicJsonType::const_reference,
  10171. typename BasicJsonType::reference>::type;
  10172. iter_impl() = default;
  10173. ~iter_impl() = default;
  10174. iter_impl(iter_impl&&) noexcept = default;
  10175. iter_impl& operator=(iter_impl&&) noexcept = default;
  10176. /*!
  10177. @brief constructor for a given JSON instance
  10178. @param[in] object pointer to a JSON object for this iterator
  10179. @pre object != nullptr
  10180. @post The iterator is initialized; i.e. `m_object != nullptr`.
  10181. */
  10182. explicit iter_impl(pointer object) noexcept : m_object(object)
  10183. {
  10184. JSON_ASSERT(m_object != nullptr);
  10185. switch (m_object->m_type)
  10186. {
  10187. case value_t::object:
  10188. {
  10189. m_it.object_iterator = typename object_t::iterator();
  10190. break;
  10191. }
  10192. case value_t::array:
  10193. {
  10194. m_it.array_iterator = typename array_t::iterator();
  10195. break;
  10196. }
  10197. case value_t::null:
  10198. case value_t::string:
  10199. case value_t::boolean:
  10200. case value_t::number_integer:
  10201. case value_t::number_unsigned:
  10202. case value_t::number_float:
  10203. case value_t::binary:
  10204. case value_t::discarded:
  10205. default:
  10206. {
  10207. m_it.primitive_iterator = primitive_iterator_t();
  10208. break;
  10209. }
  10210. }
  10211. }
  10212. /*!
  10213. @note The conventional copy constructor and copy assignment are implicitly
  10214. defined. Combined with the following converting constructor and
  10215. assignment, they support: (1) copy from iterator to iterator, (2)
  10216. copy from const iterator to const iterator, and (3) conversion from
  10217. iterator to const iterator. However conversion from const iterator
  10218. to iterator is not defined.
  10219. */
  10220. /*!
  10221. @brief const copy constructor
  10222. @param[in] other const iterator to copy from
  10223. @note This copy constructor had to be defined explicitly to circumvent a bug
  10224. occurring on msvc v19.0 compiler (VS 2015) debug build. For more
  10225. information refer to: https://github.com/nlohmann/json/issues/1608
  10226. */
  10227. iter_impl(const iter_impl<const BasicJsonType>& other) noexcept
  10228. : m_object(other.m_object), m_it(other.m_it)
  10229. {}
  10230. /*!
  10231. @brief converting assignment
  10232. @param[in] other const iterator to copy from
  10233. @return const/non-const iterator
  10234. @note It is not checked whether @a other is initialized.
  10235. */
  10236. iter_impl& operator=(const iter_impl<const BasicJsonType>& other) noexcept
  10237. {
  10238. if (&other != this)
  10239. {
  10240. m_object = other.m_object;
  10241. m_it = other.m_it;
  10242. }
  10243. return *this;
  10244. }
  10245. /*!
  10246. @brief converting constructor
  10247. @param[in] other non-const iterator to copy from
  10248. @note It is not checked whether @a other is initialized.
  10249. */
  10250. iter_impl(const iter_impl<typename std::remove_const<BasicJsonType>::type>& other) noexcept
  10251. : m_object(other.m_object), m_it(other.m_it)
  10252. {}
  10253. /*!
  10254. @brief converting assignment
  10255. @param[in] other non-const iterator to copy from
  10256. @return const/non-const iterator
  10257. @note It is not checked whether @a other is initialized.
  10258. */
  10259. iter_impl& operator=(const iter_impl<typename std::remove_const<BasicJsonType>::type>& other) noexcept // NOLINT(cert-oop54-cpp)
  10260. {
  10261. m_object = other.m_object;
  10262. m_it = other.m_it;
  10263. return *this;
  10264. }
  10265. JSON_PRIVATE_UNLESS_TESTED:
  10266. /*!
  10267. @brief set the iterator to the first value
  10268. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  10269. */
  10270. void set_begin() noexcept
  10271. {
  10272. JSON_ASSERT(m_object != nullptr);
  10273. switch (m_object->m_type)
  10274. {
  10275. case value_t::object:
  10276. {
  10277. m_it.object_iterator = m_object->m_value.object->begin();
  10278. break;
  10279. }
  10280. case value_t::array:
  10281. {
  10282. m_it.array_iterator = m_object->m_value.array->begin();
  10283. break;
  10284. }
  10285. case value_t::null:
  10286. {
  10287. // set to end so begin()==end() is true: null is empty
  10288. m_it.primitive_iterator.set_end();
  10289. break;
  10290. }
  10291. case value_t::string:
  10292. case value_t::boolean:
  10293. case value_t::number_integer:
  10294. case value_t::number_unsigned:
  10295. case value_t::number_float:
  10296. case value_t::binary:
  10297. case value_t::discarded:
  10298. default:
  10299. {
  10300. m_it.primitive_iterator.set_begin();
  10301. break;
  10302. }
  10303. }
  10304. }
  10305. /*!
  10306. @brief set the iterator past the last value
  10307. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  10308. */
  10309. void set_end() noexcept
  10310. {
  10311. JSON_ASSERT(m_object != nullptr);
  10312. switch (m_object->m_type)
  10313. {
  10314. case value_t::object:
  10315. {
  10316. m_it.object_iterator = m_object->m_value.object->end();
  10317. break;
  10318. }
  10319. case value_t::array:
  10320. {
  10321. m_it.array_iterator = m_object->m_value.array->end();
  10322. break;
  10323. }
  10324. case value_t::null:
  10325. case value_t::string:
  10326. case value_t::boolean:
  10327. case value_t::number_integer:
  10328. case value_t::number_unsigned:
  10329. case value_t::number_float:
  10330. case value_t::binary:
  10331. case value_t::discarded:
  10332. default:
  10333. {
  10334. m_it.primitive_iterator.set_end();
  10335. break;
  10336. }
  10337. }
  10338. }
  10339. public:
  10340. /*!
  10341. @brief return a reference to the value pointed to by the iterator
  10342. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  10343. */
  10344. reference operator*() const
  10345. {
  10346. JSON_ASSERT(m_object != nullptr);
  10347. switch (m_object->m_type)
  10348. {
  10349. case value_t::object:
  10350. {
  10351. JSON_ASSERT(m_it.object_iterator != m_object->m_value.object->end());
  10352. return m_it.object_iterator->second;
  10353. }
  10354. case value_t::array:
  10355. {
  10356. JSON_ASSERT(m_it.array_iterator != m_object->m_value.array->end());
  10357. return *m_it.array_iterator;
  10358. }
  10359. case value_t::null:
  10360. JSON_THROW(invalid_iterator::create(214, "cannot get value", *m_object));
  10361. case value_t::string:
  10362. case value_t::boolean:
  10363. case value_t::number_integer:
  10364. case value_t::number_unsigned:
  10365. case value_t::number_float:
  10366. case value_t::binary:
  10367. case value_t::discarded:
  10368. default:
  10369. {
  10370. if (JSON_HEDLEY_LIKELY(m_it.primitive_iterator.is_begin()))
  10371. {
  10372. return *m_object;
  10373. }
  10374. JSON_THROW(invalid_iterator::create(214, "cannot get value", *m_object));
  10375. }
  10376. }
  10377. }
  10378. /*!
  10379. @brief dereference the iterator
  10380. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  10381. */
  10382. pointer operator->() const
  10383. {
  10384. JSON_ASSERT(m_object != nullptr);
  10385. switch (m_object->m_type)
  10386. {
  10387. case value_t::object:
  10388. {
  10389. JSON_ASSERT(m_it.object_iterator != m_object->m_value.object->end());
  10390. return &(m_it.object_iterator->second);
  10391. }
  10392. case value_t::array:
  10393. {
  10394. JSON_ASSERT(m_it.array_iterator != m_object->m_value.array->end());
  10395. return &*m_it.array_iterator;
  10396. }
  10397. case value_t::null:
  10398. case value_t::string:
  10399. case value_t::boolean:
  10400. case value_t::number_integer:
  10401. case value_t::number_unsigned:
  10402. case value_t::number_float:
  10403. case value_t::binary:
  10404. case value_t::discarded:
  10405. default:
  10406. {
  10407. if (JSON_HEDLEY_LIKELY(m_it.primitive_iterator.is_begin()))
  10408. {
  10409. return m_object;
  10410. }
  10411. JSON_THROW(invalid_iterator::create(214, "cannot get value", *m_object));
  10412. }
  10413. }
  10414. }
  10415. /*!
  10416. @brief post-increment (it++)
  10417. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  10418. */
  10419. iter_impl const operator++(int) // NOLINT(readability-const-return-type)
  10420. {
  10421. auto result = *this;
  10422. ++(*this);
  10423. return result;
  10424. }
  10425. /*!
  10426. @brief pre-increment (++it)
  10427. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  10428. */
  10429. iter_impl& operator++()
  10430. {
  10431. JSON_ASSERT(m_object != nullptr);
  10432. switch (m_object->m_type)
  10433. {
  10434. case value_t::object:
  10435. {
  10436. std::advance(m_it.object_iterator, 1);
  10437. break;
  10438. }
  10439. case value_t::array:
  10440. {
  10441. std::advance(m_it.array_iterator, 1);
  10442. break;
  10443. }
  10444. case value_t::null:
  10445. case value_t::string:
  10446. case value_t::boolean:
  10447. case value_t::number_integer:
  10448. case value_t::number_unsigned:
  10449. case value_t::number_float:
  10450. case value_t::binary:
  10451. case value_t::discarded:
  10452. default:
  10453. {
  10454. ++m_it.primitive_iterator;
  10455. break;
  10456. }
  10457. }
  10458. return *this;
  10459. }
  10460. /*!
  10461. @brief post-decrement (it--)
  10462. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  10463. */
  10464. iter_impl const operator--(int) // NOLINT(readability-const-return-type)
  10465. {
  10466. auto result = *this;
  10467. --(*this);
  10468. return result;
  10469. }
  10470. /*!
  10471. @brief pre-decrement (--it)
  10472. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  10473. */
  10474. iter_impl& operator--()
  10475. {
  10476. JSON_ASSERT(m_object != nullptr);
  10477. switch (m_object->m_type)
  10478. {
  10479. case value_t::object:
  10480. {
  10481. std::advance(m_it.object_iterator, -1);
  10482. break;
  10483. }
  10484. case value_t::array:
  10485. {
  10486. std::advance(m_it.array_iterator, -1);
  10487. break;
  10488. }
  10489. case value_t::null:
  10490. case value_t::string:
  10491. case value_t::boolean:
  10492. case value_t::number_integer:
  10493. case value_t::number_unsigned:
  10494. case value_t::number_float:
  10495. case value_t::binary:
  10496. case value_t::discarded:
  10497. default:
  10498. {
  10499. --m_it.primitive_iterator;
  10500. break;
  10501. }
  10502. }
  10503. return *this;
  10504. }
  10505. /*!
  10506. @brief comparison: equal
  10507. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  10508. */
  10509. 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 >
  10510. bool operator==(const IterImpl& other) const
  10511. {
  10512. // if objects are not the same, the comparison is undefined
  10513. if (JSON_HEDLEY_UNLIKELY(m_object != other.m_object))
  10514. {
  10515. JSON_THROW(invalid_iterator::create(212, "cannot compare iterators of different containers", *m_object));
  10516. }
  10517. JSON_ASSERT(m_object != nullptr);
  10518. switch (m_object->m_type)
  10519. {
  10520. case value_t::object:
  10521. return (m_it.object_iterator == other.m_it.object_iterator);
  10522. case value_t::array:
  10523. return (m_it.array_iterator == other.m_it.array_iterator);
  10524. case value_t::null:
  10525. case value_t::string:
  10526. case value_t::boolean:
  10527. case value_t::number_integer:
  10528. case value_t::number_unsigned:
  10529. case value_t::number_float:
  10530. case value_t::binary:
  10531. case value_t::discarded:
  10532. default:
  10533. return (m_it.primitive_iterator == other.m_it.primitive_iterator);
  10534. }
  10535. }
  10536. /*!
  10537. @brief comparison: not equal
  10538. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  10539. */
  10540. 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 >
  10541. bool operator!=(const IterImpl& other) const
  10542. {
  10543. return !operator==(other);
  10544. }
  10545. /*!
  10546. @brief comparison: smaller
  10547. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  10548. */
  10549. bool operator<(const iter_impl& other) const
  10550. {
  10551. // if objects are not the same, the comparison is undefined
  10552. if (JSON_HEDLEY_UNLIKELY(m_object != other.m_object))
  10553. {
  10554. JSON_THROW(invalid_iterator::create(212, "cannot compare iterators of different containers", *m_object));
  10555. }
  10556. JSON_ASSERT(m_object != nullptr);
  10557. switch (m_object->m_type)
  10558. {
  10559. case value_t::object:
  10560. JSON_THROW(invalid_iterator::create(213, "cannot compare order of object iterators", *m_object));
  10561. case value_t::array:
  10562. return (m_it.array_iterator < other.m_it.array_iterator);
  10563. case value_t::null:
  10564. case value_t::string:
  10565. case value_t::boolean:
  10566. case value_t::number_integer:
  10567. case value_t::number_unsigned:
  10568. case value_t::number_float:
  10569. case value_t::binary:
  10570. case value_t::discarded:
  10571. default:
  10572. return (m_it.primitive_iterator < other.m_it.primitive_iterator);
  10573. }
  10574. }
  10575. /*!
  10576. @brief comparison: less than or equal
  10577. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  10578. */
  10579. bool operator<=(const iter_impl& other) const
  10580. {
  10581. return !other.operator < (*this);
  10582. }
  10583. /*!
  10584. @brief comparison: greater than
  10585. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  10586. */
  10587. bool operator>(const iter_impl& other) const
  10588. {
  10589. return !operator<=(other);
  10590. }
  10591. /*!
  10592. @brief comparison: greater than or equal
  10593. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  10594. */
  10595. bool operator>=(const iter_impl& other) const
  10596. {
  10597. return !operator<(other);
  10598. }
  10599. /*!
  10600. @brief add to iterator
  10601. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  10602. */
  10603. iter_impl& operator+=(difference_type i)
  10604. {
  10605. JSON_ASSERT(m_object != nullptr);
  10606. switch (m_object->m_type)
  10607. {
  10608. case value_t::object:
  10609. JSON_THROW(invalid_iterator::create(209, "cannot use offsets with object iterators", *m_object));
  10610. case value_t::array:
  10611. {
  10612. std::advance(m_it.array_iterator, i);
  10613. break;
  10614. }
  10615. case value_t::null:
  10616. case value_t::string:
  10617. case value_t::boolean:
  10618. case value_t::number_integer:
  10619. case value_t::number_unsigned:
  10620. case value_t::number_float:
  10621. case value_t::binary:
  10622. case value_t::discarded:
  10623. default:
  10624. {
  10625. m_it.primitive_iterator += i;
  10626. break;
  10627. }
  10628. }
  10629. return *this;
  10630. }
  10631. /*!
  10632. @brief subtract from iterator
  10633. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  10634. */
  10635. iter_impl& operator-=(difference_type i)
  10636. {
  10637. return operator+=(-i);
  10638. }
  10639. /*!
  10640. @brief add to iterator
  10641. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  10642. */
  10643. iter_impl operator+(difference_type i) const
  10644. {
  10645. auto result = *this;
  10646. result += i;
  10647. return result;
  10648. }
  10649. /*!
  10650. @brief addition of distance and iterator
  10651. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  10652. */
  10653. friend iter_impl operator+(difference_type i, const iter_impl& it)
  10654. {
  10655. auto result = it;
  10656. result += i;
  10657. return result;
  10658. }
  10659. /*!
  10660. @brief subtract from iterator
  10661. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  10662. */
  10663. iter_impl operator-(difference_type i) const
  10664. {
  10665. auto result = *this;
  10666. result -= i;
  10667. return result;
  10668. }
  10669. /*!
  10670. @brief return difference
  10671. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  10672. */
  10673. difference_type operator-(const iter_impl& other) const
  10674. {
  10675. JSON_ASSERT(m_object != nullptr);
  10676. switch (m_object->m_type)
  10677. {
  10678. case value_t::object:
  10679. JSON_THROW(invalid_iterator::create(209, "cannot use offsets with object iterators", *m_object));
  10680. case value_t::array:
  10681. return m_it.array_iterator - other.m_it.array_iterator;
  10682. case value_t::null:
  10683. case value_t::string:
  10684. case value_t::boolean:
  10685. case value_t::number_integer:
  10686. case value_t::number_unsigned:
  10687. case value_t::number_float:
  10688. case value_t::binary:
  10689. case value_t::discarded:
  10690. default:
  10691. return m_it.primitive_iterator - other.m_it.primitive_iterator;
  10692. }
  10693. }
  10694. /*!
  10695. @brief access to successor
  10696. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  10697. */
  10698. reference operator[](difference_type n) const
  10699. {
  10700. JSON_ASSERT(m_object != nullptr);
  10701. switch (m_object->m_type)
  10702. {
  10703. case value_t::object:
  10704. JSON_THROW(invalid_iterator::create(208, "cannot use operator[] for object iterators", *m_object));
  10705. case value_t::array:
  10706. return *std::next(m_it.array_iterator, n);
  10707. case value_t::null:
  10708. JSON_THROW(invalid_iterator::create(214, "cannot get value", *m_object));
  10709. case value_t::string:
  10710. case value_t::boolean:
  10711. case value_t::number_integer:
  10712. case value_t::number_unsigned:
  10713. case value_t::number_float:
  10714. case value_t::binary:
  10715. case value_t::discarded:
  10716. default:
  10717. {
  10718. if (JSON_HEDLEY_LIKELY(m_it.primitive_iterator.get_value() == -n))
  10719. {
  10720. return *m_object;
  10721. }
  10722. JSON_THROW(invalid_iterator::create(214, "cannot get value", *m_object));
  10723. }
  10724. }
  10725. }
  10726. /*!
  10727. @brief return the key of an object iterator
  10728. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  10729. */
  10730. const typename object_t::key_type& key() const
  10731. {
  10732. JSON_ASSERT(m_object != nullptr);
  10733. if (JSON_HEDLEY_LIKELY(m_object->is_object()))
  10734. {
  10735. return m_it.object_iterator->first;
  10736. }
  10737. JSON_THROW(invalid_iterator::create(207, "cannot use key() for non-object iterators", *m_object));
  10738. }
  10739. /*!
  10740. @brief return the value of an iterator
  10741. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  10742. */
  10743. reference value() const
  10744. {
  10745. return operator*();
  10746. }
  10747. JSON_PRIVATE_UNLESS_TESTED:
  10748. /// associated JSON instance
  10749. pointer m_object = nullptr;
  10750. /// the actual iterator of the associated instance
  10751. internal_iterator<typename std::remove_const<BasicJsonType>::type> m_it {};
  10752. };
  10753. } // namespace detail
  10754. } // namespace nlohmann
  10755. // #include <nlohmann/detail/iterators/iteration_proxy.hpp>
  10756. // #include <nlohmann/detail/iterators/json_reverse_iterator.hpp>
  10757. #include <cstddef> // ptrdiff_t
  10758. #include <iterator> // reverse_iterator
  10759. #include <utility> // declval
  10760. namespace nlohmann
  10761. {
  10762. namespace detail
  10763. {
  10764. //////////////////////
  10765. // reverse_iterator //
  10766. //////////////////////
  10767. /*!
  10768. @brief a template for a reverse iterator class
  10769. @tparam Base the base iterator type to reverse. Valid types are @ref
  10770. iterator (to create @ref reverse_iterator) and @ref const_iterator (to
  10771. create @ref const_reverse_iterator).
  10772. @requirement The class satisfies the following concept requirements:
  10773. -
  10774. [BidirectionalIterator](https://en.cppreference.com/w/cpp/named_req/BidirectionalIterator):
  10775. The iterator that can be moved can be moved in both directions (i.e.
  10776. incremented and decremented).
  10777. - [OutputIterator](https://en.cppreference.com/w/cpp/named_req/OutputIterator):
  10778. It is possible to write to the pointed-to element (only if @a Base is
  10779. @ref iterator).
  10780. @since version 1.0.0
  10781. */
  10782. template<typename Base>
  10783. class json_reverse_iterator : public std::reverse_iterator<Base>
  10784. {
  10785. public:
  10786. using difference_type = std::ptrdiff_t;
  10787. /// shortcut to the reverse iterator adapter
  10788. using base_iterator = std::reverse_iterator<Base>;
  10789. /// the reference type for the pointed-to element
  10790. using reference = typename Base::reference;
  10791. /// create reverse iterator from iterator
  10792. explicit json_reverse_iterator(const typename base_iterator::iterator_type& it) noexcept
  10793. : base_iterator(it) {}
  10794. /// create reverse iterator from base class
  10795. explicit json_reverse_iterator(const base_iterator& it) noexcept : base_iterator(it) {}
  10796. /// post-increment (it++)
  10797. json_reverse_iterator const operator++(int) // NOLINT(readability-const-return-type)
  10798. {
  10799. return static_cast<json_reverse_iterator>(base_iterator::operator++(1));
  10800. }
  10801. /// pre-increment (++it)
  10802. json_reverse_iterator& operator++()
  10803. {
  10804. return static_cast<json_reverse_iterator&>(base_iterator::operator++());
  10805. }
  10806. /// post-decrement (it--)
  10807. json_reverse_iterator const operator--(int) // NOLINT(readability-const-return-type)
  10808. {
  10809. return static_cast<json_reverse_iterator>(base_iterator::operator--(1));
  10810. }
  10811. /// pre-decrement (--it)
  10812. json_reverse_iterator& operator--()
  10813. {
  10814. return static_cast<json_reverse_iterator&>(base_iterator::operator--());
  10815. }
  10816. /// add to iterator
  10817. json_reverse_iterator& operator+=(difference_type i)
  10818. {
  10819. return static_cast<json_reverse_iterator&>(base_iterator::operator+=(i));
  10820. }
  10821. /// add to iterator
  10822. json_reverse_iterator operator+(difference_type i) const
  10823. {
  10824. return static_cast<json_reverse_iterator>(base_iterator::operator+(i));
  10825. }
  10826. /// subtract from iterator
  10827. json_reverse_iterator operator-(difference_type i) const
  10828. {
  10829. return static_cast<json_reverse_iterator>(base_iterator::operator-(i));
  10830. }
  10831. /// return difference
  10832. difference_type operator-(const json_reverse_iterator& other) const
  10833. {
  10834. return base_iterator(*this) - base_iterator(other);
  10835. }
  10836. /// access to successor
  10837. reference operator[](difference_type n) const
  10838. {
  10839. return *(this->operator+(n));
  10840. }
  10841. /// return the key of an object iterator
  10842. auto key() const -> decltype(std::declval<Base>().key())
  10843. {
  10844. auto it = --this->base();
  10845. return it.key();
  10846. }
  10847. /// return the value of an iterator
  10848. reference value() const
  10849. {
  10850. auto it = --this->base();
  10851. return it.operator * ();
  10852. }
  10853. };
  10854. } // namespace detail
  10855. } // namespace nlohmann
  10856. // #include <nlohmann/detail/iterators/primitive_iterator.hpp>
  10857. // #include <nlohmann/detail/json_pointer.hpp>
  10858. #include <algorithm> // all_of
  10859. #include <cctype> // isdigit
  10860. #include <limits> // max
  10861. #include <numeric> // accumulate
  10862. #include <string> // string
  10863. #include <utility> // move
  10864. #include <vector> // vector
  10865. // #include <nlohmann/detail/exceptions.hpp>
  10866. // #include <nlohmann/detail/macro_scope.hpp>
  10867. // #include <nlohmann/detail/string_escape.hpp>
  10868. // #include <nlohmann/detail/value_t.hpp>
  10869. namespace nlohmann
  10870. {
  10871. template<typename BasicJsonType>
  10872. class json_pointer
  10873. {
  10874. // allow basic_json to access private members
  10875. NLOHMANN_BASIC_JSON_TPL_DECLARATION
  10876. friend class basic_json;
  10877. public:
  10878. /*!
  10879. @brief create JSON pointer
  10880. Create a JSON pointer according to the syntax described in
  10881. [Section 3 of RFC6901](https://tools.ietf.org/html/rfc6901#section-3).
  10882. @param[in] s string representing the JSON pointer; if omitted, the empty
  10883. string is assumed which references the whole JSON value
  10884. @throw parse_error.107 if the given JSON pointer @a s is nonempty and does
  10885. not begin with a slash (`/`); see example below
  10886. @throw parse_error.108 if a tilde (`~`) in the given JSON pointer @a s is
  10887. not followed by `0` (representing `~`) or `1` (representing `/`); see
  10888. example below
  10889. @liveexample{The example shows the construction several valid JSON pointers
  10890. as well as the exceptional behavior.,json_pointer}
  10891. @since version 2.0.0
  10892. */
  10893. explicit json_pointer(const std::string& s = "")
  10894. : reference_tokens(split(s))
  10895. {}
  10896. /*!
  10897. @brief return a string representation of the JSON pointer
  10898. @invariant For each JSON pointer `ptr`, it holds:
  10899. @code {.cpp}
  10900. ptr == json_pointer(ptr.to_string());
  10901. @endcode
  10902. @return a string representation of the JSON pointer
  10903. @liveexample{The example shows the result of `to_string`.,json_pointer__to_string}
  10904. @since version 2.0.0
  10905. */
  10906. std::string to_string() const
  10907. {
  10908. return std::accumulate(reference_tokens.begin(), reference_tokens.end(),
  10909. std::string{},
  10910. [](const std::string & a, const std::string & b)
  10911. {
  10912. return a + "/" + detail::escape(b);
  10913. });
  10914. }
  10915. /// @copydoc to_string()
  10916. operator std::string() const
  10917. {
  10918. return to_string();
  10919. }
  10920. /*!
  10921. @brief append another JSON pointer at the end of this JSON pointer
  10922. @param[in] ptr JSON pointer to append
  10923. @return JSON pointer with @a ptr appended
  10924. @liveexample{The example shows the usage of `operator/=`.,json_pointer__operator_add}
  10925. @complexity Linear in the length of @a ptr.
  10926. @sa see @ref operator/=(std::string) to append a reference token
  10927. @sa see @ref operator/=(std::size_t) to append an array index
  10928. @sa see @ref operator/(const json_pointer&, const json_pointer&) for a binary operator
  10929. @since version 3.6.0
  10930. */
  10931. json_pointer& operator/=(const json_pointer& ptr)
  10932. {
  10933. reference_tokens.insert(reference_tokens.end(),
  10934. ptr.reference_tokens.begin(),
  10935. ptr.reference_tokens.end());
  10936. return *this;
  10937. }
  10938. /*!
  10939. @brief append an unescaped reference token at the end of this JSON pointer
  10940. @param[in] token reference token to append
  10941. @return JSON pointer with @a token appended without escaping @a token
  10942. @liveexample{The example shows the usage of `operator/=`.,json_pointer__operator_add}
  10943. @complexity Amortized constant.
  10944. @sa see @ref operator/=(const json_pointer&) to append a JSON pointer
  10945. @sa see @ref operator/=(std::size_t) to append an array index
  10946. @sa see @ref operator/(const json_pointer&, std::size_t) for a binary operator
  10947. @since version 3.6.0
  10948. */
  10949. json_pointer& operator/=(std::string token)
  10950. {
  10951. push_back(std::move(token));
  10952. return *this;
  10953. }
  10954. /*!
  10955. @brief append an array index at the end of this JSON pointer
  10956. @param[in] array_idx array index to append
  10957. @return JSON pointer with @a array_idx appended
  10958. @liveexample{The example shows the usage of `operator/=`.,json_pointer__operator_add}
  10959. @complexity Amortized constant.
  10960. @sa see @ref operator/=(const json_pointer&) to append a JSON pointer
  10961. @sa see @ref operator/=(std::string) to append a reference token
  10962. @sa see @ref operator/(const json_pointer&, std::string) for a binary operator
  10963. @since version 3.6.0
  10964. */
  10965. json_pointer& operator/=(std::size_t array_idx)
  10966. {
  10967. return *this /= std::to_string(array_idx);
  10968. }
  10969. /*!
  10970. @brief create a new JSON pointer by appending the right JSON pointer at the end of the left JSON pointer
  10971. @param[in] lhs JSON pointer
  10972. @param[in] rhs JSON pointer
  10973. @return a new JSON pointer with @a rhs appended to @a lhs
  10974. @liveexample{The example shows the usage of `operator/`.,json_pointer__operator_add_binary}
  10975. @complexity Linear in the length of @a lhs and @a rhs.
  10976. @sa see @ref operator/=(const json_pointer&) to append a JSON pointer
  10977. @since version 3.6.0
  10978. */
  10979. friend json_pointer operator/(const json_pointer& lhs,
  10980. const json_pointer& rhs)
  10981. {
  10982. return json_pointer(lhs) /= rhs;
  10983. }
  10984. /*!
  10985. @brief create a new JSON pointer by appending the unescaped token at the end of the JSON pointer
  10986. @param[in] ptr JSON pointer
  10987. @param[in] token reference token
  10988. @return a new JSON pointer with unescaped @a token appended to @a ptr
  10989. @liveexample{The example shows the usage of `operator/`.,json_pointer__operator_add_binary}
  10990. @complexity Linear in the length of @a ptr.
  10991. @sa see @ref operator/=(std::string) to append a reference token
  10992. @since version 3.6.0
  10993. */
  10994. friend json_pointer operator/(const json_pointer& ptr, std::string token) // NOLINT(performance-unnecessary-value-param)
  10995. {
  10996. return json_pointer(ptr) /= std::move(token);
  10997. }
  10998. /*!
  10999. @brief create a new JSON pointer by appending the array-index-token at the end of the JSON pointer
  11000. @param[in] ptr JSON pointer
  11001. @param[in] array_idx array index
  11002. @return a new JSON pointer with @a array_idx appended to @a ptr
  11003. @liveexample{The example shows the usage of `operator/`.,json_pointer__operator_add_binary}
  11004. @complexity Linear in the length of @a ptr.
  11005. @sa see @ref operator/=(std::size_t) to append an array index
  11006. @since version 3.6.0
  11007. */
  11008. friend json_pointer operator/(const json_pointer& ptr, std::size_t array_idx)
  11009. {
  11010. return json_pointer(ptr) /= array_idx;
  11011. }
  11012. /*!
  11013. @brief returns the parent of this JSON pointer
  11014. @return parent of this JSON pointer; in case this JSON pointer is the root,
  11015. the root itself is returned
  11016. @complexity Linear in the length of the JSON pointer.
  11017. @liveexample{The example shows the result of `parent_pointer` for different
  11018. JSON Pointers.,json_pointer__parent_pointer}
  11019. @since version 3.6.0
  11020. */
  11021. json_pointer parent_pointer() const
  11022. {
  11023. if (empty())
  11024. {
  11025. return *this;
  11026. }
  11027. json_pointer res = *this;
  11028. res.pop_back();
  11029. return res;
  11030. }
  11031. /*!
  11032. @brief remove last reference token
  11033. @pre not `empty()`
  11034. @liveexample{The example shows the usage of `pop_back`.,json_pointer__pop_back}
  11035. @complexity Constant.
  11036. @throw out_of_range.405 if JSON pointer has no parent
  11037. @since version 3.6.0
  11038. */
  11039. void pop_back()
  11040. {
  11041. if (JSON_HEDLEY_UNLIKELY(empty()))
  11042. {
  11043. JSON_THROW(detail::out_of_range::create(405, "JSON pointer has no parent", BasicJsonType()));
  11044. }
  11045. reference_tokens.pop_back();
  11046. }
  11047. /*!
  11048. @brief return last reference token
  11049. @pre not `empty()`
  11050. @return last reference token
  11051. @liveexample{The example shows the usage of `back`.,json_pointer__back}
  11052. @complexity Constant.
  11053. @throw out_of_range.405 if JSON pointer has no parent
  11054. @since version 3.6.0
  11055. */
  11056. const std::string& back() const
  11057. {
  11058. if (JSON_HEDLEY_UNLIKELY(empty()))
  11059. {
  11060. JSON_THROW(detail::out_of_range::create(405, "JSON pointer has no parent", BasicJsonType()));
  11061. }
  11062. return reference_tokens.back();
  11063. }
  11064. /*!
  11065. @brief append an unescaped token at the end of the reference pointer
  11066. @param[in] token token to add
  11067. @complexity Amortized constant.
  11068. @liveexample{The example shows the result of `push_back` for different
  11069. JSON Pointers.,json_pointer__push_back}
  11070. @since version 3.6.0
  11071. */
  11072. void push_back(const std::string& token)
  11073. {
  11074. reference_tokens.push_back(token);
  11075. }
  11076. /// @copydoc push_back(const std::string&)
  11077. void push_back(std::string&& token)
  11078. {
  11079. reference_tokens.push_back(std::move(token));
  11080. }
  11081. /*!
  11082. @brief return whether pointer points to the root document
  11083. @return true iff the JSON pointer points to the root document
  11084. @complexity Constant.
  11085. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  11086. @liveexample{The example shows the result of `empty` for different JSON
  11087. Pointers.,json_pointer__empty}
  11088. @since version 3.6.0
  11089. */
  11090. bool empty() const noexcept
  11091. {
  11092. return reference_tokens.empty();
  11093. }
  11094. private:
  11095. /*!
  11096. @param[in] s reference token to be converted into an array index
  11097. @return integer representation of @a s
  11098. @throw parse_error.106 if an array index begins with '0'
  11099. @throw parse_error.109 if an array index begins not with a digit
  11100. @throw out_of_range.404 if string @a s could not be converted to an integer
  11101. @throw out_of_range.410 if an array index exceeds size_type
  11102. */
  11103. static typename BasicJsonType::size_type array_index(const std::string& s)
  11104. {
  11105. using size_type = typename BasicJsonType::size_type;
  11106. // error condition (cf. RFC 6901, Sect. 4)
  11107. if (JSON_HEDLEY_UNLIKELY(s.size() > 1 && s[0] == '0'))
  11108. {
  11109. JSON_THROW(detail::parse_error::create(106, 0, "array index '" + s + "' must not begin with '0'", BasicJsonType()));
  11110. }
  11111. // error condition (cf. RFC 6901, Sect. 4)
  11112. if (JSON_HEDLEY_UNLIKELY(s.size() > 1 && !(s[0] >= '1' && s[0] <= '9')))
  11113. {
  11114. JSON_THROW(detail::parse_error::create(109, 0, "array index '" + s + "' is not a number", BasicJsonType()));
  11115. }
  11116. std::size_t processed_chars = 0;
  11117. unsigned long long res = 0; // NOLINT(runtime/int)
  11118. JSON_TRY
  11119. {
  11120. res = std::stoull(s, &processed_chars);
  11121. }
  11122. JSON_CATCH(std::out_of_range&)
  11123. {
  11124. JSON_THROW(detail::out_of_range::create(404, "unresolved reference token '" + s + "'", BasicJsonType()));
  11125. }
  11126. // check if the string was completely read
  11127. if (JSON_HEDLEY_UNLIKELY(processed_chars != s.size()))
  11128. {
  11129. JSON_THROW(detail::out_of_range::create(404, "unresolved reference token '" + s + "'", BasicJsonType()));
  11130. }
  11131. // only triggered on special platforms (like 32bit), see also
  11132. // https://github.com/nlohmann/json/pull/2203
  11133. if (res >= static_cast<unsigned long long>((std::numeric_limits<size_type>::max)())) // NOLINT(runtime/int)
  11134. {
  11135. JSON_THROW(detail::out_of_range::create(410, "array index " + s + " exceeds size_type", BasicJsonType())); // LCOV_EXCL_LINE
  11136. }
  11137. return static_cast<size_type>(res);
  11138. }
  11139. JSON_PRIVATE_UNLESS_TESTED:
  11140. json_pointer top() const
  11141. {
  11142. if (JSON_HEDLEY_UNLIKELY(empty()))
  11143. {
  11144. JSON_THROW(detail::out_of_range::create(405, "JSON pointer has no parent", BasicJsonType()));
  11145. }
  11146. json_pointer result = *this;
  11147. result.reference_tokens = {reference_tokens[0]};
  11148. return result;
  11149. }
  11150. private:
  11151. /*!
  11152. @brief create and return a reference to the pointed to value
  11153. @complexity Linear in the number of reference tokens.
  11154. @throw parse_error.109 if array index is not a number
  11155. @throw type_error.313 if value cannot be unflattened
  11156. */
  11157. BasicJsonType& get_and_create(BasicJsonType& j) const
  11158. {
  11159. auto* result = &j;
  11160. // in case no reference tokens exist, return a reference to the JSON value
  11161. // j which will be overwritten by a primitive value
  11162. for (const auto& reference_token : reference_tokens)
  11163. {
  11164. switch (result->type())
  11165. {
  11166. case detail::value_t::null:
  11167. {
  11168. if (reference_token == "0")
  11169. {
  11170. // start a new array if reference token is 0
  11171. result = &result->operator[](0);
  11172. }
  11173. else
  11174. {
  11175. // start a new object otherwise
  11176. result = &result->operator[](reference_token);
  11177. }
  11178. break;
  11179. }
  11180. case detail::value_t::object:
  11181. {
  11182. // create an entry in the object
  11183. result = &result->operator[](reference_token);
  11184. break;
  11185. }
  11186. case detail::value_t::array:
  11187. {
  11188. // create an entry in the array
  11189. result = &result->operator[](array_index(reference_token));
  11190. break;
  11191. }
  11192. /*
  11193. The following code is only reached if there exists a reference
  11194. token _and_ the current value is primitive. In this case, we have
  11195. an error situation, because primitive values may only occur as
  11196. single value; that is, with an empty list of reference tokens.
  11197. */
  11198. case detail::value_t::string:
  11199. case detail::value_t::boolean:
  11200. case detail::value_t::number_integer:
  11201. case detail::value_t::number_unsigned:
  11202. case detail::value_t::number_float:
  11203. case detail::value_t::binary:
  11204. case detail::value_t::discarded:
  11205. default:
  11206. JSON_THROW(detail::type_error::create(313, "invalid value to unflatten", j));
  11207. }
  11208. }
  11209. return *result;
  11210. }
  11211. /*!
  11212. @brief return a reference to the pointed to value
  11213. @note This version does not throw if a value is not present, but tries to
  11214. create nested values instead. For instance, calling this function
  11215. with pointer `"/this/that"` on a null value is equivalent to calling
  11216. `operator[]("this").operator[]("that")` on that value, effectively
  11217. changing the null value to an object.
  11218. @param[in] ptr a JSON value
  11219. @return reference to the JSON value pointed to by the JSON pointer
  11220. @complexity Linear in the length of the JSON pointer.
  11221. @throw parse_error.106 if an array index begins with '0'
  11222. @throw parse_error.109 if an array index was not a number
  11223. @throw out_of_range.404 if the JSON pointer can not be resolved
  11224. */
  11225. BasicJsonType& get_unchecked(BasicJsonType* ptr) const
  11226. {
  11227. for (const auto& reference_token : reference_tokens)
  11228. {
  11229. // convert null values to arrays or objects before continuing
  11230. if (ptr->is_null())
  11231. {
  11232. // check if reference token is a number
  11233. const bool nums =
  11234. std::all_of(reference_token.begin(), reference_token.end(),
  11235. [](const unsigned char x)
  11236. {
  11237. return std::isdigit(x);
  11238. });
  11239. // change value to array for numbers or "-" or to object otherwise
  11240. *ptr = (nums || reference_token == "-")
  11241. ? detail::value_t::array
  11242. : detail::value_t::object;
  11243. }
  11244. switch (ptr->type())
  11245. {
  11246. case detail::value_t::object:
  11247. {
  11248. // use unchecked object access
  11249. ptr = &ptr->operator[](reference_token);
  11250. break;
  11251. }
  11252. case detail::value_t::array:
  11253. {
  11254. if (reference_token == "-")
  11255. {
  11256. // explicitly treat "-" as index beyond the end
  11257. ptr = &ptr->operator[](ptr->m_value.array->size());
  11258. }
  11259. else
  11260. {
  11261. // convert array index to number; unchecked access
  11262. ptr = &ptr->operator[](array_index(reference_token));
  11263. }
  11264. break;
  11265. }
  11266. case detail::value_t::null:
  11267. case detail::value_t::string:
  11268. case detail::value_t::boolean:
  11269. case detail::value_t::number_integer:
  11270. case detail::value_t::number_unsigned:
  11271. case detail::value_t::number_float:
  11272. case detail::value_t::binary:
  11273. case detail::value_t::discarded:
  11274. default:
  11275. JSON_THROW(detail::out_of_range::create(404, "unresolved reference token '" + reference_token + "'", *ptr));
  11276. }
  11277. }
  11278. return *ptr;
  11279. }
  11280. /*!
  11281. @throw parse_error.106 if an array index begins with '0'
  11282. @throw parse_error.109 if an array index was not a number
  11283. @throw out_of_range.402 if the array index '-' is used
  11284. @throw out_of_range.404 if the JSON pointer can not be resolved
  11285. */
  11286. BasicJsonType& get_checked(BasicJsonType* ptr) const
  11287. {
  11288. for (const auto& reference_token : reference_tokens)
  11289. {
  11290. switch (ptr->type())
  11291. {
  11292. case detail::value_t::object:
  11293. {
  11294. // note: at performs range check
  11295. ptr = &ptr->at(reference_token);
  11296. break;
  11297. }
  11298. case detail::value_t::array:
  11299. {
  11300. if (JSON_HEDLEY_UNLIKELY(reference_token == "-"))
  11301. {
  11302. // "-" always fails the range check
  11303. JSON_THROW(detail::out_of_range::create(402,
  11304. "array index '-' (" + std::to_string(ptr->m_value.array->size()) +
  11305. ") is out of range", *ptr));
  11306. }
  11307. // note: at performs range check
  11308. ptr = &ptr->at(array_index(reference_token));
  11309. break;
  11310. }
  11311. case detail::value_t::null:
  11312. case detail::value_t::string:
  11313. case detail::value_t::boolean:
  11314. case detail::value_t::number_integer:
  11315. case detail::value_t::number_unsigned:
  11316. case detail::value_t::number_float:
  11317. case detail::value_t::binary:
  11318. case detail::value_t::discarded:
  11319. default:
  11320. JSON_THROW(detail::out_of_range::create(404, "unresolved reference token '" + reference_token + "'", *ptr));
  11321. }
  11322. }
  11323. return *ptr;
  11324. }
  11325. /*!
  11326. @brief return a const reference to the pointed to value
  11327. @param[in] ptr a JSON value
  11328. @return const reference to the JSON value pointed to by the JSON
  11329. pointer
  11330. @throw parse_error.106 if an array index begins with '0'
  11331. @throw parse_error.109 if an array index was not a number
  11332. @throw out_of_range.402 if the array index '-' is used
  11333. @throw out_of_range.404 if the JSON pointer can not be resolved
  11334. */
  11335. const BasicJsonType& get_unchecked(const BasicJsonType* ptr) const
  11336. {
  11337. for (const auto& reference_token : reference_tokens)
  11338. {
  11339. switch (ptr->type())
  11340. {
  11341. case detail::value_t::object:
  11342. {
  11343. // use unchecked object access
  11344. ptr = &ptr->operator[](reference_token);
  11345. break;
  11346. }
  11347. case detail::value_t::array:
  11348. {
  11349. if (JSON_HEDLEY_UNLIKELY(reference_token == "-"))
  11350. {
  11351. // "-" cannot be used for const access
  11352. JSON_THROW(detail::out_of_range::create(402, "array index '-' (" + std::to_string(ptr->m_value.array->size()) + ") is out of range", *ptr));
  11353. }
  11354. // use unchecked array access
  11355. ptr = &ptr->operator[](array_index(reference_token));
  11356. break;
  11357. }
  11358. case detail::value_t::null:
  11359. case detail::value_t::string:
  11360. case detail::value_t::boolean:
  11361. case detail::value_t::number_integer:
  11362. case detail::value_t::number_unsigned:
  11363. case detail::value_t::number_float:
  11364. case detail::value_t::binary:
  11365. case detail::value_t::discarded:
  11366. default:
  11367. JSON_THROW(detail::out_of_range::create(404, "unresolved reference token '" + reference_token + "'", *ptr));
  11368. }
  11369. }
  11370. return *ptr;
  11371. }
  11372. /*!
  11373. @throw parse_error.106 if an array index begins with '0'
  11374. @throw parse_error.109 if an array index was not a number
  11375. @throw out_of_range.402 if the array index '-' is used
  11376. @throw out_of_range.404 if the JSON pointer can not be resolved
  11377. */
  11378. const BasicJsonType& get_checked(const BasicJsonType* ptr) const
  11379. {
  11380. for (const auto& reference_token : reference_tokens)
  11381. {
  11382. switch (ptr->type())
  11383. {
  11384. case detail::value_t::object:
  11385. {
  11386. // note: at performs range check
  11387. ptr = &ptr->at(reference_token);
  11388. break;
  11389. }
  11390. case detail::value_t::array:
  11391. {
  11392. if (JSON_HEDLEY_UNLIKELY(reference_token == "-"))
  11393. {
  11394. // "-" always fails the range check
  11395. JSON_THROW(detail::out_of_range::create(402,
  11396. "array index '-' (" + std::to_string(ptr->m_value.array->size()) +
  11397. ") is out of range", *ptr));
  11398. }
  11399. // note: at performs range check
  11400. ptr = &ptr->at(array_index(reference_token));
  11401. break;
  11402. }
  11403. case detail::value_t::null:
  11404. case detail::value_t::string:
  11405. case detail::value_t::boolean:
  11406. case detail::value_t::number_integer:
  11407. case detail::value_t::number_unsigned:
  11408. case detail::value_t::number_float:
  11409. case detail::value_t::binary:
  11410. case detail::value_t::discarded:
  11411. default:
  11412. JSON_THROW(detail::out_of_range::create(404, "unresolved reference token '" + reference_token + "'", *ptr));
  11413. }
  11414. }
  11415. return *ptr;
  11416. }
  11417. /*!
  11418. @throw parse_error.106 if an array index begins with '0'
  11419. @throw parse_error.109 if an array index was not a number
  11420. */
  11421. bool contains(const BasicJsonType* ptr) const
  11422. {
  11423. for (const auto& reference_token : reference_tokens)
  11424. {
  11425. switch (ptr->type())
  11426. {
  11427. case detail::value_t::object:
  11428. {
  11429. if (!ptr->contains(reference_token))
  11430. {
  11431. // we did not find the key in the object
  11432. return false;
  11433. }
  11434. ptr = &ptr->operator[](reference_token);
  11435. break;
  11436. }
  11437. case detail::value_t::array:
  11438. {
  11439. if (JSON_HEDLEY_UNLIKELY(reference_token == "-"))
  11440. {
  11441. // "-" always fails the range check
  11442. return false;
  11443. }
  11444. if (JSON_HEDLEY_UNLIKELY(reference_token.size() == 1 && !("0" <= reference_token && reference_token <= "9")))
  11445. {
  11446. // invalid char
  11447. return false;
  11448. }
  11449. if (JSON_HEDLEY_UNLIKELY(reference_token.size() > 1))
  11450. {
  11451. if (JSON_HEDLEY_UNLIKELY(!('1' <= reference_token[0] && reference_token[0] <= '9')))
  11452. {
  11453. // first char should be between '1' and '9'
  11454. return false;
  11455. }
  11456. for (std::size_t i = 1; i < reference_token.size(); i++)
  11457. {
  11458. if (JSON_HEDLEY_UNLIKELY(!('0' <= reference_token[i] && reference_token[i] <= '9')))
  11459. {
  11460. // other char should be between '0' and '9'
  11461. return false;
  11462. }
  11463. }
  11464. }
  11465. const auto idx = array_index(reference_token);
  11466. if (idx >= ptr->size())
  11467. {
  11468. // index out of range
  11469. return false;
  11470. }
  11471. ptr = &ptr->operator[](idx);
  11472. break;
  11473. }
  11474. case detail::value_t::null:
  11475. case detail::value_t::string:
  11476. case detail::value_t::boolean:
  11477. case detail::value_t::number_integer:
  11478. case detail::value_t::number_unsigned:
  11479. case detail::value_t::number_float:
  11480. case detail::value_t::binary:
  11481. case detail::value_t::discarded:
  11482. default:
  11483. {
  11484. // we do not expect primitive values if there is still a
  11485. // reference token to process
  11486. return false;
  11487. }
  11488. }
  11489. }
  11490. // no reference token left means we found a primitive value
  11491. return true;
  11492. }
  11493. /*!
  11494. @brief split the string input to reference tokens
  11495. @note This function is only called by the json_pointer constructor.
  11496. All exceptions below are documented there.
  11497. @throw parse_error.107 if the pointer is not empty or begins with '/'
  11498. @throw parse_error.108 if character '~' is not followed by '0' or '1'
  11499. */
  11500. static std::vector<std::string> split(const std::string& reference_string)
  11501. {
  11502. std::vector<std::string> result;
  11503. // special case: empty reference string -> no reference tokens
  11504. if (reference_string.empty())
  11505. {
  11506. return result;
  11507. }
  11508. // check if nonempty reference string begins with slash
  11509. if (JSON_HEDLEY_UNLIKELY(reference_string[0] != '/'))
  11510. {
  11511. JSON_THROW(detail::parse_error::create(107, 1, "JSON pointer must be empty or begin with '/' - was: '" + reference_string + "'", BasicJsonType()));
  11512. }
  11513. // extract the reference tokens:
  11514. // - slash: position of the last read slash (or end of string)
  11515. // - start: position after the previous slash
  11516. for (
  11517. // search for the first slash after the first character
  11518. std::size_t slash = reference_string.find_first_of('/', 1),
  11519. // set the beginning of the first reference token
  11520. start = 1;
  11521. // we can stop if start == 0 (if slash == std::string::npos)
  11522. start != 0;
  11523. // set the beginning of the next reference token
  11524. // (will eventually be 0 if slash == std::string::npos)
  11525. start = (slash == std::string::npos) ? 0 : slash + 1,
  11526. // find next slash
  11527. slash = reference_string.find_first_of('/', start))
  11528. {
  11529. // use the text between the beginning of the reference token
  11530. // (start) and the last slash (slash).
  11531. auto reference_token = reference_string.substr(start, slash - start);
  11532. // check reference tokens are properly escaped
  11533. for (std::size_t pos = reference_token.find_first_of('~');
  11534. pos != std::string::npos;
  11535. pos = reference_token.find_first_of('~', pos + 1))
  11536. {
  11537. JSON_ASSERT(reference_token[pos] == '~');
  11538. // ~ must be followed by 0 or 1
  11539. if (JSON_HEDLEY_UNLIKELY(pos == reference_token.size() - 1 ||
  11540. (reference_token[pos + 1] != '0' &&
  11541. reference_token[pos + 1] != '1')))
  11542. {
  11543. JSON_THROW(detail::parse_error::create(108, 0, "escape character '~' must be followed with '0' or '1'", BasicJsonType()));
  11544. }
  11545. }
  11546. // finally, store the reference token
  11547. detail::unescape(reference_token);
  11548. result.push_back(reference_token);
  11549. }
  11550. return result;
  11551. }
  11552. private:
  11553. /*!
  11554. @param[in] reference_string the reference string to the current value
  11555. @param[in] value the value to consider
  11556. @param[in,out] result the result object to insert values to
  11557. @note Empty objects or arrays are flattened to `null`.
  11558. */
  11559. static void flatten(const std::string& reference_string,
  11560. const BasicJsonType& value,
  11561. BasicJsonType& result)
  11562. {
  11563. switch (value.type())
  11564. {
  11565. case detail::value_t::array:
  11566. {
  11567. if (value.m_value.array->empty())
  11568. {
  11569. // flatten empty array as null
  11570. result[reference_string] = nullptr;
  11571. }
  11572. else
  11573. {
  11574. // iterate array and use index as reference string
  11575. for (std::size_t i = 0; i < value.m_value.array->size(); ++i)
  11576. {
  11577. flatten(reference_string + "/" + std::to_string(i),
  11578. value.m_value.array->operator[](i), result);
  11579. }
  11580. }
  11581. break;
  11582. }
  11583. case detail::value_t::object:
  11584. {
  11585. if (value.m_value.object->empty())
  11586. {
  11587. // flatten empty object as null
  11588. result[reference_string] = nullptr;
  11589. }
  11590. else
  11591. {
  11592. // iterate object and use keys as reference string
  11593. for (const auto& element : *value.m_value.object)
  11594. {
  11595. flatten(reference_string + "/" + detail::escape(element.first), element.second, result);
  11596. }
  11597. }
  11598. break;
  11599. }
  11600. case detail::value_t::null:
  11601. case detail::value_t::string:
  11602. case detail::value_t::boolean:
  11603. case detail::value_t::number_integer:
  11604. case detail::value_t::number_unsigned:
  11605. case detail::value_t::number_float:
  11606. case detail::value_t::binary:
  11607. case detail::value_t::discarded:
  11608. default:
  11609. {
  11610. // add primitive value with its reference string
  11611. result[reference_string] = value;
  11612. break;
  11613. }
  11614. }
  11615. }
  11616. /*!
  11617. @param[in] value flattened JSON
  11618. @return unflattened JSON
  11619. @throw parse_error.109 if array index is not a number
  11620. @throw type_error.314 if value is not an object
  11621. @throw type_error.315 if object values are not primitive
  11622. @throw type_error.313 if value cannot be unflattened
  11623. */
  11624. static BasicJsonType
  11625. unflatten(const BasicJsonType& value)
  11626. {
  11627. if (JSON_HEDLEY_UNLIKELY(!value.is_object()))
  11628. {
  11629. JSON_THROW(detail::type_error::create(314, "only objects can be unflattened", value));
  11630. }
  11631. BasicJsonType result;
  11632. // iterate the JSON object values
  11633. for (const auto& element : *value.m_value.object)
  11634. {
  11635. if (JSON_HEDLEY_UNLIKELY(!element.second.is_primitive()))
  11636. {
  11637. JSON_THROW(detail::type_error::create(315, "values in object must be primitive", element.second));
  11638. }
  11639. // assign value to reference pointed to by JSON pointer; Note that if
  11640. // the JSON pointer is "" (i.e., points to the whole value), function
  11641. // get_and_create returns a reference to result itself. An assignment
  11642. // will then create a primitive value.
  11643. json_pointer(element.first).get_and_create(result) = element.second;
  11644. }
  11645. return result;
  11646. }
  11647. /*!
  11648. @brief compares two JSON pointers for equality
  11649. @param[in] lhs JSON pointer to compare
  11650. @param[in] rhs JSON pointer to compare
  11651. @return whether @a lhs is equal to @a rhs
  11652. @complexity Linear in the length of the JSON pointer
  11653. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  11654. */
  11655. friend bool operator==(json_pointer const& lhs,
  11656. json_pointer const& rhs) noexcept
  11657. {
  11658. return lhs.reference_tokens == rhs.reference_tokens;
  11659. }
  11660. /*!
  11661. @brief compares two JSON pointers for inequality
  11662. @param[in] lhs JSON pointer to compare
  11663. @param[in] rhs JSON pointer to compare
  11664. @return whether @a lhs is not equal @a rhs
  11665. @complexity Linear in the length of the JSON pointer
  11666. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  11667. */
  11668. friend bool operator!=(json_pointer const& lhs,
  11669. json_pointer const& rhs) noexcept
  11670. {
  11671. return !(lhs == rhs);
  11672. }
  11673. /// the reference tokens
  11674. std::vector<std::string> reference_tokens;
  11675. };
  11676. } // namespace nlohmann
  11677. // #include <nlohmann/detail/json_ref.hpp>
  11678. #include <initializer_list>
  11679. #include <utility>
  11680. // #include <nlohmann/detail/meta/type_traits.hpp>
  11681. namespace nlohmann
  11682. {
  11683. namespace detail
  11684. {
  11685. template<typename BasicJsonType>
  11686. class json_ref
  11687. {
  11688. public:
  11689. using value_type = BasicJsonType;
  11690. json_ref(value_type&& value)
  11691. : owned_value(std::move(value))
  11692. {}
  11693. json_ref(const value_type& value)
  11694. : value_ref(&value)
  11695. {}
  11696. json_ref(std::initializer_list<json_ref> init)
  11697. : owned_value(init)
  11698. {}
  11699. template <
  11700. class... Args,
  11701. enable_if_t<std::is_constructible<value_type, Args...>::value, int> = 0 >
  11702. json_ref(Args && ... args)
  11703. : owned_value(std::forward<Args>(args)...)
  11704. {}
  11705. // class should be movable only
  11706. json_ref(json_ref&&) noexcept = default;
  11707. json_ref(const json_ref&) = delete;
  11708. json_ref& operator=(const json_ref&) = delete;
  11709. json_ref& operator=(json_ref&&) = delete;
  11710. ~json_ref() = default;
  11711. value_type moved_or_copied() const
  11712. {
  11713. if (value_ref == nullptr)
  11714. {
  11715. return std::move(owned_value);
  11716. }
  11717. return *value_ref;
  11718. }
  11719. value_type const& operator*() const
  11720. {
  11721. return value_ref ? *value_ref : owned_value;
  11722. }
  11723. value_type const* operator->() const
  11724. {
  11725. return &** this;
  11726. }
  11727. private:
  11728. mutable value_type owned_value = nullptr;
  11729. value_type const* value_ref = nullptr;
  11730. };
  11731. } // namespace detail
  11732. } // namespace nlohmann
  11733. // #include <nlohmann/detail/macro_scope.hpp>
  11734. // #include <nlohmann/detail/string_escape.hpp>
  11735. // #include <nlohmann/detail/meta/cpp_future.hpp>
  11736. // #include <nlohmann/detail/meta/type_traits.hpp>
  11737. // #include <nlohmann/detail/output/binary_writer.hpp>
  11738. #include <algorithm> // reverse
  11739. #include <array> // array
  11740. #include <cmath> // isnan, isinf
  11741. #include <cstdint> // uint8_t, uint16_t, uint32_t, uint64_t
  11742. #include <cstring> // memcpy
  11743. #include <limits> // numeric_limits
  11744. #include <string> // string
  11745. #include <utility> // move
  11746. // #include <nlohmann/detail/input/binary_reader.hpp>
  11747. // #include <nlohmann/detail/macro_scope.hpp>
  11748. // #include <nlohmann/detail/output/output_adapters.hpp>
  11749. #include <algorithm> // copy
  11750. #include <cstddef> // size_t
  11751. #include <iterator> // back_inserter
  11752. #include <memory> // shared_ptr, make_shared
  11753. #include <string> // basic_string
  11754. #include <vector> // vector
  11755. #ifndef JSON_NO_IO
  11756. #include <ios> // streamsize
  11757. #include <ostream> // basic_ostream
  11758. #endif // JSON_NO_IO
  11759. // #include <nlohmann/detail/macro_scope.hpp>
  11760. namespace nlohmann
  11761. {
  11762. namespace detail
  11763. {
  11764. /// abstract output adapter interface
  11765. template<typename CharType> struct output_adapter_protocol
  11766. {
  11767. virtual void write_character(CharType c) = 0;
  11768. virtual void write_characters(const CharType* s, std::size_t length) = 0;
  11769. virtual ~output_adapter_protocol() = default;
  11770. output_adapter_protocol() = default;
  11771. output_adapter_protocol(const output_adapter_protocol&) = default;
  11772. output_adapter_protocol(output_adapter_protocol&&) noexcept = default;
  11773. output_adapter_protocol& operator=(const output_adapter_protocol&) = default;
  11774. output_adapter_protocol& operator=(output_adapter_protocol&&) noexcept = default;
  11775. };
  11776. /// a type to simplify interfaces
  11777. template<typename CharType>
  11778. using output_adapter_t = std::shared_ptr<output_adapter_protocol<CharType>>;
  11779. /// output adapter for byte vectors
  11780. template<typename CharType, typename AllocatorType = std::allocator<CharType>>
  11781. class output_vector_adapter : public output_adapter_protocol<CharType>
  11782. {
  11783. public:
  11784. explicit output_vector_adapter(std::vector<CharType, AllocatorType>& vec) noexcept
  11785. : v(vec)
  11786. {}
  11787. void write_character(CharType c) override
  11788. {
  11789. v.push_back(c);
  11790. }
  11791. JSON_HEDLEY_NON_NULL(2)
  11792. void write_characters(const CharType* s, std::size_t length) override
  11793. {
  11794. std::copy(s, s + length, std::back_inserter(v));
  11795. }
  11796. private:
  11797. std::vector<CharType, AllocatorType>& v;
  11798. };
  11799. #ifndef JSON_NO_IO
  11800. /// output adapter for output streams
  11801. template<typename CharType>
  11802. class output_stream_adapter : public output_adapter_protocol<CharType>
  11803. {
  11804. public:
  11805. explicit output_stream_adapter(std::basic_ostream<CharType>& s) noexcept
  11806. : stream(s)
  11807. {}
  11808. void write_character(CharType c) override
  11809. {
  11810. stream.put(c);
  11811. }
  11812. JSON_HEDLEY_NON_NULL(2)
  11813. void write_characters(const CharType* s, std::size_t length) override
  11814. {
  11815. stream.write(s, static_cast<std::streamsize>(length));
  11816. }
  11817. private:
  11818. std::basic_ostream<CharType>& stream;
  11819. };
  11820. #endif // JSON_NO_IO
  11821. /// output adapter for basic_string
  11822. template<typename CharType, typename StringType = std::basic_string<CharType>>
  11823. class output_string_adapter : public output_adapter_protocol<CharType>
  11824. {
  11825. public:
  11826. explicit output_string_adapter(StringType& s) noexcept
  11827. : str(s)
  11828. {}
  11829. void write_character(CharType c) override
  11830. {
  11831. str.push_back(c);
  11832. }
  11833. JSON_HEDLEY_NON_NULL(2)
  11834. void write_characters(const CharType* s, std::size_t length) override
  11835. {
  11836. str.append(s, length);
  11837. }
  11838. private:
  11839. StringType& str;
  11840. };
  11841. template<typename CharType, typename StringType = std::basic_string<CharType>>
  11842. class output_adapter
  11843. {
  11844. public:
  11845. template<typename AllocatorType = std::allocator<CharType>>
  11846. output_adapter(std::vector<CharType, AllocatorType>& vec)
  11847. : oa(std::make_shared<output_vector_adapter<CharType, AllocatorType>>(vec)) {}
  11848. #ifndef JSON_NO_IO
  11849. output_adapter(std::basic_ostream<CharType>& s)
  11850. : oa(std::make_shared<output_stream_adapter<CharType>>(s)) {}
  11851. #endif // JSON_NO_IO
  11852. output_adapter(StringType& s)
  11853. : oa(std::make_shared<output_string_adapter<CharType, StringType>>(s)) {}
  11854. operator output_adapter_t<CharType>()
  11855. {
  11856. return oa;
  11857. }
  11858. private:
  11859. output_adapter_t<CharType> oa = nullptr;
  11860. };
  11861. } // namespace detail
  11862. } // namespace nlohmann
  11863. namespace nlohmann
  11864. {
  11865. namespace detail
  11866. {
  11867. ///////////////////
  11868. // binary writer //
  11869. ///////////////////
  11870. /*!
  11871. @brief serialization to CBOR and MessagePack values
  11872. */
  11873. template<typename BasicJsonType, typename CharType>
  11874. class binary_writer
  11875. {
  11876. using string_t = typename BasicJsonType::string_t;
  11877. using binary_t = typename BasicJsonType::binary_t;
  11878. using number_float_t = typename BasicJsonType::number_float_t;
  11879. public:
  11880. /*!
  11881. @brief create a binary writer
  11882. @param[in] adapter output adapter to write to
  11883. */
  11884. explicit binary_writer(output_adapter_t<CharType> adapter) : oa(std::move(adapter))
  11885. {
  11886. JSON_ASSERT(oa);
  11887. }
  11888. /*!
  11889. @param[in] j JSON value to serialize
  11890. @pre j.type() == value_t::object
  11891. */
  11892. void write_bson(const BasicJsonType& j)
  11893. {
  11894. switch (j.type())
  11895. {
  11896. case value_t::object:
  11897. {
  11898. write_bson_object(*j.m_value.object);
  11899. break;
  11900. }
  11901. case value_t::null:
  11902. case value_t::array:
  11903. case value_t::string:
  11904. case value_t::boolean:
  11905. case value_t::number_integer:
  11906. case value_t::number_unsigned:
  11907. case value_t::number_float:
  11908. case value_t::binary:
  11909. case value_t::discarded:
  11910. default:
  11911. {
  11912. JSON_THROW(type_error::create(317, "to serialize to BSON, top-level type must be object, but is " + std::string(j.type_name()), j));
  11913. }
  11914. }
  11915. }
  11916. /*!
  11917. @param[in] j JSON value to serialize
  11918. */
  11919. void write_cbor(const BasicJsonType& j)
  11920. {
  11921. switch (j.type())
  11922. {
  11923. case value_t::null:
  11924. {
  11925. oa->write_character(to_char_type(0xF6));
  11926. break;
  11927. }
  11928. case value_t::boolean:
  11929. {
  11930. oa->write_character(j.m_value.boolean
  11931. ? to_char_type(0xF5)
  11932. : to_char_type(0xF4));
  11933. break;
  11934. }
  11935. case value_t::number_integer:
  11936. {
  11937. if (j.m_value.number_integer >= 0)
  11938. {
  11939. // CBOR does not differentiate between positive signed
  11940. // integers and unsigned integers. Therefore, we used the
  11941. // code from the value_t::number_unsigned case here.
  11942. if (j.m_value.number_integer <= 0x17)
  11943. {
  11944. write_number(static_cast<std::uint8_t>(j.m_value.number_integer));
  11945. }
  11946. else if (j.m_value.number_integer <= (std::numeric_limits<std::uint8_t>::max)())
  11947. {
  11948. oa->write_character(to_char_type(0x18));
  11949. write_number(static_cast<std::uint8_t>(j.m_value.number_integer));
  11950. }
  11951. else if (j.m_value.number_integer <= (std::numeric_limits<std::uint16_t>::max)())
  11952. {
  11953. oa->write_character(to_char_type(0x19));
  11954. write_number(static_cast<std::uint16_t>(j.m_value.number_integer));
  11955. }
  11956. else if (j.m_value.number_integer <= (std::numeric_limits<std::uint32_t>::max)())
  11957. {
  11958. oa->write_character(to_char_type(0x1A));
  11959. write_number(static_cast<std::uint32_t>(j.m_value.number_integer));
  11960. }
  11961. else
  11962. {
  11963. oa->write_character(to_char_type(0x1B));
  11964. write_number(static_cast<std::uint64_t>(j.m_value.number_integer));
  11965. }
  11966. }
  11967. else
  11968. {
  11969. // The conversions below encode the sign in the first
  11970. // byte, and the value is converted to a positive number.
  11971. const auto positive_number = -1 - j.m_value.number_integer;
  11972. if (j.m_value.number_integer >= -24)
  11973. {
  11974. write_number(static_cast<std::uint8_t>(0x20 + positive_number));
  11975. }
  11976. else if (positive_number <= (std::numeric_limits<std::uint8_t>::max)())
  11977. {
  11978. oa->write_character(to_char_type(0x38));
  11979. write_number(static_cast<std::uint8_t>(positive_number));
  11980. }
  11981. else if (positive_number <= (std::numeric_limits<std::uint16_t>::max)())
  11982. {
  11983. oa->write_character(to_char_type(0x39));
  11984. write_number(static_cast<std::uint16_t>(positive_number));
  11985. }
  11986. else if (positive_number <= (std::numeric_limits<std::uint32_t>::max)())
  11987. {
  11988. oa->write_character(to_char_type(0x3A));
  11989. write_number(static_cast<std::uint32_t>(positive_number));
  11990. }
  11991. else
  11992. {
  11993. oa->write_character(to_char_type(0x3B));
  11994. write_number(static_cast<std::uint64_t>(positive_number));
  11995. }
  11996. }
  11997. break;
  11998. }
  11999. case value_t::number_unsigned:
  12000. {
  12001. if (j.m_value.number_unsigned <= 0x17)
  12002. {
  12003. write_number(static_cast<std::uint8_t>(j.m_value.number_unsigned));
  12004. }
  12005. else if (j.m_value.number_unsigned <= (std::numeric_limits<std::uint8_t>::max)())
  12006. {
  12007. oa->write_character(to_char_type(0x18));
  12008. write_number(static_cast<std::uint8_t>(j.m_value.number_unsigned));
  12009. }
  12010. else if (j.m_value.number_unsigned <= (std::numeric_limits<std::uint16_t>::max)())
  12011. {
  12012. oa->write_character(to_char_type(0x19));
  12013. write_number(static_cast<std::uint16_t>(j.m_value.number_unsigned));
  12014. }
  12015. else if (j.m_value.number_unsigned <= (std::numeric_limits<std::uint32_t>::max)())
  12016. {
  12017. oa->write_character(to_char_type(0x1A));
  12018. write_number(static_cast<std::uint32_t>(j.m_value.number_unsigned));
  12019. }
  12020. else
  12021. {
  12022. oa->write_character(to_char_type(0x1B));
  12023. write_number(static_cast<std::uint64_t>(j.m_value.number_unsigned));
  12024. }
  12025. break;
  12026. }
  12027. case value_t::number_float:
  12028. {
  12029. if (std::isnan(j.m_value.number_float))
  12030. {
  12031. // NaN is 0xf97e00 in CBOR
  12032. oa->write_character(to_char_type(0xF9));
  12033. oa->write_character(to_char_type(0x7E));
  12034. oa->write_character(to_char_type(0x00));
  12035. }
  12036. else if (std::isinf(j.m_value.number_float))
  12037. {
  12038. // Infinity is 0xf97c00, -Infinity is 0xf9fc00
  12039. oa->write_character(to_char_type(0xf9));
  12040. oa->write_character(j.m_value.number_float > 0 ? to_char_type(0x7C) : to_char_type(0xFC));
  12041. oa->write_character(to_char_type(0x00));
  12042. }
  12043. else
  12044. {
  12045. write_compact_float(j.m_value.number_float, detail::input_format_t::cbor);
  12046. }
  12047. break;
  12048. }
  12049. case value_t::string:
  12050. {
  12051. // step 1: write control byte and the string length
  12052. const auto N = j.m_value.string->size();
  12053. if (N <= 0x17)
  12054. {
  12055. write_number(static_cast<std::uint8_t>(0x60 + N));
  12056. }
  12057. else if (N <= (std::numeric_limits<std::uint8_t>::max)())
  12058. {
  12059. oa->write_character(to_char_type(0x78));
  12060. write_number(static_cast<std::uint8_t>(N));
  12061. }
  12062. else if (N <= (std::numeric_limits<std::uint16_t>::max)())
  12063. {
  12064. oa->write_character(to_char_type(0x79));
  12065. write_number(static_cast<std::uint16_t>(N));
  12066. }
  12067. else if (N <= (std::numeric_limits<std::uint32_t>::max)())
  12068. {
  12069. oa->write_character(to_char_type(0x7A));
  12070. write_number(static_cast<std::uint32_t>(N));
  12071. }
  12072. // LCOV_EXCL_START
  12073. else if (N <= (std::numeric_limits<std::uint64_t>::max)())
  12074. {
  12075. oa->write_character(to_char_type(0x7B));
  12076. write_number(static_cast<std::uint64_t>(N));
  12077. }
  12078. // LCOV_EXCL_STOP
  12079. // step 2: write the string
  12080. oa->write_characters(
  12081. reinterpret_cast<const CharType*>(j.m_value.string->c_str()),
  12082. j.m_value.string->size());
  12083. break;
  12084. }
  12085. case value_t::array:
  12086. {
  12087. // step 1: write control byte and the array size
  12088. const auto N = j.m_value.array->size();
  12089. if (N <= 0x17)
  12090. {
  12091. write_number(static_cast<std::uint8_t>(0x80 + N));
  12092. }
  12093. else if (N <= (std::numeric_limits<std::uint8_t>::max)())
  12094. {
  12095. oa->write_character(to_char_type(0x98));
  12096. write_number(static_cast<std::uint8_t>(N));
  12097. }
  12098. else if (N <= (std::numeric_limits<std::uint16_t>::max)())
  12099. {
  12100. oa->write_character(to_char_type(0x99));
  12101. write_number(static_cast<std::uint16_t>(N));
  12102. }
  12103. else if (N <= (std::numeric_limits<std::uint32_t>::max)())
  12104. {
  12105. oa->write_character(to_char_type(0x9A));
  12106. write_number(static_cast<std::uint32_t>(N));
  12107. }
  12108. // LCOV_EXCL_START
  12109. else if (N <= (std::numeric_limits<std::uint64_t>::max)())
  12110. {
  12111. oa->write_character(to_char_type(0x9B));
  12112. write_number(static_cast<std::uint64_t>(N));
  12113. }
  12114. // LCOV_EXCL_STOP
  12115. // step 2: write each element
  12116. for (const auto& el : *j.m_value.array)
  12117. {
  12118. write_cbor(el);
  12119. }
  12120. break;
  12121. }
  12122. case value_t::binary:
  12123. {
  12124. if (j.m_value.binary->has_subtype())
  12125. {
  12126. if (j.m_value.binary->subtype() <= (std::numeric_limits<std::uint8_t>::max)())
  12127. {
  12128. write_number(static_cast<std::uint8_t>(0xd8));
  12129. write_number(static_cast<std::uint8_t>(j.m_value.binary->subtype()));
  12130. }
  12131. else if (j.m_value.binary->subtype() <= (std::numeric_limits<std::uint16_t>::max)())
  12132. {
  12133. write_number(static_cast<std::uint8_t>(0xd9));
  12134. write_number(static_cast<std::uint16_t>(j.m_value.binary->subtype()));
  12135. }
  12136. else if (j.m_value.binary->subtype() <= (std::numeric_limits<std::uint32_t>::max)())
  12137. {
  12138. write_number(static_cast<std::uint8_t>(0xda));
  12139. write_number(static_cast<std::uint32_t>(j.m_value.binary->subtype()));
  12140. }
  12141. else if (j.m_value.binary->subtype() <= (std::numeric_limits<std::uint64_t>::max)())
  12142. {
  12143. write_number(static_cast<std::uint8_t>(0xdb));
  12144. write_number(static_cast<std::uint64_t>(j.m_value.binary->subtype()));
  12145. }
  12146. }
  12147. // step 1: write control byte and the binary array size
  12148. const auto N = j.m_value.binary->size();
  12149. if (N <= 0x17)
  12150. {
  12151. write_number(static_cast<std::uint8_t>(0x40 + N));
  12152. }
  12153. else if (N <= (std::numeric_limits<std::uint8_t>::max)())
  12154. {
  12155. oa->write_character(to_char_type(0x58));
  12156. write_number(static_cast<std::uint8_t>(N));
  12157. }
  12158. else if (N <= (std::numeric_limits<std::uint16_t>::max)())
  12159. {
  12160. oa->write_character(to_char_type(0x59));
  12161. write_number(static_cast<std::uint16_t>(N));
  12162. }
  12163. else if (N <= (std::numeric_limits<std::uint32_t>::max)())
  12164. {
  12165. oa->write_character(to_char_type(0x5A));
  12166. write_number(static_cast<std::uint32_t>(N));
  12167. }
  12168. // LCOV_EXCL_START
  12169. else if (N <= (std::numeric_limits<std::uint64_t>::max)())
  12170. {
  12171. oa->write_character(to_char_type(0x5B));
  12172. write_number(static_cast<std::uint64_t>(N));
  12173. }
  12174. // LCOV_EXCL_STOP
  12175. // step 2: write each element
  12176. oa->write_characters(
  12177. reinterpret_cast<const CharType*>(j.m_value.binary->data()),
  12178. N);
  12179. break;
  12180. }
  12181. case value_t::object:
  12182. {
  12183. // step 1: write control byte and the object size
  12184. const auto N = j.m_value.object->size();
  12185. if (N <= 0x17)
  12186. {
  12187. write_number(static_cast<std::uint8_t>(0xA0 + N));
  12188. }
  12189. else if (N <= (std::numeric_limits<std::uint8_t>::max)())
  12190. {
  12191. oa->write_character(to_char_type(0xB8));
  12192. write_number(static_cast<std::uint8_t>(N));
  12193. }
  12194. else if (N <= (std::numeric_limits<std::uint16_t>::max)())
  12195. {
  12196. oa->write_character(to_char_type(0xB9));
  12197. write_number(static_cast<std::uint16_t>(N));
  12198. }
  12199. else if (N <= (std::numeric_limits<std::uint32_t>::max)())
  12200. {
  12201. oa->write_character(to_char_type(0xBA));
  12202. write_number(static_cast<std::uint32_t>(N));
  12203. }
  12204. // LCOV_EXCL_START
  12205. else if (N <= (std::numeric_limits<std::uint64_t>::max)())
  12206. {
  12207. oa->write_character(to_char_type(0xBB));
  12208. write_number(static_cast<std::uint64_t>(N));
  12209. }
  12210. // LCOV_EXCL_STOP
  12211. // step 2: write each element
  12212. for (const auto& el : *j.m_value.object)
  12213. {
  12214. write_cbor(el.first);
  12215. write_cbor(el.second);
  12216. }
  12217. break;
  12218. }
  12219. case value_t::discarded:
  12220. default:
  12221. break;
  12222. }
  12223. }
  12224. /*!
  12225. @param[in] j JSON value to serialize
  12226. */
  12227. void write_msgpack(const BasicJsonType& j)
  12228. {
  12229. switch (j.type())
  12230. {
  12231. case value_t::null: // nil
  12232. {
  12233. oa->write_character(to_char_type(0xC0));
  12234. break;
  12235. }
  12236. case value_t::boolean: // true and false
  12237. {
  12238. oa->write_character(j.m_value.boolean
  12239. ? to_char_type(0xC3)
  12240. : to_char_type(0xC2));
  12241. break;
  12242. }
  12243. case value_t::number_integer:
  12244. {
  12245. if (j.m_value.number_integer >= 0)
  12246. {
  12247. // MessagePack does not differentiate between positive
  12248. // signed integers and unsigned integers. Therefore, we used
  12249. // the code from the value_t::number_unsigned case here.
  12250. if (j.m_value.number_unsigned < 128)
  12251. {
  12252. // positive fixnum
  12253. write_number(static_cast<std::uint8_t>(j.m_value.number_integer));
  12254. }
  12255. else if (j.m_value.number_unsigned <= (std::numeric_limits<std::uint8_t>::max)())
  12256. {
  12257. // uint 8
  12258. oa->write_character(to_char_type(0xCC));
  12259. write_number(static_cast<std::uint8_t>(j.m_value.number_integer));
  12260. }
  12261. else if (j.m_value.number_unsigned <= (std::numeric_limits<std::uint16_t>::max)())
  12262. {
  12263. // uint 16
  12264. oa->write_character(to_char_type(0xCD));
  12265. write_number(static_cast<std::uint16_t>(j.m_value.number_integer));
  12266. }
  12267. else if (j.m_value.number_unsigned <= (std::numeric_limits<std::uint32_t>::max)())
  12268. {
  12269. // uint 32
  12270. oa->write_character(to_char_type(0xCE));
  12271. write_number(static_cast<std::uint32_t>(j.m_value.number_integer));
  12272. }
  12273. else if (j.m_value.number_unsigned <= (std::numeric_limits<std::uint64_t>::max)())
  12274. {
  12275. // uint 64
  12276. oa->write_character(to_char_type(0xCF));
  12277. write_number(static_cast<std::uint64_t>(j.m_value.number_integer));
  12278. }
  12279. }
  12280. else
  12281. {
  12282. if (j.m_value.number_integer >= -32)
  12283. {
  12284. // negative fixnum
  12285. write_number(static_cast<std::int8_t>(j.m_value.number_integer));
  12286. }
  12287. else if (j.m_value.number_integer >= (std::numeric_limits<std::int8_t>::min)() &&
  12288. j.m_value.number_integer <= (std::numeric_limits<std::int8_t>::max)())
  12289. {
  12290. // int 8
  12291. oa->write_character(to_char_type(0xD0));
  12292. write_number(static_cast<std::int8_t>(j.m_value.number_integer));
  12293. }
  12294. else if (j.m_value.number_integer >= (std::numeric_limits<std::int16_t>::min)() &&
  12295. j.m_value.number_integer <= (std::numeric_limits<std::int16_t>::max)())
  12296. {
  12297. // int 16
  12298. oa->write_character(to_char_type(0xD1));
  12299. write_number(static_cast<std::int16_t>(j.m_value.number_integer));
  12300. }
  12301. else if (j.m_value.number_integer >= (std::numeric_limits<std::int32_t>::min)() &&
  12302. j.m_value.number_integer <= (std::numeric_limits<std::int32_t>::max)())
  12303. {
  12304. // int 32
  12305. oa->write_character(to_char_type(0xD2));
  12306. write_number(static_cast<std::int32_t>(j.m_value.number_integer));
  12307. }
  12308. else if (j.m_value.number_integer >= (std::numeric_limits<std::int64_t>::min)() &&
  12309. j.m_value.number_integer <= (std::numeric_limits<std::int64_t>::max)())
  12310. {
  12311. // int 64
  12312. oa->write_character(to_char_type(0xD3));
  12313. write_number(static_cast<std::int64_t>(j.m_value.number_integer));
  12314. }
  12315. }
  12316. break;
  12317. }
  12318. case value_t::number_unsigned:
  12319. {
  12320. if (j.m_value.number_unsigned < 128)
  12321. {
  12322. // positive fixnum
  12323. write_number(static_cast<std::uint8_t>(j.m_value.number_integer));
  12324. }
  12325. else if (j.m_value.number_unsigned <= (std::numeric_limits<std::uint8_t>::max)())
  12326. {
  12327. // uint 8
  12328. oa->write_character(to_char_type(0xCC));
  12329. write_number(static_cast<std::uint8_t>(j.m_value.number_integer));
  12330. }
  12331. else if (j.m_value.number_unsigned <= (std::numeric_limits<std::uint16_t>::max)())
  12332. {
  12333. // uint 16
  12334. oa->write_character(to_char_type(0xCD));
  12335. write_number(static_cast<std::uint16_t>(j.m_value.number_integer));
  12336. }
  12337. else if (j.m_value.number_unsigned <= (std::numeric_limits<std::uint32_t>::max)())
  12338. {
  12339. // uint 32
  12340. oa->write_character(to_char_type(0xCE));
  12341. write_number(static_cast<std::uint32_t>(j.m_value.number_integer));
  12342. }
  12343. else if (j.m_value.number_unsigned <= (std::numeric_limits<std::uint64_t>::max)())
  12344. {
  12345. // uint 64
  12346. oa->write_character(to_char_type(0xCF));
  12347. write_number(static_cast<std::uint64_t>(j.m_value.number_integer));
  12348. }
  12349. break;
  12350. }
  12351. case value_t::number_float:
  12352. {
  12353. write_compact_float(j.m_value.number_float, detail::input_format_t::msgpack);
  12354. break;
  12355. }
  12356. case value_t::string:
  12357. {
  12358. // step 1: write control byte and the string length
  12359. const auto N = j.m_value.string->size();
  12360. if (N <= 31)
  12361. {
  12362. // fixstr
  12363. write_number(static_cast<std::uint8_t>(0xA0 | N));
  12364. }
  12365. else if (N <= (std::numeric_limits<std::uint8_t>::max)())
  12366. {
  12367. // str 8
  12368. oa->write_character(to_char_type(0xD9));
  12369. write_number(static_cast<std::uint8_t>(N));
  12370. }
  12371. else if (N <= (std::numeric_limits<std::uint16_t>::max)())
  12372. {
  12373. // str 16
  12374. oa->write_character(to_char_type(0xDA));
  12375. write_number(static_cast<std::uint16_t>(N));
  12376. }
  12377. else if (N <= (std::numeric_limits<std::uint32_t>::max)())
  12378. {
  12379. // str 32
  12380. oa->write_character(to_char_type(0xDB));
  12381. write_number(static_cast<std::uint32_t>(N));
  12382. }
  12383. // step 2: write the string
  12384. oa->write_characters(
  12385. reinterpret_cast<const CharType*>(j.m_value.string->c_str()),
  12386. j.m_value.string->size());
  12387. break;
  12388. }
  12389. case value_t::array:
  12390. {
  12391. // step 1: write control byte and the array size
  12392. const auto N = j.m_value.array->size();
  12393. if (N <= 15)
  12394. {
  12395. // fixarray
  12396. write_number(static_cast<std::uint8_t>(0x90 | N));
  12397. }
  12398. else if (N <= (std::numeric_limits<std::uint16_t>::max)())
  12399. {
  12400. // array 16
  12401. oa->write_character(to_char_type(0xDC));
  12402. write_number(static_cast<std::uint16_t>(N));
  12403. }
  12404. else if (N <= (std::numeric_limits<std::uint32_t>::max)())
  12405. {
  12406. // array 32
  12407. oa->write_character(to_char_type(0xDD));
  12408. write_number(static_cast<std::uint32_t>(N));
  12409. }
  12410. // step 2: write each element
  12411. for (const auto& el : *j.m_value.array)
  12412. {
  12413. write_msgpack(el);
  12414. }
  12415. break;
  12416. }
  12417. case value_t::binary:
  12418. {
  12419. // step 0: determine if the binary type has a set subtype to
  12420. // determine whether or not to use the ext or fixext types
  12421. const bool use_ext = j.m_value.binary->has_subtype();
  12422. // step 1: write control byte and the byte string length
  12423. const auto N = j.m_value.binary->size();
  12424. if (N <= (std::numeric_limits<std::uint8_t>::max)())
  12425. {
  12426. std::uint8_t output_type{};
  12427. bool fixed = true;
  12428. if (use_ext)
  12429. {
  12430. switch (N)
  12431. {
  12432. case 1:
  12433. output_type = 0xD4; // fixext 1
  12434. break;
  12435. case 2:
  12436. output_type = 0xD5; // fixext 2
  12437. break;
  12438. case 4:
  12439. output_type = 0xD6; // fixext 4
  12440. break;
  12441. case 8:
  12442. output_type = 0xD7; // fixext 8
  12443. break;
  12444. case 16:
  12445. output_type = 0xD8; // fixext 16
  12446. break;
  12447. default:
  12448. output_type = 0xC7; // ext 8
  12449. fixed = false;
  12450. break;
  12451. }
  12452. }
  12453. else
  12454. {
  12455. output_type = 0xC4; // bin 8
  12456. fixed = false;
  12457. }
  12458. oa->write_character(to_char_type(output_type));
  12459. if (!fixed)
  12460. {
  12461. write_number(static_cast<std::uint8_t>(N));
  12462. }
  12463. }
  12464. else if (N <= (std::numeric_limits<std::uint16_t>::max)())
  12465. {
  12466. std::uint8_t output_type = use_ext
  12467. ? 0xC8 // ext 16
  12468. : 0xC5; // bin 16
  12469. oa->write_character(to_char_type(output_type));
  12470. write_number(static_cast<std::uint16_t>(N));
  12471. }
  12472. else if (N <= (std::numeric_limits<std::uint32_t>::max)())
  12473. {
  12474. std::uint8_t output_type = use_ext
  12475. ? 0xC9 // ext 32
  12476. : 0xC6; // bin 32
  12477. oa->write_character(to_char_type(output_type));
  12478. write_number(static_cast<std::uint32_t>(N));
  12479. }
  12480. // step 1.5: if this is an ext type, write the subtype
  12481. if (use_ext)
  12482. {
  12483. write_number(static_cast<std::int8_t>(j.m_value.binary->subtype()));
  12484. }
  12485. // step 2: write the byte string
  12486. oa->write_characters(
  12487. reinterpret_cast<const CharType*>(j.m_value.binary->data()),
  12488. N);
  12489. break;
  12490. }
  12491. case value_t::object:
  12492. {
  12493. // step 1: write control byte and the object size
  12494. const auto N = j.m_value.object->size();
  12495. if (N <= 15)
  12496. {
  12497. // fixmap
  12498. write_number(static_cast<std::uint8_t>(0x80 | (N & 0xF)));
  12499. }
  12500. else if (N <= (std::numeric_limits<std::uint16_t>::max)())
  12501. {
  12502. // map 16
  12503. oa->write_character(to_char_type(0xDE));
  12504. write_number(static_cast<std::uint16_t>(N));
  12505. }
  12506. else if (N <= (std::numeric_limits<std::uint32_t>::max)())
  12507. {
  12508. // map 32
  12509. oa->write_character(to_char_type(0xDF));
  12510. write_number(static_cast<std::uint32_t>(N));
  12511. }
  12512. // step 2: write each element
  12513. for (const auto& el : *j.m_value.object)
  12514. {
  12515. write_msgpack(el.first);
  12516. write_msgpack(el.second);
  12517. }
  12518. break;
  12519. }
  12520. case value_t::discarded:
  12521. default:
  12522. break;
  12523. }
  12524. }
  12525. /*!
  12526. @param[in] j JSON value to serialize
  12527. @param[in] use_count whether to use '#' prefixes (optimized format)
  12528. @param[in] use_type whether to use '$' prefixes (optimized format)
  12529. @param[in] add_prefix whether prefixes need to be used for this value
  12530. */
  12531. void write_ubjson(const BasicJsonType& j, const bool use_count,
  12532. const bool use_type, const bool add_prefix = true)
  12533. {
  12534. switch (j.type())
  12535. {
  12536. case value_t::null:
  12537. {
  12538. if (add_prefix)
  12539. {
  12540. oa->write_character(to_char_type('Z'));
  12541. }
  12542. break;
  12543. }
  12544. case value_t::boolean:
  12545. {
  12546. if (add_prefix)
  12547. {
  12548. oa->write_character(j.m_value.boolean
  12549. ? to_char_type('T')
  12550. : to_char_type('F'));
  12551. }
  12552. break;
  12553. }
  12554. case value_t::number_integer:
  12555. {
  12556. write_number_with_ubjson_prefix(j.m_value.number_integer, add_prefix);
  12557. break;
  12558. }
  12559. case value_t::number_unsigned:
  12560. {
  12561. write_number_with_ubjson_prefix(j.m_value.number_unsigned, add_prefix);
  12562. break;
  12563. }
  12564. case value_t::number_float:
  12565. {
  12566. write_number_with_ubjson_prefix(j.m_value.number_float, add_prefix);
  12567. break;
  12568. }
  12569. case value_t::string:
  12570. {
  12571. if (add_prefix)
  12572. {
  12573. oa->write_character(to_char_type('S'));
  12574. }
  12575. write_number_with_ubjson_prefix(j.m_value.string->size(), true);
  12576. oa->write_characters(
  12577. reinterpret_cast<const CharType*>(j.m_value.string->c_str()),
  12578. j.m_value.string->size());
  12579. break;
  12580. }
  12581. case value_t::array:
  12582. {
  12583. if (add_prefix)
  12584. {
  12585. oa->write_character(to_char_type('['));
  12586. }
  12587. bool prefix_required = true;
  12588. if (use_type && !j.m_value.array->empty())
  12589. {
  12590. JSON_ASSERT(use_count);
  12591. const CharType first_prefix = ubjson_prefix(j.front());
  12592. const bool same_prefix = std::all_of(j.begin() + 1, j.end(),
  12593. [this, first_prefix](const BasicJsonType & v)
  12594. {
  12595. return ubjson_prefix(v) == first_prefix;
  12596. });
  12597. if (same_prefix)
  12598. {
  12599. prefix_required = false;
  12600. oa->write_character(to_char_type('$'));
  12601. oa->write_character(first_prefix);
  12602. }
  12603. }
  12604. if (use_count)
  12605. {
  12606. oa->write_character(to_char_type('#'));
  12607. write_number_with_ubjson_prefix(j.m_value.array->size(), true);
  12608. }
  12609. for (const auto& el : *j.m_value.array)
  12610. {
  12611. write_ubjson(el, use_count, use_type, prefix_required);
  12612. }
  12613. if (!use_count)
  12614. {
  12615. oa->write_character(to_char_type(']'));
  12616. }
  12617. break;
  12618. }
  12619. case value_t::binary:
  12620. {
  12621. if (add_prefix)
  12622. {
  12623. oa->write_character(to_char_type('['));
  12624. }
  12625. if (use_type && !j.m_value.binary->empty())
  12626. {
  12627. JSON_ASSERT(use_count);
  12628. oa->write_character(to_char_type('$'));
  12629. oa->write_character('U');
  12630. }
  12631. if (use_count)
  12632. {
  12633. oa->write_character(to_char_type('#'));
  12634. write_number_with_ubjson_prefix(j.m_value.binary->size(), true);
  12635. }
  12636. if (use_type)
  12637. {
  12638. oa->write_characters(
  12639. reinterpret_cast<const CharType*>(j.m_value.binary->data()),
  12640. j.m_value.binary->size());
  12641. }
  12642. else
  12643. {
  12644. for (size_t i = 0; i < j.m_value.binary->size(); ++i)
  12645. {
  12646. oa->write_character(to_char_type('U'));
  12647. oa->write_character(j.m_value.binary->data()[i]);
  12648. }
  12649. }
  12650. if (!use_count)
  12651. {
  12652. oa->write_character(to_char_type(']'));
  12653. }
  12654. break;
  12655. }
  12656. case value_t::object:
  12657. {
  12658. if (add_prefix)
  12659. {
  12660. oa->write_character(to_char_type('{'));
  12661. }
  12662. bool prefix_required = true;
  12663. if (use_type && !j.m_value.object->empty())
  12664. {
  12665. JSON_ASSERT(use_count);
  12666. const CharType first_prefix = ubjson_prefix(j.front());
  12667. const bool same_prefix = std::all_of(j.begin(), j.end(),
  12668. [this, first_prefix](const BasicJsonType & v)
  12669. {
  12670. return ubjson_prefix(v) == first_prefix;
  12671. });
  12672. if (same_prefix)
  12673. {
  12674. prefix_required = false;
  12675. oa->write_character(to_char_type('$'));
  12676. oa->write_character(first_prefix);
  12677. }
  12678. }
  12679. if (use_count)
  12680. {
  12681. oa->write_character(to_char_type('#'));
  12682. write_number_with_ubjson_prefix(j.m_value.object->size(), true);
  12683. }
  12684. for (const auto& el : *j.m_value.object)
  12685. {
  12686. write_number_with_ubjson_prefix(el.first.size(), true);
  12687. oa->write_characters(
  12688. reinterpret_cast<const CharType*>(el.first.c_str()),
  12689. el.first.size());
  12690. write_ubjson(el.second, use_count, use_type, prefix_required);
  12691. }
  12692. if (!use_count)
  12693. {
  12694. oa->write_character(to_char_type('}'));
  12695. }
  12696. break;
  12697. }
  12698. case value_t::discarded:
  12699. default:
  12700. break;
  12701. }
  12702. }
  12703. private:
  12704. //////////
  12705. // BSON //
  12706. //////////
  12707. /*!
  12708. @return The size of a BSON document entry header, including the id marker
  12709. and the entry name size (and its null-terminator).
  12710. */
  12711. static std::size_t calc_bson_entry_header_size(const string_t& name, const BasicJsonType& j)
  12712. {
  12713. const auto it = name.find(static_cast<typename string_t::value_type>(0));
  12714. if (JSON_HEDLEY_UNLIKELY(it != BasicJsonType::string_t::npos))
  12715. {
  12716. JSON_THROW(out_of_range::create(409, "BSON key cannot contain code point U+0000 (at byte " + std::to_string(it) + ")", j));
  12717. static_cast<void>(j);
  12718. }
  12719. return /*id*/ 1ul + name.size() + /*zero-terminator*/1u;
  12720. }
  12721. /*!
  12722. @brief Writes the given @a element_type and @a name to the output adapter
  12723. */
  12724. void write_bson_entry_header(const string_t& name,
  12725. const std::uint8_t element_type)
  12726. {
  12727. oa->write_character(to_char_type(element_type)); // boolean
  12728. oa->write_characters(
  12729. reinterpret_cast<const CharType*>(name.c_str()),
  12730. name.size() + 1u);
  12731. }
  12732. /*!
  12733. @brief Writes a BSON element with key @a name and boolean value @a value
  12734. */
  12735. void write_bson_boolean(const string_t& name,
  12736. const bool value)
  12737. {
  12738. write_bson_entry_header(name, 0x08);
  12739. oa->write_character(value ? to_char_type(0x01) : to_char_type(0x00));
  12740. }
  12741. /*!
  12742. @brief Writes a BSON element with key @a name and double value @a value
  12743. */
  12744. void write_bson_double(const string_t& name,
  12745. const double value)
  12746. {
  12747. write_bson_entry_header(name, 0x01);
  12748. write_number<double, true>(value);
  12749. }
  12750. /*!
  12751. @return The size of the BSON-encoded string in @a value
  12752. */
  12753. static std::size_t calc_bson_string_size(const string_t& value)
  12754. {
  12755. return sizeof(std::int32_t) + value.size() + 1ul;
  12756. }
  12757. /*!
  12758. @brief Writes a BSON element with key @a name and string value @a value
  12759. */
  12760. void write_bson_string(const string_t& name,
  12761. const string_t& value)
  12762. {
  12763. write_bson_entry_header(name, 0x02);
  12764. write_number<std::int32_t, true>(static_cast<std::int32_t>(value.size() + 1ul));
  12765. oa->write_characters(
  12766. reinterpret_cast<const CharType*>(value.c_str()),
  12767. value.size() + 1);
  12768. }
  12769. /*!
  12770. @brief Writes a BSON element with key @a name and null value
  12771. */
  12772. void write_bson_null(const string_t& name)
  12773. {
  12774. write_bson_entry_header(name, 0x0A);
  12775. }
  12776. /*!
  12777. @return The size of the BSON-encoded integer @a value
  12778. */
  12779. static std::size_t calc_bson_integer_size(const std::int64_t value)
  12780. {
  12781. return (std::numeric_limits<std::int32_t>::min)() <= value && value <= (std::numeric_limits<std::int32_t>::max)()
  12782. ? sizeof(std::int32_t)
  12783. : sizeof(std::int64_t);
  12784. }
  12785. /*!
  12786. @brief Writes a BSON element with key @a name and integer @a value
  12787. */
  12788. void write_bson_integer(const string_t& name,
  12789. const std::int64_t value)
  12790. {
  12791. if ((std::numeric_limits<std::int32_t>::min)() <= value && value <= (std::numeric_limits<std::int32_t>::max)())
  12792. {
  12793. write_bson_entry_header(name, 0x10); // int32
  12794. write_number<std::int32_t, true>(static_cast<std::int32_t>(value));
  12795. }
  12796. else
  12797. {
  12798. write_bson_entry_header(name, 0x12); // int64
  12799. write_number<std::int64_t, true>(static_cast<std::int64_t>(value));
  12800. }
  12801. }
  12802. /*!
  12803. @return The size of the BSON-encoded unsigned integer in @a j
  12804. */
  12805. static constexpr std::size_t calc_bson_unsigned_size(const std::uint64_t value) noexcept
  12806. {
  12807. return (value <= static_cast<std::uint64_t>((std::numeric_limits<std::int32_t>::max)()))
  12808. ? sizeof(std::int32_t)
  12809. : sizeof(std::int64_t);
  12810. }
  12811. /*!
  12812. @brief Writes a BSON element with key @a name and unsigned @a value
  12813. */
  12814. void write_bson_unsigned(const string_t& name,
  12815. const BasicJsonType& j)
  12816. {
  12817. if (j.m_value.number_unsigned <= static_cast<std::uint64_t>((std::numeric_limits<std::int32_t>::max)()))
  12818. {
  12819. write_bson_entry_header(name, 0x10 /* int32 */);
  12820. write_number<std::int32_t, true>(static_cast<std::int32_t>(j.m_value.number_unsigned));
  12821. }
  12822. else if (j.m_value.number_unsigned <= static_cast<std::uint64_t>((std::numeric_limits<std::int64_t>::max)()))
  12823. {
  12824. write_bson_entry_header(name, 0x12 /* int64 */);
  12825. write_number<std::int64_t, true>(static_cast<std::int64_t>(j.m_value.number_unsigned));
  12826. }
  12827. else
  12828. {
  12829. 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));
  12830. }
  12831. }
  12832. /*!
  12833. @brief Writes a BSON element with key @a name and object @a value
  12834. */
  12835. void write_bson_object_entry(const string_t& name,
  12836. const typename BasicJsonType::object_t& value)
  12837. {
  12838. write_bson_entry_header(name, 0x03); // object
  12839. write_bson_object(value);
  12840. }
  12841. /*!
  12842. @return The size of the BSON-encoded array @a value
  12843. */
  12844. static std::size_t calc_bson_array_size(const typename BasicJsonType::array_t& value)
  12845. {
  12846. std::size_t array_index = 0ul;
  12847. 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)
  12848. {
  12849. return result + calc_bson_element_size(std::to_string(array_index++), el);
  12850. });
  12851. return sizeof(std::int32_t) + embedded_document_size + 1ul;
  12852. }
  12853. /*!
  12854. @return The size of the BSON-encoded binary array @a value
  12855. */
  12856. static std::size_t calc_bson_binary_size(const typename BasicJsonType::binary_t& value)
  12857. {
  12858. return sizeof(std::int32_t) + value.size() + 1ul;
  12859. }
  12860. /*!
  12861. @brief Writes a BSON element with key @a name and array @a value
  12862. */
  12863. void write_bson_array(const string_t& name,
  12864. const typename BasicJsonType::array_t& value)
  12865. {
  12866. write_bson_entry_header(name, 0x04); // array
  12867. write_number<std::int32_t, true>(static_cast<std::int32_t>(calc_bson_array_size(value)));
  12868. std::size_t array_index = 0ul;
  12869. for (const auto& el : value)
  12870. {
  12871. write_bson_element(std::to_string(array_index++), el);
  12872. }
  12873. oa->write_character(to_char_type(0x00));
  12874. }
  12875. /*!
  12876. @brief Writes a BSON element with key @a name and binary value @a value
  12877. */
  12878. void write_bson_binary(const string_t& name,
  12879. const binary_t& value)
  12880. {
  12881. write_bson_entry_header(name, 0x05);
  12882. write_number<std::int32_t, true>(static_cast<std::int32_t>(value.size()));
  12883. write_number(value.has_subtype() ? static_cast<std::uint8_t>(value.subtype()) : std::uint8_t(0x00));
  12884. oa->write_characters(reinterpret_cast<const CharType*>(value.data()), value.size());
  12885. }
  12886. /*!
  12887. @brief Calculates the size necessary to serialize the JSON value @a j with its @a name
  12888. @return The calculated size for the BSON document entry for @a j with the given @a name.
  12889. */
  12890. static std::size_t calc_bson_element_size(const string_t& name,
  12891. const BasicJsonType& j)
  12892. {
  12893. const auto header_size = calc_bson_entry_header_size(name, j);
  12894. switch (j.type())
  12895. {
  12896. case value_t::object:
  12897. return header_size + calc_bson_object_size(*j.m_value.object);
  12898. case value_t::array:
  12899. return header_size + calc_bson_array_size(*j.m_value.array);
  12900. case value_t::binary:
  12901. return header_size + calc_bson_binary_size(*j.m_value.binary);
  12902. case value_t::boolean:
  12903. return header_size + 1ul;
  12904. case value_t::number_float:
  12905. return header_size + 8ul;
  12906. case value_t::number_integer:
  12907. return header_size + calc_bson_integer_size(j.m_value.number_integer);
  12908. case value_t::number_unsigned:
  12909. return header_size + calc_bson_unsigned_size(j.m_value.number_unsigned);
  12910. case value_t::string:
  12911. return header_size + calc_bson_string_size(*j.m_value.string);
  12912. case value_t::null:
  12913. return header_size + 0ul;
  12914. // LCOV_EXCL_START
  12915. case value_t::discarded:
  12916. default:
  12917. JSON_ASSERT(false); // NOLINT(cert-dcl03-c,hicpp-static-assert,misc-static-assert)
  12918. return 0ul;
  12919. // LCOV_EXCL_STOP
  12920. }
  12921. }
  12922. /*!
  12923. @brief Serializes the JSON value @a j to BSON and associates it with the
  12924. key @a name.
  12925. @param name The name to associate with the JSON entity @a j within the
  12926. current BSON document
  12927. */
  12928. void write_bson_element(const string_t& name,
  12929. const BasicJsonType& j)
  12930. {
  12931. switch (j.type())
  12932. {
  12933. case value_t::object:
  12934. return write_bson_object_entry(name, *j.m_value.object);
  12935. case value_t::array:
  12936. return write_bson_array(name, *j.m_value.array);
  12937. case value_t::binary:
  12938. return write_bson_binary(name, *j.m_value.binary);
  12939. case value_t::boolean:
  12940. return write_bson_boolean(name, j.m_value.boolean);
  12941. case value_t::number_float:
  12942. return write_bson_double(name, j.m_value.number_float);
  12943. case value_t::number_integer:
  12944. return write_bson_integer(name, j.m_value.number_integer);
  12945. case value_t::number_unsigned:
  12946. return write_bson_unsigned(name, j);
  12947. case value_t::string:
  12948. return write_bson_string(name, *j.m_value.string);
  12949. case value_t::null:
  12950. return write_bson_null(name);
  12951. // LCOV_EXCL_START
  12952. case value_t::discarded:
  12953. default:
  12954. JSON_ASSERT(false); // NOLINT(cert-dcl03-c,hicpp-static-assert,misc-static-assert)
  12955. return;
  12956. // LCOV_EXCL_STOP
  12957. }
  12958. }
  12959. /*!
  12960. @brief Calculates the size of the BSON serialization of the given
  12961. JSON-object @a j.
  12962. @param[in] value JSON value to serialize
  12963. @pre value.type() == value_t::object
  12964. */
  12965. static std::size_t calc_bson_object_size(const typename BasicJsonType::object_t& value)
  12966. {
  12967. std::size_t document_size = std::accumulate(value.begin(), value.end(), std::size_t(0),
  12968. [](size_t result, const typename BasicJsonType::object_t::value_type & el)
  12969. {
  12970. return result += calc_bson_element_size(el.first, el.second);
  12971. });
  12972. return sizeof(std::int32_t) + document_size + 1ul;
  12973. }
  12974. /*!
  12975. @param[in] value JSON value to serialize
  12976. @pre value.type() == value_t::object
  12977. */
  12978. void write_bson_object(const typename BasicJsonType::object_t& value)
  12979. {
  12980. write_number<std::int32_t, true>(static_cast<std::int32_t>(calc_bson_object_size(value)));
  12981. for (const auto& el : value)
  12982. {
  12983. write_bson_element(el.first, el.second);
  12984. }
  12985. oa->write_character(to_char_type(0x00));
  12986. }
  12987. //////////
  12988. // CBOR //
  12989. //////////
  12990. static constexpr CharType get_cbor_float_prefix(float /*unused*/)
  12991. {
  12992. return to_char_type(0xFA); // Single-Precision Float
  12993. }
  12994. static constexpr CharType get_cbor_float_prefix(double /*unused*/)
  12995. {
  12996. return to_char_type(0xFB); // Double-Precision Float
  12997. }
  12998. /////////////
  12999. // MsgPack //
  13000. /////////////
  13001. static constexpr CharType get_msgpack_float_prefix(float /*unused*/)
  13002. {
  13003. return to_char_type(0xCA); // float 32
  13004. }
  13005. static constexpr CharType get_msgpack_float_prefix(double /*unused*/)
  13006. {
  13007. return to_char_type(0xCB); // float 64
  13008. }
  13009. ////////////
  13010. // UBJSON //
  13011. ////////////
  13012. // UBJSON: write number (floating point)
  13013. template<typename NumberType, typename std::enable_if<
  13014. std::is_floating_point<NumberType>::value, int>::type = 0>
  13015. void write_number_with_ubjson_prefix(const NumberType n,
  13016. const bool add_prefix)
  13017. {
  13018. if (add_prefix)
  13019. {
  13020. oa->write_character(get_ubjson_float_prefix(n));
  13021. }
  13022. write_number(n);
  13023. }
  13024. // UBJSON: write number (unsigned integer)
  13025. template<typename NumberType, typename std::enable_if<
  13026. std::is_unsigned<NumberType>::value, int>::type = 0>
  13027. void write_number_with_ubjson_prefix(const NumberType n,
  13028. const bool add_prefix)
  13029. {
  13030. if (n <= static_cast<std::uint64_t>((std::numeric_limits<std::int8_t>::max)()))
  13031. {
  13032. if (add_prefix)
  13033. {
  13034. oa->write_character(to_char_type('i')); // int8
  13035. }
  13036. write_number(static_cast<std::uint8_t>(n));
  13037. }
  13038. else if (n <= (std::numeric_limits<std::uint8_t>::max)())
  13039. {
  13040. if (add_prefix)
  13041. {
  13042. oa->write_character(to_char_type('U')); // uint8
  13043. }
  13044. write_number(static_cast<std::uint8_t>(n));
  13045. }
  13046. else if (n <= static_cast<std::uint64_t>((std::numeric_limits<std::int16_t>::max)()))
  13047. {
  13048. if (add_prefix)
  13049. {
  13050. oa->write_character(to_char_type('I')); // int16
  13051. }
  13052. write_number(static_cast<std::int16_t>(n));
  13053. }
  13054. else if (n <= static_cast<std::uint64_t>((std::numeric_limits<std::int32_t>::max)()))
  13055. {
  13056. if (add_prefix)
  13057. {
  13058. oa->write_character(to_char_type('l')); // int32
  13059. }
  13060. write_number(static_cast<std::int32_t>(n));
  13061. }
  13062. else if (n <= static_cast<std::uint64_t>((std::numeric_limits<std::int64_t>::max)()))
  13063. {
  13064. if (add_prefix)
  13065. {
  13066. oa->write_character(to_char_type('L')); // int64
  13067. }
  13068. write_number(static_cast<std::int64_t>(n));
  13069. }
  13070. else
  13071. {
  13072. if (add_prefix)
  13073. {
  13074. oa->write_character(to_char_type('H')); // high-precision number
  13075. }
  13076. const auto number = BasicJsonType(n).dump();
  13077. write_number_with_ubjson_prefix(number.size(), true);
  13078. for (std::size_t i = 0; i < number.size(); ++i)
  13079. {
  13080. oa->write_character(to_char_type(static_cast<std::uint8_t>(number[i])));
  13081. }
  13082. }
  13083. }
  13084. // UBJSON: write number (signed integer)
  13085. template < typename NumberType, typename std::enable_if <
  13086. std::is_signed<NumberType>::value&&
  13087. !std::is_floating_point<NumberType>::value, int >::type = 0 >
  13088. void write_number_with_ubjson_prefix(const NumberType n,
  13089. const bool add_prefix)
  13090. {
  13091. if ((std::numeric_limits<std::int8_t>::min)() <= n && n <= (std::numeric_limits<std::int8_t>::max)())
  13092. {
  13093. if (add_prefix)
  13094. {
  13095. oa->write_character(to_char_type('i')); // int8
  13096. }
  13097. write_number(static_cast<std::int8_t>(n));
  13098. }
  13099. 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)()))
  13100. {
  13101. if (add_prefix)
  13102. {
  13103. oa->write_character(to_char_type('U')); // uint8
  13104. }
  13105. write_number(static_cast<std::uint8_t>(n));
  13106. }
  13107. else if ((std::numeric_limits<std::int16_t>::min)() <= n && n <= (std::numeric_limits<std::int16_t>::max)())
  13108. {
  13109. if (add_prefix)
  13110. {
  13111. oa->write_character(to_char_type('I')); // int16
  13112. }
  13113. write_number(static_cast<std::int16_t>(n));
  13114. }
  13115. else if ((std::numeric_limits<std::int32_t>::min)() <= n && n <= (std::numeric_limits<std::int32_t>::max)())
  13116. {
  13117. if (add_prefix)
  13118. {
  13119. oa->write_character(to_char_type('l')); // int32
  13120. }
  13121. write_number(static_cast<std::int32_t>(n));
  13122. }
  13123. else if ((std::numeric_limits<std::int64_t>::min)() <= n && n <= (std::numeric_limits<std::int64_t>::max)())
  13124. {
  13125. if (add_prefix)
  13126. {
  13127. oa->write_character(to_char_type('L')); // int64
  13128. }
  13129. write_number(static_cast<std::int64_t>(n));
  13130. }
  13131. // LCOV_EXCL_START
  13132. else
  13133. {
  13134. if (add_prefix)
  13135. {
  13136. oa->write_character(to_char_type('H')); // high-precision number
  13137. }
  13138. const auto number = BasicJsonType(n).dump();
  13139. write_number_with_ubjson_prefix(number.size(), true);
  13140. for (std::size_t i = 0; i < number.size(); ++i)
  13141. {
  13142. oa->write_character(to_char_type(static_cast<std::uint8_t>(number[i])));
  13143. }
  13144. }
  13145. // LCOV_EXCL_STOP
  13146. }
  13147. /*!
  13148. @brief determine the type prefix of container values
  13149. */
  13150. CharType ubjson_prefix(const BasicJsonType& j) const noexcept
  13151. {
  13152. switch (j.type())
  13153. {
  13154. case value_t::null:
  13155. return 'Z';
  13156. case value_t::boolean:
  13157. return j.m_value.boolean ? 'T' : 'F';
  13158. case value_t::number_integer:
  13159. {
  13160. 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)())
  13161. {
  13162. return 'i';
  13163. }
  13164. 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)())
  13165. {
  13166. return 'U';
  13167. }
  13168. 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)())
  13169. {
  13170. return 'I';
  13171. }
  13172. 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)())
  13173. {
  13174. return 'l';
  13175. }
  13176. 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)())
  13177. {
  13178. return 'L';
  13179. }
  13180. // anything else is treated as high-precision number
  13181. return 'H'; // LCOV_EXCL_LINE
  13182. }
  13183. case value_t::number_unsigned:
  13184. {
  13185. if (j.m_value.number_unsigned <= static_cast<std::uint64_t>((std::numeric_limits<std::int8_t>::max)()))
  13186. {
  13187. return 'i';
  13188. }
  13189. if (j.m_value.number_unsigned <= static_cast<std::uint64_t>((std::numeric_limits<std::uint8_t>::max)()))
  13190. {
  13191. return 'U';
  13192. }
  13193. if (j.m_value.number_unsigned <= static_cast<std::uint64_t>((std::numeric_limits<std::int16_t>::max)()))
  13194. {
  13195. return 'I';
  13196. }
  13197. if (j.m_value.number_unsigned <= static_cast<std::uint64_t>((std::numeric_limits<std::int32_t>::max)()))
  13198. {
  13199. return 'l';
  13200. }
  13201. if (j.m_value.number_unsigned <= static_cast<std::uint64_t>((std::numeric_limits<std::int64_t>::max)()))
  13202. {
  13203. return 'L';
  13204. }
  13205. // anything else is treated as high-precision number
  13206. return 'H'; // LCOV_EXCL_LINE
  13207. }
  13208. case value_t::number_float:
  13209. return get_ubjson_float_prefix(j.m_value.number_float);
  13210. case value_t::string:
  13211. return 'S';
  13212. case value_t::array: // fallthrough
  13213. case value_t::binary:
  13214. return '[';
  13215. case value_t::object:
  13216. return '{';
  13217. case value_t::discarded:
  13218. default: // discarded values
  13219. return 'N';
  13220. }
  13221. }
  13222. static constexpr CharType get_ubjson_float_prefix(float /*unused*/)
  13223. {
  13224. return 'd'; // float 32
  13225. }
  13226. static constexpr CharType get_ubjson_float_prefix(double /*unused*/)
  13227. {
  13228. return 'D'; // float 64
  13229. }
  13230. ///////////////////////
  13231. // Utility functions //
  13232. ///////////////////////
  13233. /*
  13234. @brief write a number to output input
  13235. @param[in] n number of type @a NumberType
  13236. @tparam NumberType the type of the number
  13237. @tparam OutputIsLittleEndian Set to true if output data is
  13238. required to be little endian
  13239. @note This function needs to respect the system's endianess, because bytes
  13240. in CBOR, MessagePack, and UBJSON are stored in network order (big
  13241. endian) and therefore need reordering on little endian systems.
  13242. */
  13243. template<typename NumberType, bool OutputIsLittleEndian = false>
  13244. void write_number(const NumberType n)
  13245. {
  13246. // step 1: write number to array of length NumberType
  13247. std::array<CharType, sizeof(NumberType)> vec{};
  13248. std::memcpy(vec.data(), &n, sizeof(NumberType));
  13249. // step 2: write array to output (with possible reordering)
  13250. if (is_little_endian != OutputIsLittleEndian)
  13251. {
  13252. // reverse byte order prior to conversion if necessary
  13253. std::reverse(vec.begin(), vec.end());
  13254. }
  13255. oa->write_characters(vec.data(), sizeof(NumberType));
  13256. }
  13257. void write_compact_float(const number_float_t n, detail::input_format_t format)
  13258. {
  13259. #ifdef __GNUC__
  13260. #pragma GCC diagnostic push
  13261. #pragma GCC diagnostic ignored "-Wfloat-equal"
  13262. #endif
  13263. if (static_cast<double>(n) >= static_cast<double>(std::numeric_limits<float>::lowest()) &&
  13264. static_cast<double>(n) <= static_cast<double>((std::numeric_limits<float>::max)()) &&
  13265. static_cast<double>(static_cast<float>(n)) == static_cast<double>(n))
  13266. {
  13267. oa->write_character(format == detail::input_format_t::cbor
  13268. ? get_cbor_float_prefix(static_cast<float>(n))
  13269. : get_msgpack_float_prefix(static_cast<float>(n)));
  13270. write_number(static_cast<float>(n));
  13271. }
  13272. else
  13273. {
  13274. oa->write_character(format == detail::input_format_t::cbor
  13275. ? get_cbor_float_prefix(n)
  13276. : get_msgpack_float_prefix(n));
  13277. write_number(n);
  13278. }
  13279. #ifdef __GNUC__
  13280. #pragma GCC diagnostic pop
  13281. #endif
  13282. }
  13283. public:
  13284. // The following to_char_type functions are implement the conversion
  13285. // between uint8_t and CharType. In case CharType is not unsigned,
  13286. // such a conversion is required to allow values greater than 128.
  13287. // See <https://github.com/nlohmann/json/issues/1286> for a discussion.
  13288. template < typename C = CharType,
  13289. enable_if_t < std::is_signed<C>::value && std::is_signed<char>::value > * = nullptr >
  13290. static constexpr CharType to_char_type(std::uint8_t x) noexcept
  13291. {
  13292. return *reinterpret_cast<char*>(&x);
  13293. }
  13294. template < typename C = CharType,
  13295. enable_if_t < std::is_signed<C>::value && std::is_unsigned<char>::value > * = nullptr >
  13296. static CharType to_char_type(std::uint8_t x) noexcept
  13297. {
  13298. static_assert(sizeof(std::uint8_t) == sizeof(CharType), "size of CharType must be equal to std::uint8_t");
  13299. static_assert(std::is_trivial<CharType>::value, "CharType must be trivial");
  13300. CharType result;
  13301. std::memcpy(&result, &x, sizeof(x));
  13302. return result;
  13303. }
  13304. template<typename C = CharType,
  13305. enable_if_t<std::is_unsigned<C>::value>* = nullptr>
  13306. static constexpr CharType to_char_type(std::uint8_t x) noexcept
  13307. {
  13308. return x;
  13309. }
  13310. template < typename InputCharType, typename C = CharType,
  13311. enable_if_t <
  13312. std::is_signed<C>::value &&
  13313. std::is_signed<char>::value &&
  13314. std::is_same<char, typename std::remove_cv<InputCharType>::type>::value
  13315. > * = nullptr >
  13316. static constexpr CharType to_char_type(InputCharType x) noexcept
  13317. {
  13318. return x;
  13319. }
  13320. private:
  13321. /// whether we can assume little endianess
  13322. const bool is_little_endian = little_endianess();
  13323. /// the output
  13324. output_adapter_t<CharType> oa = nullptr;
  13325. };
  13326. } // namespace detail
  13327. } // namespace nlohmann
  13328. // #include <nlohmann/detail/output/output_adapters.hpp>
  13329. // #include <nlohmann/detail/output/serializer.hpp>
  13330. #include <algorithm> // reverse, remove, fill, find, none_of
  13331. #include <array> // array
  13332. #include <clocale> // localeconv, lconv
  13333. #include <cmath> // labs, isfinite, isnan, signbit
  13334. #include <cstddef> // size_t, ptrdiff_t
  13335. #include <cstdint> // uint8_t
  13336. #include <cstdio> // snprintf
  13337. #include <limits> // numeric_limits
  13338. #include <string> // string, char_traits
  13339. #include <type_traits> // is_same
  13340. #include <utility> // move
  13341. // #include <nlohmann/detail/conversions/to_chars.hpp>
  13342. #include <array> // array
  13343. #include <cmath> // signbit, isfinite
  13344. #include <cstdint> // intN_t, uintN_t
  13345. #include <cstring> // memcpy, memmove
  13346. #include <limits> // numeric_limits
  13347. #include <type_traits> // conditional
  13348. // #include <nlohmann/detail/macro_scope.hpp>
  13349. namespace nlohmann
  13350. {
  13351. namespace detail
  13352. {
  13353. /*!
  13354. @brief implements the Grisu2 algorithm for binary to decimal floating-point
  13355. conversion.
  13356. This implementation is a slightly modified version of the reference
  13357. implementation which may be obtained from
  13358. http://florian.loitsch.com/publications (bench.tar.gz).
  13359. The code is distributed under the MIT license, Copyright (c) 2009 Florian Loitsch.
  13360. For a detailed description of the algorithm see:
  13361. [1] Loitsch, "Printing Floating-Point Numbers Quickly and Accurately with
  13362. Integers", Proceedings of the ACM SIGPLAN 2010 Conference on Programming
  13363. Language Design and Implementation, PLDI 2010
  13364. [2] Burger, Dybvig, "Printing Floating-Point Numbers Quickly and Accurately",
  13365. Proceedings of the ACM SIGPLAN 1996 Conference on Programming Language
  13366. Design and Implementation, PLDI 1996
  13367. */
  13368. namespace dtoa_impl
  13369. {
  13370. template<typename Target, typename Source>
  13371. Target reinterpret_bits(const Source source)
  13372. {
  13373. static_assert(sizeof(Target) == sizeof(Source), "size mismatch");
  13374. Target target;
  13375. std::memcpy(&target, &source, sizeof(Source));
  13376. return target;
  13377. }
  13378. struct diyfp // f * 2^e
  13379. {
  13380. static constexpr int kPrecision = 64; // = q
  13381. std::uint64_t f = 0;
  13382. int e = 0;
  13383. constexpr diyfp(std::uint64_t f_, int e_) noexcept : f(f_), e(e_) {}
  13384. /*!
  13385. @brief returns x - y
  13386. @pre x.e == y.e and x.f >= y.f
  13387. */
  13388. static diyfp sub(const diyfp& x, const diyfp& y) noexcept
  13389. {
  13390. JSON_ASSERT(x.e == y.e);
  13391. JSON_ASSERT(x.f >= y.f);
  13392. return {x.f - y.f, x.e};
  13393. }
  13394. /*!
  13395. @brief returns x * y
  13396. @note The result is rounded. (Only the upper q bits are returned.)
  13397. */
  13398. static diyfp mul(const diyfp& x, const diyfp& y) noexcept
  13399. {
  13400. static_assert(kPrecision == 64, "internal error");
  13401. // Computes:
  13402. // f = round((x.f * y.f) / 2^q)
  13403. // e = x.e + y.e + q
  13404. // Emulate the 64-bit * 64-bit multiplication:
  13405. //
  13406. // p = u * v
  13407. // = (u_lo + 2^32 u_hi) (v_lo + 2^32 v_hi)
  13408. // = (u_lo v_lo ) + 2^32 ((u_lo v_hi ) + (u_hi v_lo )) + 2^64 (u_hi v_hi )
  13409. // = (p0 ) + 2^32 ((p1 ) + (p2 )) + 2^64 (p3 )
  13410. // = (p0_lo + 2^32 p0_hi) + 2^32 ((p1_lo + 2^32 p1_hi) + (p2_lo + 2^32 p2_hi)) + 2^64 (p3 )
  13411. // = (p0_lo ) + 2^32 (p0_hi + p1_lo + p2_lo ) + 2^64 (p1_hi + p2_hi + p3)
  13412. // = (p0_lo ) + 2^32 (Q ) + 2^64 (H )
  13413. // = (p0_lo ) + 2^32 (Q_lo + 2^32 Q_hi ) + 2^64 (H )
  13414. //
  13415. // (Since Q might be larger than 2^32 - 1)
  13416. //
  13417. // = (p0_lo + 2^32 Q_lo) + 2^64 (Q_hi + H)
  13418. //
  13419. // (Q_hi + H does not overflow a 64-bit int)
  13420. //
  13421. // = p_lo + 2^64 p_hi
  13422. const std::uint64_t u_lo = x.f & 0xFFFFFFFFu;
  13423. const std::uint64_t u_hi = x.f >> 32u;
  13424. const std::uint64_t v_lo = y.f & 0xFFFFFFFFu;
  13425. const std::uint64_t v_hi = y.f >> 32u;
  13426. const std::uint64_t p0 = u_lo * v_lo;
  13427. const std::uint64_t p1 = u_lo * v_hi;
  13428. const std::uint64_t p2 = u_hi * v_lo;
  13429. const std::uint64_t p3 = u_hi * v_hi;
  13430. const std::uint64_t p0_hi = p0 >> 32u;
  13431. const std::uint64_t p1_lo = p1 & 0xFFFFFFFFu;
  13432. const std::uint64_t p1_hi = p1 >> 32u;
  13433. const std::uint64_t p2_lo = p2 & 0xFFFFFFFFu;
  13434. const std::uint64_t p2_hi = p2 >> 32u;
  13435. std::uint64_t Q = p0_hi + p1_lo + p2_lo;
  13436. // The full product might now be computed as
  13437. //
  13438. // p_hi = p3 + p2_hi + p1_hi + (Q >> 32)
  13439. // p_lo = p0_lo + (Q << 32)
  13440. //
  13441. // But in this particular case here, the full p_lo is not required.
  13442. // Effectively we only need to add the highest bit in p_lo to p_hi (and
  13443. // Q_hi + 1 does not overflow).
  13444. Q += std::uint64_t{1} << (64u - 32u - 1u); // round, ties up
  13445. const std::uint64_t h = p3 + p2_hi + p1_hi + (Q >> 32u);
  13446. return {h, x.e + y.e + 64};
  13447. }
  13448. /*!
  13449. @brief normalize x such that the significand is >= 2^(q-1)
  13450. @pre x.f != 0
  13451. */
  13452. static diyfp normalize(diyfp x) noexcept
  13453. {
  13454. JSON_ASSERT(x.f != 0);
  13455. while ((x.f >> 63u) == 0)
  13456. {
  13457. x.f <<= 1u;
  13458. x.e--;
  13459. }
  13460. return x;
  13461. }
  13462. /*!
  13463. @brief normalize x such that the result has the exponent E
  13464. @pre e >= x.e and the upper e - x.e bits of x.f must be zero.
  13465. */
  13466. static diyfp normalize_to(const diyfp& x, const int target_exponent) noexcept
  13467. {
  13468. const int delta = x.e - target_exponent;
  13469. JSON_ASSERT(delta >= 0);
  13470. JSON_ASSERT(((x.f << delta) >> delta) == x.f);
  13471. return {x.f << delta, target_exponent};
  13472. }
  13473. };
  13474. struct boundaries
  13475. {
  13476. diyfp w;
  13477. diyfp minus;
  13478. diyfp plus;
  13479. };
  13480. /*!
  13481. Compute the (normalized) diyfp representing the input number 'value' and its
  13482. boundaries.
  13483. @pre value must be finite and positive
  13484. */
  13485. template<typename FloatType>
  13486. boundaries compute_boundaries(FloatType value)
  13487. {
  13488. JSON_ASSERT(std::isfinite(value));
  13489. JSON_ASSERT(value > 0);
  13490. // Convert the IEEE representation into a diyfp.
  13491. //
  13492. // If v is denormal:
  13493. // value = 0.F * 2^(1 - bias) = ( F) * 2^(1 - bias - (p-1))
  13494. // If v is normalized:
  13495. // value = 1.F * 2^(E - bias) = (2^(p-1) + F) * 2^(E - bias - (p-1))
  13496. static_assert(std::numeric_limits<FloatType>::is_iec559,
  13497. "internal error: dtoa_short requires an IEEE-754 floating-point implementation");
  13498. constexpr int kPrecision = std::numeric_limits<FloatType>::digits; // = p (includes the hidden bit)
  13499. constexpr int kBias = std::numeric_limits<FloatType>::max_exponent - 1 + (kPrecision - 1);
  13500. constexpr int kMinExp = 1 - kBias;
  13501. constexpr std::uint64_t kHiddenBit = std::uint64_t{1} << (kPrecision - 1); // = 2^(p-1)
  13502. using bits_type = typename std::conditional<kPrecision == 24, std::uint32_t, std::uint64_t >::type;
  13503. const auto bits = static_cast<std::uint64_t>(reinterpret_bits<bits_type>(value));
  13504. const std::uint64_t E = bits >> (kPrecision - 1);
  13505. const std::uint64_t F = bits & (kHiddenBit - 1);
  13506. const bool is_denormal = E == 0;
  13507. const diyfp v = is_denormal
  13508. ? diyfp(F, kMinExp)
  13509. : diyfp(F + kHiddenBit, static_cast<int>(E) - kBias);
  13510. // Compute the boundaries m- and m+ of the floating-point value
  13511. // v = f * 2^e.
  13512. //
  13513. // Determine v- and v+, the floating-point predecessor and successor if v,
  13514. // respectively.
  13515. //
  13516. // v- = v - 2^e if f != 2^(p-1) or e == e_min (A)
  13517. // = v - 2^(e-1) if f == 2^(p-1) and e > e_min (B)
  13518. //
  13519. // v+ = v + 2^e
  13520. //
  13521. // Let m- = (v- + v) / 2 and m+ = (v + v+) / 2. All real numbers _strictly_
  13522. // between m- and m+ round to v, regardless of how the input rounding
  13523. // algorithm breaks ties.
  13524. //
  13525. // ---+-------------+-------------+-------------+-------------+--- (A)
  13526. // v- m- v m+ v+
  13527. //
  13528. // -----------------+------+------+-------------+-------------+--- (B)
  13529. // v- m- v m+ v+
  13530. const bool lower_boundary_is_closer = F == 0 && E > 1;
  13531. const diyfp m_plus = diyfp(2 * v.f + 1, v.e - 1);
  13532. const diyfp m_minus = lower_boundary_is_closer
  13533. ? diyfp(4 * v.f - 1, v.e - 2) // (B)
  13534. : diyfp(2 * v.f - 1, v.e - 1); // (A)
  13535. // Determine the normalized w+ = m+.
  13536. const diyfp w_plus = diyfp::normalize(m_plus);
  13537. // Determine w- = m- such that e_(w-) = e_(w+).
  13538. const diyfp w_minus = diyfp::normalize_to(m_minus, w_plus.e);
  13539. return {diyfp::normalize(v), w_minus, w_plus};
  13540. }
  13541. // Given normalized diyfp w, Grisu needs to find a (normalized) cached
  13542. // power-of-ten c, such that the exponent of the product c * w = f * 2^e lies
  13543. // within a certain range [alpha, gamma] (Definition 3.2 from [1])
  13544. //
  13545. // alpha <= e = e_c + e_w + q <= gamma
  13546. //
  13547. // or
  13548. //
  13549. // f_c * f_w * 2^alpha <= f_c 2^(e_c) * f_w 2^(e_w) * 2^q
  13550. // <= f_c * f_w * 2^gamma
  13551. //
  13552. // Since c and w are normalized, i.e. 2^(q-1) <= f < 2^q, this implies
  13553. //
  13554. // 2^(q-1) * 2^(q-1) * 2^alpha <= c * w * 2^q < 2^q * 2^q * 2^gamma
  13555. //
  13556. // or
  13557. //
  13558. // 2^(q - 2 + alpha) <= c * w < 2^(q + gamma)
  13559. //
  13560. // The choice of (alpha,gamma) determines the size of the table and the form of
  13561. // the digit generation procedure. Using (alpha,gamma)=(-60,-32) works out well
  13562. // in practice:
  13563. //
  13564. // The idea is to cut the number c * w = f * 2^e into two parts, which can be
  13565. // processed independently: An integral part p1, and a fractional part p2:
  13566. //
  13567. // f * 2^e = ( (f div 2^-e) * 2^-e + (f mod 2^-e) ) * 2^e
  13568. // = (f div 2^-e) + (f mod 2^-e) * 2^e
  13569. // = p1 + p2 * 2^e
  13570. //
  13571. // The conversion of p1 into decimal form requires a series of divisions and
  13572. // modulos by (a power of) 10. These operations are faster for 32-bit than for
  13573. // 64-bit integers, so p1 should ideally fit into a 32-bit integer. This can be
  13574. // achieved by choosing
  13575. //
  13576. // -e >= 32 or e <= -32 := gamma
  13577. //
  13578. // In order to convert the fractional part
  13579. //
  13580. // p2 * 2^e = p2 / 2^-e = d[-1] / 10^1 + d[-2] / 10^2 + ...
  13581. //
  13582. // into decimal form, the fraction is repeatedly multiplied by 10 and the digits
  13583. // d[-i] are extracted in order:
  13584. //
  13585. // (10 * p2) div 2^-e = d[-1]
  13586. // (10 * p2) mod 2^-e = d[-2] / 10^1 + ...
  13587. //
  13588. // The multiplication by 10 must not overflow. It is sufficient to choose
  13589. //
  13590. // 10 * p2 < 16 * p2 = 2^4 * p2 <= 2^64.
  13591. //
  13592. // Since p2 = f mod 2^-e < 2^-e,
  13593. //
  13594. // -e <= 60 or e >= -60 := alpha
  13595. constexpr int kAlpha = -60;
  13596. constexpr int kGamma = -32;
  13597. struct cached_power // c = f * 2^e ~= 10^k
  13598. {
  13599. std::uint64_t f;
  13600. int e;
  13601. int k;
  13602. };
  13603. /*!
  13604. For a normalized diyfp w = f * 2^e, this function returns a (normalized) cached
  13605. power-of-ten c = f_c * 2^e_c, such that the exponent of the product w * c
  13606. satisfies (Definition 3.2 from [1])
  13607. alpha <= e_c + e + q <= gamma.
  13608. */
  13609. inline cached_power get_cached_power_for_binary_exponent(int e)
  13610. {
  13611. // Now
  13612. //
  13613. // alpha <= e_c + e + q <= gamma (1)
  13614. // ==> f_c * 2^alpha <= c * 2^e * 2^q
  13615. //
  13616. // and since the c's are normalized, 2^(q-1) <= f_c,
  13617. //
  13618. // ==> 2^(q - 1 + alpha) <= c * 2^(e + q)
  13619. // ==> 2^(alpha - e - 1) <= c
  13620. //
  13621. // If c were an exact power of ten, i.e. c = 10^k, one may determine k as
  13622. //
  13623. // k = ceil( log_10( 2^(alpha - e - 1) ) )
  13624. // = ceil( (alpha - e - 1) * log_10(2) )
  13625. //
  13626. // From the paper:
  13627. // "In theory the result of the procedure could be wrong since c is rounded,
  13628. // and the computation itself is approximated [...]. In practice, however,
  13629. // this simple function is sufficient."
  13630. //
  13631. // For IEEE double precision floating-point numbers converted into
  13632. // normalized diyfp's w = f * 2^e, with q = 64,
  13633. //
  13634. // e >= -1022 (min IEEE exponent)
  13635. // -52 (p - 1)
  13636. // -52 (p - 1, possibly normalize denormal IEEE numbers)
  13637. // -11 (normalize the diyfp)
  13638. // = -1137
  13639. //
  13640. // and
  13641. //
  13642. // e <= +1023 (max IEEE exponent)
  13643. // -52 (p - 1)
  13644. // -11 (normalize the diyfp)
  13645. // = 960
  13646. //
  13647. // This binary exponent range [-1137,960] results in a decimal exponent
  13648. // range [-307,324]. One does not need to store a cached power for each
  13649. // k in this range. For each such k it suffices to find a cached power
  13650. // such that the exponent of the product lies in [alpha,gamma].
  13651. // This implies that the difference of the decimal exponents of adjacent
  13652. // table entries must be less than or equal to
  13653. //
  13654. // floor( (gamma - alpha) * log_10(2) ) = 8.
  13655. //
  13656. // (A smaller distance gamma-alpha would require a larger table.)
  13657. // NB:
  13658. // Actually this function returns c, such that -60 <= e_c + e + 64 <= -34.
  13659. constexpr int kCachedPowersMinDecExp = -300;
  13660. constexpr int kCachedPowersDecStep = 8;
  13661. static constexpr std::array<cached_power, 79> kCachedPowers =
  13662. {
  13663. {
  13664. { 0xAB70FE17C79AC6CA, -1060, -300 },
  13665. { 0xFF77B1FCBEBCDC4F, -1034, -292 },
  13666. { 0xBE5691EF416BD60C, -1007, -284 },
  13667. { 0x8DD01FAD907FFC3C, -980, -276 },
  13668. { 0xD3515C2831559A83, -954, -268 },
  13669. { 0x9D71AC8FADA6C9B5, -927, -260 },
  13670. { 0xEA9C227723EE8BCB, -901, -252 },
  13671. { 0xAECC49914078536D, -874, -244 },
  13672. { 0x823C12795DB6CE57, -847, -236 },
  13673. { 0xC21094364DFB5637, -821, -228 },
  13674. { 0x9096EA6F3848984F, -794, -220 },
  13675. { 0xD77485CB25823AC7, -768, -212 },
  13676. { 0xA086CFCD97BF97F4, -741, -204 },
  13677. { 0xEF340A98172AACE5, -715, -196 },
  13678. { 0xB23867FB2A35B28E, -688, -188 },
  13679. { 0x84C8D4DFD2C63F3B, -661, -180 },
  13680. { 0xC5DD44271AD3CDBA, -635, -172 },
  13681. { 0x936B9FCEBB25C996, -608, -164 },
  13682. { 0xDBAC6C247D62A584, -582, -156 },
  13683. { 0xA3AB66580D5FDAF6, -555, -148 },
  13684. { 0xF3E2F893DEC3F126, -529, -140 },
  13685. { 0xB5B5ADA8AAFF80B8, -502, -132 },
  13686. { 0x87625F056C7C4A8B, -475, -124 },
  13687. { 0xC9BCFF6034C13053, -449, -116 },
  13688. { 0x964E858C91BA2655, -422, -108 },
  13689. { 0xDFF9772470297EBD, -396, -100 },
  13690. { 0xA6DFBD9FB8E5B88F, -369, -92 },
  13691. { 0xF8A95FCF88747D94, -343, -84 },
  13692. { 0xB94470938FA89BCF, -316, -76 },
  13693. { 0x8A08F0F8BF0F156B, -289, -68 },
  13694. { 0xCDB02555653131B6, -263, -60 },
  13695. { 0x993FE2C6D07B7FAC, -236, -52 },
  13696. { 0xE45C10C42A2B3B06, -210, -44 },
  13697. { 0xAA242499697392D3, -183, -36 },
  13698. { 0xFD87B5F28300CA0E, -157, -28 },
  13699. { 0xBCE5086492111AEB, -130, -20 },
  13700. { 0x8CBCCC096F5088CC, -103, -12 },
  13701. { 0xD1B71758E219652C, -77, -4 },
  13702. { 0x9C40000000000000, -50, 4 },
  13703. { 0xE8D4A51000000000, -24, 12 },
  13704. { 0xAD78EBC5AC620000, 3, 20 },
  13705. { 0x813F3978F8940984, 30, 28 },
  13706. { 0xC097CE7BC90715B3, 56, 36 },
  13707. { 0x8F7E32CE7BEA5C70, 83, 44 },
  13708. { 0xD5D238A4ABE98068, 109, 52 },
  13709. { 0x9F4F2726179A2245, 136, 60 },
  13710. { 0xED63A231D4C4FB27, 162, 68 },
  13711. { 0xB0DE65388CC8ADA8, 189, 76 },
  13712. { 0x83C7088E1AAB65DB, 216, 84 },
  13713. { 0xC45D1DF942711D9A, 242, 92 },
  13714. { 0x924D692CA61BE758, 269, 100 },
  13715. { 0xDA01EE641A708DEA, 295, 108 },
  13716. { 0xA26DA3999AEF774A, 322, 116 },
  13717. { 0xF209787BB47D6B85, 348, 124 },
  13718. { 0xB454E4A179DD1877, 375, 132 },
  13719. { 0x865B86925B9BC5C2, 402, 140 },
  13720. { 0xC83553C5C8965D3D, 428, 148 },
  13721. { 0x952AB45CFA97A0B3, 455, 156 },
  13722. { 0xDE469FBD99A05FE3, 481, 164 },
  13723. { 0xA59BC234DB398C25, 508, 172 },
  13724. { 0xF6C69A72A3989F5C, 534, 180 },
  13725. { 0xB7DCBF5354E9BECE, 561, 188 },
  13726. { 0x88FCF317F22241E2, 588, 196 },
  13727. { 0xCC20CE9BD35C78A5, 614, 204 },
  13728. { 0x98165AF37B2153DF, 641, 212 },
  13729. { 0xE2A0B5DC971F303A, 667, 220 },
  13730. { 0xA8D9D1535CE3B396, 694, 228 },
  13731. { 0xFB9B7CD9A4A7443C, 720, 236 },
  13732. { 0xBB764C4CA7A44410, 747, 244 },
  13733. { 0x8BAB8EEFB6409C1A, 774, 252 },
  13734. { 0xD01FEF10A657842C, 800, 260 },
  13735. { 0x9B10A4E5E9913129, 827, 268 },
  13736. { 0xE7109BFBA19C0C9D, 853, 276 },
  13737. { 0xAC2820D9623BF429, 880, 284 },
  13738. { 0x80444B5E7AA7CF85, 907, 292 },
  13739. { 0xBF21E44003ACDD2D, 933, 300 },
  13740. { 0x8E679C2F5E44FF8F, 960, 308 },
  13741. { 0xD433179D9C8CB841, 986, 316 },
  13742. { 0x9E19DB92B4E31BA9, 1013, 324 },
  13743. }
  13744. };
  13745. // This computation gives exactly the same results for k as
  13746. // k = ceil((kAlpha - e - 1) * 0.30102999566398114)
  13747. // for |e| <= 1500, but doesn't require floating-point operations.
  13748. // NB: log_10(2) ~= 78913 / 2^18
  13749. JSON_ASSERT(e >= -1500);
  13750. JSON_ASSERT(e <= 1500);
  13751. const int f = kAlpha - e - 1;
  13752. const int k = (f * 78913) / (1 << 18) + static_cast<int>(f > 0);
  13753. const int index = (-kCachedPowersMinDecExp + k + (kCachedPowersDecStep - 1)) / kCachedPowersDecStep;
  13754. JSON_ASSERT(index >= 0);
  13755. JSON_ASSERT(static_cast<std::size_t>(index) < kCachedPowers.size());
  13756. const cached_power cached = kCachedPowers[static_cast<std::size_t>(index)];
  13757. JSON_ASSERT(kAlpha <= cached.e + e + 64);
  13758. JSON_ASSERT(kGamma >= cached.e + e + 64);
  13759. return cached;
  13760. }
  13761. /*!
  13762. For n != 0, returns k, such that pow10 := 10^(k-1) <= n < 10^k.
  13763. For n == 0, returns 1 and sets pow10 := 1.
  13764. */
  13765. inline int find_largest_pow10(const std::uint32_t n, std::uint32_t& pow10)
  13766. {
  13767. // LCOV_EXCL_START
  13768. if (n >= 1000000000)
  13769. {
  13770. pow10 = 1000000000;
  13771. return 10;
  13772. }
  13773. // LCOV_EXCL_STOP
  13774. if (n >= 100000000)
  13775. {
  13776. pow10 = 100000000;
  13777. return 9;
  13778. }
  13779. if (n >= 10000000)
  13780. {
  13781. pow10 = 10000000;
  13782. return 8;
  13783. }
  13784. if (n >= 1000000)
  13785. {
  13786. pow10 = 1000000;
  13787. return 7;
  13788. }
  13789. if (n >= 100000)
  13790. {
  13791. pow10 = 100000;
  13792. return 6;
  13793. }
  13794. if (n >= 10000)
  13795. {
  13796. pow10 = 10000;
  13797. return 5;
  13798. }
  13799. if (n >= 1000)
  13800. {
  13801. pow10 = 1000;
  13802. return 4;
  13803. }
  13804. if (n >= 100)
  13805. {
  13806. pow10 = 100;
  13807. return 3;
  13808. }
  13809. if (n >= 10)
  13810. {
  13811. pow10 = 10;
  13812. return 2;
  13813. }
  13814. pow10 = 1;
  13815. return 1;
  13816. }
  13817. inline void grisu2_round(char* buf, int len, std::uint64_t dist, std::uint64_t delta,
  13818. std::uint64_t rest, std::uint64_t ten_k)
  13819. {
  13820. JSON_ASSERT(len >= 1);
  13821. JSON_ASSERT(dist <= delta);
  13822. JSON_ASSERT(rest <= delta);
  13823. JSON_ASSERT(ten_k > 0);
  13824. // <--------------------------- delta ---->
  13825. // <---- dist --------->
  13826. // --------------[------------------+-------------------]--------------
  13827. // M- w M+
  13828. //
  13829. // ten_k
  13830. // <------>
  13831. // <---- rest ---->
  13832. // --------------[------------------+----+--------------]--------------
  13833. // w V
  13834. // = buf * 10^k
  13835. //
  13836. // ten_k represents a unit-in-the-last-place in the decimal representation
  13837. // stored in buf.
  13838. // Decrement buf by ten_k while this takes buf closer to w.
  13839. // The tests are written in this order to avoid overflow in unsigned
  13840. // integer arithmetic.
  13841. while (rest < dist
  13842. && delta - rest >= ten_k
  13843. && (rest + ten_k < dist || dist - rest > rest + ten_k - dist))
  13844. {
  13845. JSON_ASSERT(buf[len - 1] != '0');
  13846. buf[len - 1]--;
  13847. rest += ten_k;
  13848. }
  13849. }
  13850. /*!
  13851. Generates V = buffer * 10^decimal_exponent, such that M- <= V <= M+.
  13852. M- and M+ must be normalized and share the same exponent -60 <= e <= -32.
  13853. */
  13854. inline void grisu2_digit_gen(char* buffer, int& length, int& decimal_exponent,
  13855. diyfp M_minus, diyfp w, diyfp M_plus)
  13856. {
  13857. static_assert(kAlpha >= -60, "internal error");
  13858. static_assert(kGamma <= -32, "internal error");
  13859. // Generates the digits (and the exponent) of a decimal floating-point
  13860. // number V = buffer * 10^decimal_exponent in the range [M-, M+]. The diyfp's
  13861. // w, M- and M+ share the same exponent e, which satisfies alpha <= e <= gamma.
  13862. //
  13863. // <--------------------------- delta ---->
  13864. // <---- dist --------->
  13865. // --------------[------------------+-------------------]--------------
  13866. // M- w M+
  13867. //
  13868. // Grisu2 generates the digits of M+ from left to right and stops as soon as
  13869. // V is in [M-,M+].
  13870. JSON_ASSERT(M_plus.e >= kAlpha);
  13871. JSON_ASSERT(M_plus.e <= kGamma);
  13872. std::uint64_t delta = diyfp::sub(M_plus, M_minus).f; // (significand of (M+ - M-), implicit exponent is e)
  13873. std::uint64_t dist = diyfp::sub(M_plus, w ).f; // (significand of (M+ - w ), implicit exponent is e)
  13874. // Split M+ = f * 2^e into two parts p1 and p2 (note: e < 0):
  13875. //
  13876. // M+ = f * 2^e
  13877. // = ((f div 2^-e) * 2^-e + (f mod 2^-e)) * 2^e
  13878. // = ((p1 ) * 2^-e + (p2 )) * 2^e
  13879. // = p1 + p2 * 2^e
  13880. const diyfp one(std::uint64_t{1} << -M_plus.e, M_plus.e);
  13881. 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.)
  13882. std::uint64_t p2 = M_plus.f & (one.f - 1); // p2 = f mod 2^-e
  13883. // 1)
  13884. //
  13885. // Generate the digits of the integral part p1 = d[n-1]...d[1]d[0]
  13886. JSON_ASSERT(p1 > 0);
  13887. std::uint32_t pow10{};
  13888. const int k = find_largest_pow10(p1, pow10);
  13889. // 10^(k-1) <= p1 < 10^k, pow10 = 10^(k-1)
  13890. //
  13891. // p1 = (p1 div 10^(k-1)) * 10^(k-1) + (p1 mod 10^(k-1))
  13892. // = (d[k-1] ) * 10^(k-1) + (p1 mod 10^(k-1))
  13893. //
  13894. // M+ = p1 + p2 * 2^e
  13895. // = d[k-1] * 10^(k-1) + (p1 mod 10^(k-1)) + p2 * 2^e
  13896. // = d[k-1] * 10^(k-1) + ((p1 mod 10^(k-1)) * 2^-e + p2) * 2^e
  13897. // = d[k-1] * 10^(k-1) + ( rest) * 2^e
  13898. //
  13899. // Now generate the digits d[n] of p1 from left to right (n = k-1,...,0)
  13900. //
  13901. // p1 = d[k-1]...d[n] * 10^n + d[n-1]...d[0]
  13902. //
  13903. // but stop as soon as
  13904. //
  13905. // rest * 2^e = (d[n-1]...d[0] * 2^-e + p2) * 2^e <= delta * 2^e
  13906. int n = k;
  13907. while (n > 0)
  13908. {
  13909. // Invariants:
  13910. // M+ = buffer * 10^n + (p1 + p2 * 2^e) (buffer = 0 for n = k)
  13911. // pow10 = 10^(n-1) <= p1 < 10^n
  13912. //
  13913. const std::uint32_t d = p1 / pow10; // d = p1 div 10^(n-1)
  13914. const std::uint32_t r = p1 % pow10; // r = p1 mod 10^(n-1)
  13915. //
  13916. // M+ = buffer * 10^n + (d * 10^(n-1) + r) + p2 * 2^e
  13917. // = (buffer * 10 + d) * 10^(n-1) + (r + p2 * 2^e)
  13918. //
  13919. JSON_ASSERT(d <= 9);
  13920. buffer[length++] = static_cast<char>('0' + d); // buffer := buffer * 10 + d
  13921. //
  13922. // M+ = buffer * 10^(n-1) + (r + p2 * 2^e)
  13923. //
  13924. p1 = r;
  13925. n--;
  13926. //
  13927. // M+ = buffer * 10^n + (p1 + p2 * 2^e)
  13928. // pow10 = 10^n
  13929. //
  13930. // Now check if enough digits have been generated.
  13931. // Compute
  13932. //
  13933. // p1 + p2 * 2^e = (p1 * 2^-e + p2) * 2^e = rest * 2^e
  13934. //
  13935. // Note:
  13936. // Since rest and delta share the same exponent e, it suffices to
  13937. // compare the significands.
  13938. const std::uint64_t rest = (std::uint64_t{p1} << -one.e) + p2;
  13939. if (rest <= delta)
  13940. {
  13941. // V = buffer * 10^n, with M- <= V <= M+.
  13942. decimal_exponent += n;
  13943. // We may now just stop. But instead look if the buffer could be
  13944. // decremented to bring V closer to w.
  13945. //
  13946. // pow10 = 10^n is now 1 ulp in the decimal representation V.
  13947. // The rounding procedure works with diyfp's with an implicit
  13948. // exponent of e.
  13949. //
  13950. // 10^n = (10^n * 2^-e) * 2^e = ulp * 2^e
  13951. //
  13952. const std::uint64_t ten_n = std::uint64_t{pow10} << -one.e;
  13953. grisu2_round(buffer, length, dist, delta, rest, ten_n);
  13954. return;
  13955. }
  13956. pow10 /= 10;
  13957. //
  13958. // pow10 = 10^(n-1) <= p1 < 10^n
  13959. // Invariants restored.
  13960. }
  13961. // 2)
  13962. //
  13963. // The digits of the integral part have been generated:
  13964. //
  13965. // M+ = d[k-1]...d[1]d[0] + p2 * 2^e
  13966. // = buffer + p2 * 2^e
  13967. //
  13968. // Now generate the digits of the fractional part p2 * 2^e.
  13969. //
  13970. // Note:
  13971. // No decimal point is generated: the exponent is adjusted instead.
  13972. //
  13973. // p2 actually represents the fraction
  13974. //
  13975. // p2 * 2^e
  13976. // = p2 / 2^-e
  13977. // = d[-1] / 10^1 + d[-2] / 10^2 + ...
  13978. //
  13979. // Now generate the digits d[-m] of p1 from left to right (m = 1,2,...)
  13980. //
  13981. // p2 * 2^e = d[-1]d[-2]...d[-m] * 10^-m
  13982. // + 10^-m * (d[-m-1] / 10^1 + d[-m-2] / 10^2 + ...)
  13983. //
  13984. // using
  13985. //
  13986. // 10^m * p2 = ((10^m * p2) div 2^-e) * 2^-e + ((10^m * p2) mod 2^-e)
  13987. // = ( d) * 2^-e + ( r)
  13988. //
  13989. // or
  13990. // 10^m * p2 * 2^e = d + r * 2^e
  13991. //
  13992. // i.e.
  13993. //
  13994. // M+ = buffer + p2 * 2^e
  13995. // = buffer + 10^-m * (d + r * 2^e)
  13996. // = (buffer * 10^m + d) * 10^-m + 10^-m * r * 2^e
  13997. //
  13998. // and stop as soon as 10^-m * r * 2^e <= delta * 2^e
  13999. JSON_ASSERT(p2 > delta);
  14000. int m = 0;
  14001. for (;;)
  14002. {
  14003. // Invariant:
  14004. // M+ = buffer * 10^-m + 10^-m * (d[-m-1] / 10 + d[-m-2] / 10^2 + ...) * 2^e
  14005. // = buffer * 10^-m + 10^-m * (p2 ) * 2^e
  14006. // = buffer * 10^-m + 10^-m * (1/10 * (10 * p2) ) * 2^e
  14007. // = buffer * 10^-m + 10^-m * (1/10 * ((10*p2 div 2^-e) * 2^-e + (10*p2 mod 2^-e)) * 2^e
  14008. //
  14009. JSON_ASSERT(p2 <= (std::numeric_limits<std::uint64_t>::max)() / 10);
  14010. p2 *= 10;
  14011. const std::uint64_t d = p2 >> -one.e; // d = (10 * p2) div 2^-e
  14012. const std::uint64_t r = p2 & (one.f - 1); // r = (10 * p2) mod 2^-e
  14013. //
  14014. // M+ = buffer * 10^-m + 10^-m * (1/10 * (d * 2^-e + r) * 2^e
  14015. // = buffer * 10^-m + 10^-m * (1/10 * (d + r * 2^e))
  14016. // = (buffer * 10 + d) * 10^(-m-1) + 10^(-m-1) * r * 2^e
  14017. //
  14018. JSON_ASSERT(d <= 9);
  14019. buffer[length++] = static_cast<char>('0' + d); // buffer := buffer * 10 + d
  14020. //
  14021. // M+ = buffer * 10^(-m-1) + 10^(-m-1) * r * 2^e
  14022. //
  14023. p2 = r;
  14024. m++;
  14025. //
  14026. // M+ = buffer * 10^-m + 10^-m * p2 * 2^e
  14027. // Invariant restored.
  14028. // Check if enough digits have been generated.
  14029. //
  14030. // 10^-m * p2 * 2^e <= delta * 2^e
  14031. // p2 * 2^e <= 10^m * delta * 2^e
  14032. // p2 <= 10^m * delta
  14033. delta *= 10;
  14034. dist *= 10;
  14035. if (p2 <= delta)
  14036. {
  14037. break;
  14038. }
  14039. }
  14040. // V = buffer * 10^-m, with M- <= V <= M+.
  14041. decimal_exponent -= m;
  14042. // 1 ulp in the decimal representation is now 10^-m.
  14043. // Since delta and dist are now scaled by 10^m, we need to do the
  14044. // same with ulp in order to keep the units in sync.
  14045. //
  14046. // 10^m * 10^-m = 1 = 2^-e * 2^e = ten_m * 2^e
  14047. //
  14048. const std::uint64_t ten_m = one.f;
  14049. grisu2_round(buffer, length, dist, delta, p2, ten_m);
  14050. // By construction this algorithm generates the shortest possible decimal
  14051. // number (Loitsch, Theorem 6.2) which rounds back to w.
  14052. // For an input number of precision p, at least
  14053. //
  14054. // N = 1 + ceil(p * log_10(2))
  14055. //
  14056. // decimal digits are sufficient to identify all binary floating-point
  14057. // numbers (Matula, "In-and-Out conversions").
  14058. // This implies that the algorithm does not produce more than N decimal
  14059. // digits.
  14060. //
  14061. // N = 17 for p = 53 (IEEE double precision)
  14062. // N = 9 for p = 24 (IEEE single precision)
  14063. }
  14064. /*!
  14065. v = buf * 10^decimal_exponent
  14066. len is the length of the buffer (number of decimal digits)
  14067. The buffer must be large enough, i.e. >= max_digits10.
  14068. */
  14069. JSON_HEDLEY_NON_NULL(1)
  14070. inline void grisu2(char* buf, int& len, int& decimal_exponent,
  14071. diyfp m_minus, diyfp v, diyfp m_plus)
  14072. {
  14073. JSON_ASSERT(m_plus.e == m_minus.e);
  14074. JSON_ASSERT(m_plus.e == v.e);
  14075. // --------(-----------------------+-----------------------)-------- (A)
  14076. // m- v m+
  14077. //
  14078. // --------------------(-----------+-----------------------)-------- (B)
  14079. // m- v m+
  14080. //
  14081. // First scale v (and m- and m+) such that the exponent is in the range
  14082. // [alpha, gamma].
  14083. const cached_power cached = get_cached_power_for_binary_exponent(m_plus.e);
  14084. const diyfp c_minus_k(cached.f, cached.e); // = c ~= 10^-k
  14085. // The exponent of the products is = v.e + c_minus_k.e + q and is in the range [alpha,gamma]
  14086. const diyfp w = diyfp::mul(v, c_minus_k);
  14087. const diyfp w_minus = diyfp::mul(m_minus, c_minus_k);
  14088. const diyfp w_plus = diyfp::mul(m_plus, c_minus_k);
  14089. // ----(---+---)---------------(---+---)---------------(---+---)----
  14090. // w- w w+
  14091. // = c*m- = c*v = c*m+
  14092. //
  14093. // diyfp::mul rounds its result and c_minus_k is approximated too. w, w- and
  14094. // w+ are now off by a small amount.
  14095. // In fact:
  14096. //
  14097. // w - v * 10^k < 1 ulp
  14098. //
  14099. // To account for this inaccuracy, add resp. subtract 1 ulp.
  14100. //
  14101. // --------+---[---------------(---+---)---------------]---+--------
  14102. // w- M- w M+ w+
  14103. //
  14104. // Now any number in [M-, M+] (bounds included) will round to w when input,
  14105. // regardless of how the input rounding algorithm breaks ties.
  14106. //
  14107. // And digit_gen generates the shortest possible such number in [M-, M+].
  14108. // Note that this does not mean that Grisu2 always generates the shortest
  14109. // possible number in the interval (m-, m+).
  14110. const diyfp M_minus(w_minus.f + 1, w_minus.e);
  14111. const diyfp M_plus (w_plus.f - 1, w_plus.e );
  14112. decimal_exponent = -cached.k; // = -(-k) = k
  14113. grisu2_digit_gen(buf, len, decimal_exponent, M_minus, w, M_plus);
  14114. }
  14115. /*!
  14116. v = buf * 10^decimal_exponent
  14117. len is the length of the buffer (number of decimal digits)
  14118. The buffer must be large enough, i.e. >= max_digits10.
  14119. */
  14120. template<typename FloatType>
  14121. JSON_HEDLEY_NON_NULL(1)
  14122. void grisu2(char* buf, int& len, int& decimal_exponent, FloatType value)
  14123. {
  14124. static_assert(diyfp::kPrecision >= std::numeric_limits<FloatType>::digits + 3,
  14125. "internal error: not enough precision");
  14126. JSON_ASSERT(std::isfinite(value));
  14127. JSON_ASSERT(value > 0);
  14128. // If the neighbors (and boundaries) of 'value' are always computed for double-precision
  14129. // numbers, all float's can be recovered using strtod (and strtof). However, the resulting
  14130. // decimal representations are not exactly "short".
  14131. //
  14132. // The documentation for 'std::to_chars' (https://en.cppreference.com/w/cpp/utility/to_chars)
  14133. // says "value is converted to a string as if by std::sprintf in the default ("C") locale"
  14134. // and since sprintf promotes float's to double's, I think this is exactly what 'std::to_chars'
  14135. // does.
  14136. // On the other hand, the documentation for 'std::to_chars' requires that "parsing the
  14137. // representation using the corresponding std::from_chars function recovers value exactly". That
  14138. // indicates that single precision floating-point numbers should be recovered using
  14139. // 'std::strtof'.
  14140. //
  14141. // NB: If the neighbors are computed for single-precision numbers, there is a single float
  14142. // (7.0385307e-26f) which can't be recovered using strtod. The resulting double precision
  14143. // value is off by 1 ulp.
  14144. #if 0
  14145. const boundaries w = compute_boundaries(static_cast<double>(value));
  14146. #else
  14147. const boundaries w = compute_boundaries(value);
  14148. #endif
  14149. grisu2(buf, len, decimal_exponent, w.minus, w.w, w.plus);
  14150. }
  14151. /*!
  14152. @brief appends a decimal representation of e to buf
  14153. @return a pointer to the element following the exponent.
  14154. @pre -1000 < e < 1000
  14155. */
  14156. JSON_HEDLEY_NON_NULL(1)
  14157. JSON_HEDLEY_RETURNS_NON_NULL
  14158. inline char* append_exponent(char* buf, int e)
  14159. {
  14160. JSON_ASSERT(e > -1000);
  14161. JSON_ASSERT(e < 1000);
  14162. if (e < 0)
  14163. {
  14164. e = -e;
  14165. *buf++ = '-';
  14166. }
  14167. else
  14168. {
  14169. *buf++ = '+';
  14170. }
  14171. auto k = static_cast<std::uint32_t>(e);
  14172. if (k < 10)
  14173. {
  14174. // Always print at least two digits in the exponent.
  14175. // This is for compatibility with printf("%g").
  14176. *buf++ = '0';
  14177. *buf++ = static_cast<char>('0' + k);
  14178. }
  14179. else if (k < 100)
  14180. {
  14181. *buf++ = static_cast<char>('0' + k / 10);
  14182. k %= 10;
  14183. *buf++ = static_cast<char>('0' + k);
  14184. }
  14185. else
  14186. {
  14187. *buf++ = static_cast<char>('0' + k / 100);
  14188. k %= 100;
  14189. *buf++ = static_cast<char>('0' + k / 10);
  14190. k %= 10;
  14191. *buf++ = static_cast<char>('0' + k);
  14192. }
  14193. return buf;
  14194. }
  14195. /*!
  14196. @brief prettify v = buf * 10^decimal_exponent
  14197. If v is in the range [10^min_exp, 10^max_exp) it will be printed in fixed-point
  14198. notation. Otherwise it will be printed in exponential notation.
  14199. @pre min_exp < 0
  14200. @pre max_exp > 0
  14201. */
  14202. JSON_HEDLEY_NON_NULL(1)
  14203. JSON_HEDLEY_RETURNS_NON_NULL
  14204. inline char* format_buffer(char* buf, int len, int decimal_exponent,
  14205. int min_exp, int max_exp)
  14206. {
  14207. JSON_ASSERT(min_exp < 0);
  14208. JSON_ASSERT(max_exp > 0);
  14209. const int k = len;
  14210. const int n = len + decimal_exponent;
  14211. // v = buf * 10^(n-k)
  14212. // k is the length of the buffer (number of decimal digits)
  14213. // n is the position of the decimal point relative to the start of the buffer.
  14214. if (k <= n && n <= max_exp)
  14215. {
  14216. // digits[000]
  14217. // len <= max_exp + 2
  14218. std::memset(buf + k, '0', static_cast<size_t>(n) - static_cast<size_t>(k));
  14219. // Make it look like a floating-point number (#362, #378)
  14220. buf[n + 0] = '.';
  14221. buf[n + 1] = '0';
  14222. return buf + (static_cast<size_t>(n) + 2);
  14223. }
  14224. if (0 < n && n <= max_exp)
  14225. {
  14226. // dig.its
  14227. // len <= max_digits10 + 1
  14228. JSON_ASSERT(k > n);
  14229. std::memmove(buf + (static_cast<size_t>(n) + 1), buf + n, static_cast<size_t>(k) - static_cast<size_t>(n));
  14230. buf[n] = '.';
  14231. return buf + (static_cast<size_t>(k) + 1U);
  14232. }
  14233. if (min_exp < n && n <= 0)
  14234. {
  14235. // 0.[000]digits
  14236. // len <= 2 + (-min_exp - 1) + max_digits10
  14237. std::memmove(buf + (2 + static_cast<size_t>(-n)), buf, static_cast<size_t>(k));
  14238. buf[0] = '0';
  14239. buf[1] = '.';
  14240. std::memset(buf + 2, '0', static_cast<size_t>(-n));
  14241. return buf + (2U + static_cast<size_t>(-n) + static_cast<size_t>(k));
  14242. }
  14243. if (k == 1)
  14244. {
  14245. // dE+123
  14246. // len <= 1 + 5
  14247. buf += 1;
  14248. }
  14249. else
  14250. {
  14251. // d.igitsE+123
  14252. // len <= max_digits10 + 1 + 5
  14253. std::memmove(buf + 2, buf + 1, static_cast<size_t>(k) - 1);
  14254. buf[1] = '.';
  14255. buf += 1 + static_cast<size_t>(k);
  14256. }
  14257. *buf++ = 'e';
  14258. return append_exponent(buf, n - 1);
  14259. }
  14260. } // namespace dtoa_impl
  14261. /*!
  14262. @brief generates a decimal representation of the floating-point number value in [first, last).
  14263. The format of the resulting decimal representation is similar to printf's %g
  14264. format. Returns an iterator pointing past-the-end of the decimal representation.
  14265. @note The input number must be finite, i.e. NaN's and Inf's are not supported.
  14266. @note The buffer must be large enough.
  14267. @note The result is NOT null-terminated.
  14268. */
  14269. template<typename FloatType>
  14270. JSON_HEDLEY_NON_NULL(1, 2)
  14271. JSON_HEDLEY_RETURNS_NON_NULL
  14272. char* to_chars(char* first, const char* last, FloatType value)
  14273. {
  14274. static_cast<void>(last); // maybe unused - fix warning
  14275. JSON_ASSERT(std::isfinite(value));
  14276. // Use signbit(value) instead of (value < 0) since signbit works for -0.
  14277. if (std::signbit(value))
  14278. {
  14279. value = -value;
  14280. *first++ = '-';
  14281. }
  14282. #ifdef __GNUC__
  14283. #pragma GCC diagnostic push
  14284. #pragma GCC diagnostic ignored "-Wfloat-equal"
  14285. #endif
  14286. if (value == 0) // +-0
  14287. {
  14288. *first++ = '0';
  14289. // Make it look like a floating-point number (#362, #378)
  14290. *first++ = '.';
  14291. *first++ = '0';
  14292. return first;
  14293. }
  14294. #ifdef __GNUC__
  14295. #pragma GCC diagnostic pop
  14296. #endif
  14297. JSON_ASSERT(last - first >= std::numeric_limits<FloatType>::max_digits10);
  14298. // Compute v = buffer * 10^decimal_exponent.
  14299. // The decimal digits are stored in the buffer, which needs to be interpreted
  14300. // as an unsigned decimal integer.
  14301. // len is the length of the buffer, i.e. the number of decimal digits.
  14302. int len = 0;
  14303. int decimal_exponent = 0;
  14304. dtoa_impl::grisu2(first, len, decimal_exponent, value);
  14305. JSON_ASSERT(len <= std::numeric_limits<FloatType>::max_digits10);
  14306. // Format the buffer like printf("%.*g", prec, value)
  14307. constexpr int kMinExp = -4;
  14308. // Use digits10 here to increase compatibility with version 2.
  14309. constexpr int kMaxExp = std::numeric_limits<FloatType>::digits10;
  14310. JSON_ASSERT(last - first >= kMaxExp + 2);
  14311. JSON_ASSERT(last - first >= 2 + (-kMinExp - 1) + std::numeric_limits<FloatType>::max_digits10);
  14312. JSON_ASSERT(last - first >= std::numeric_limits<FloatType>::max_digits10 + 6);
  14313. return dtoa_impl::format_buffer(first, len, decimal_exponent, kMinExp, kMaxExp);
  14314. }
  14315. } // namespace detail
  14316. } // namespace nlohmann
  14317. // #include <nlohmann/detail/exceptions.hpp>
  14318. // #include <nlohmann/detail/macro_scope.hpp>
  14319. // #include <nlohmann/detail/meta/cpp_future.hpp>
  14320. // #include <nlohmann/detail/output/binary_writer.hpp>
  14321. // #include <nlohmann/detail/output/output_adapters.hpp>
  14322. // #include <nlohmann/detail/value_t.hpp>
  14323. namespace nlohmann
  14324. {
  14325. namespace detail
  14326. {
  14327. ///////////////////
  14328. // serialization //
  14329. ///////////////////
  14330. /// how to treat decoding errors
  14331. enum class error_handler_t
  14332. {
  14333. strict, ///< throw a type_error exception in case of invalid UTF-8
  14334. replace, ///< replace invalid UTF-8 sequences with U+FFFD
  14335. ignore ///< ignore invalid UTF-8 sequences
  14336. };
  14337. template<typename BasicJsonType>
  14338. class serializer
  14339. {
  14340. using string_t = typename BasicJsonType::string_t;
  14341. using number_float_t = typename BasicJsonType::number_float_t;
  14342. using number_integer_t = typename BasicJsonType::number_integer_t;
  14343. using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
  14344. using binary_char_t = typename BasicJsonType::binary_t::value_type;
  14345. static constexpr std::uint8_t UTF8_ACCEPT = 0;
  14346. static constexpr std::uint8_t UTF8_REJECT = 1;
  14347. public:
  14348. /*!
  14349. @param[in] s output stream to serialize to
  14350. @param[in] ichar indentation character to use
  14351. @param[in] error_handler_ how to react on decoding errors
  14352. */
  14353. serializer(output_adapter_t<char> s, const char ichar,
  14354. error_handler_t error_handler_ = error_handler_t::strict)
  14355. : o(std::move(s))
  14356. , loc(std::localeconv())
  14357. , thousands_sep(loc->thousands_sep == nullptr ? '\0' : std::char_traits<char>::to_char_type(* (loc->thousands_sep)))
  14358. , decimal_point(loc->decimal_point == nullptr ? '\0' : std::char_traits<char>::to_char_type(* (loc->decimal_point)))
  14359. , indent_char(ichar)
  14360. , indent_string(512, indent_char)
  14361. , error_handler(error_handler_)
  14362. {}
  14363. // delete because of pointer members
  14364. serializer(const serializer&) = delete;
  14365. serializer& operator=(const serializer&) = delete;
  14366. serializer(serializer&&) = delete;
  14367. serializer& operator=(serializer&&) = delete;
  14368. ~serializer() = default;
  14369. /*!
  14370. @brief internal implementation of the serialization function
  14371. This function is called by the public member function dump and organizes
  14372. the serialization internally. The indentation level is propagated as
  14373. additional parameter. In case of arrays and objects, the function is
  14374. called recursively.
  14375. - strings and object keys are escaped using `escape_string()`
  14376. - integer numbers are converted implicitly via `operator<<`
  14377. - floating-point numbers are converted to a string using `"%g"` format
  14378. - binary values are serialized as objects containing the subtype and the
  14379. byte array
  14380. @param[in] val value to serialize
  14381. @param[in] pretty_print whether the output shall be pretty-printed
  14382. @param[in] ensure_ascii If @a ensure_ascii is true, all non-ASCII characters
  14383. in the output are escaped with `\uXXXX` sequences, and the result consists
  14384. of ASCII characters only.
  14385. @param[in] indent_step the indent level
  14386. @param[in] current_indent the current indent level (only used internally)
  14387. */
  14388. void dump(const BasicJsonType& val,
  14389. const bool pretty_print,
  14390. const bool ensure_ascii,
  14391. const unsigned int indent_step,
  14392. const unsigned int current_indent = 0)
  14393. {
  14394. switch (val.m_type)
  14395. {
  14396. case value_t::object:
  14397. {
  14398. if (val.m_value.object->empty())
  14399. {
  14400. o->write_characters("{}", 2);
  14401. return;
  14402. }
  14403. if (pretty_print)
  14404. {
  14405. o->write_characters("{\n", 2);
  14406. // variable to hold indentation for recursive calls
  14407. const auto new_indent = current_indent + indent_step;
  14408. if (JSON_HEDLEY_UNLIKELY(indent_string.size() < new_indent))
  14409. {
  14410. indent_string.resize(indent_string.size() * 2, ' ');
  14411. }
  14412. // first n-1 elements
  14413. auto i = val.m_value.object->cbegin();
  14414. for (std::size_t cnt = 0; cnt < val.m_value.object->size() - 1; ++cnt, ++i)
  14415. {
  14416. o->write_characters(indent_string.c_str(), new_indent);
  14417. o->write_character('\"');
  14418. dump_escaped(i->first, ensure_ascii);
  14419. o->write_characters("\": ", 3);
  14420. dump(i->second, true, ensure_ascii, indent_step, new_indent);
  14421. o->write_characters(",\n", 2);
  14422. }
  14423. // last element
  14424. JSON_ASSERT(i != val.m_value.object->cend());
  14425. JSON_ASSERT(std::next(i) == val.m_value.object->cend());
  14426. o->write_characters(indent_string.c_str(), new_indent);
  14427. o->write_character('\"');
  14428. dump_escaped(i->first, ensure_ascii);
  14429. o->write_characters("\": ", 3);
  14430. dump(i->second, true, ensure_ascii, indent_step, new_indent);
  14431. o->write_character('\n');
  14432. o->write_characters(indent_string.c_str(), current_indent);
  14433. o->write_character('}');
  14434. }
  14435. else
  14436. {
  14437. o->write_character('{');
  14438. // first n-1 elements
  14439. auto i = val.m_value.object->cbegin();
  14440. for (std::size_t cnt = 0; cnt < val.m_value.object->size() - 1; ++cnt, ++i)
  14441. {
  14442. o->write_character('\"');
  14443. dump_escaped(i->first, ensure_ascii);
  14444. o->write_characters("\":", 2);
  14445. dump(i->second, false, ensure_ascii, indent_step, current_indent);
  14446. o->write_character(',');
  14447. }
  14448. // last element
  14449. JSON_ASSERT(i != val.m_value.object->cend());
  14450. JSON_ASSERT(std::next(i) == val.m_value.object->cend());
  14451. o->write_character('\"');
  14452. dump_escaped(i->first, ensure_ascii);
  14453. o->write_characters("\":", 2);
  14454. dump(i->second, false, ensure_ascii, indent_step, current_indent);
  14455. o->write_character('}');
  14456. }
  14457. return;
  14458. }
  14459. case value_t::array:
  14460. {
  14461. if (val.m_value.array->empty())
  14462. {
  14463. o->write_characters("[]", 2);
  14464. return;
  14465. }
  14466. if (pretty_print)
  14467. {
  14468. o->write_characters("[\n", 2);
  14469. // variable to hold indentation for recursive calls
  14470. const auto new_indent = current_indent + indent_step;
  14471. if (JSON_HEDLEY_UNLIKELY(indent_string.size() < new_indent))
  14472. {
  14473. indent_string.resize(indent_string.size() * 2, ' ');
  14474. }
  14475. // first n-1 elements
  14476. for (auto i = val.m_value.array->cbegin();
  14477. i != val.m_value.array->cend() - 1; ++i)
  14478. {
  14479. o->write_characters(indent_string.c_str(), new_indent);
  14480. dump(*i, true, ensure_ascii, indent_step, new_indent);
  14481. o->write_characters(",\n", 2);
  14482. }
  14483. // last element
  14484. JSON_ASSERT(!val.m_value.array->empty());
  14485. o->write_characters(indent_string.c_str(), new_indent);
  14486. dump(val.m_value.array->back(), true, ensure_ascii, indent_step, new_indent);
  14487. o->write_character('\n');
  14488. o->write_characters(indent_string.c_str(), current_indent);
  14489. o->write_character(']');
  14490. }
  14491. else
  14492. {
  14493. o->write_character('[');
  14494. // first n-1 elements
  14495. for (auto i = val.m_value.array->cbegin();
  14496. i != val.m_value.array->cend() - 1; ++i)
  14497. {
  14498. dump(*i, false, ensure_ascii, indent_step, current_indent);
  14499. o->write_character(',');
  14500. }
  14501. // last element
  14502. JSON_ASSERT(!val.m_value.array->empty());
  14503. dump(val.m_value.array->back(), false, ensure_ascii, indent_step, current_indent);
  14504. o->write_character(']');
  14505. }
  14506. return;
  14507. }
  14508. case value_t::string:
  14509. {
  14510. o->write_character('\"');
  14511. dump_escaped(*val.m_value.string, ensure_ascii);
  14512. o->write_character('\"');
  14513. return;
  14514. }
  14515. case value_t::binary:
  14516. {
  14517. if (pretty_print)
  14518. {
  14519. o->write_characters("{\n", 2);
  14520. // variable to hold indentation for recursive calls
  14521. const auto new_indent = current_indent + indent_step;
  14522. if (JSON_HEDLEY_UNLIKELY(indent_string.size() < new_indent))
  14523. {
  14524. indent_string.resize(indent_string.size() * 2, ' ');
  14525. }
  14526. o->write_characters(indent_string.c_str(), new_indent);
  14527. o->write_characters("\"bytes\": [", 10);
  14528. if (!val.m_value.binary->empty())
  14529. {
  14530. for (auto i = val.m_value.binary->cbegin();
  14531. i != val.m_value.binary->cend() - 1; ++i)
  14532. {
  14533. dump_integer(*i);
  14534. o->write_characters(", ", 2);
  14535. }
  14536. dump_integer(val.m_value.binary->back());
  14537. }
  14538. o->write_characters("],\n", 3);
  14539. o->write_characters(indent_string.c_str(), new_indent);
  14540. o->write_characters("\"subtype\": ", 11);
  14541. if (val.m_value.binary->has_subtype())
  14542. {
  14543. dump_integer(val.m_value.binary->subtype());
  14544. }
  14545. else
  14546. {
  14547. o->write_characters("null", 4);
  14548. }
  14549. o->write_character('\n');
  14550. o->write_characters(indent_string.c_str(), current_indent);
  14551. o->write_character('}');
  14552. }
  14553. else
  14554. {
  14555. o->write_characters("{\"bytes\":[", 10);
  14556. if (!val.m_value.binary->empty())
  14557. {
  14558. for (auto i = val.m_value.binary->cbegin();
  14559. i != val.m_value.binary->cend() - 1; ++i)
  14560. {
  14561. dump_integer(*i);
  14562. o->write_character(',');
  14563. }
  14564. dump_integer(val.m_value.binary->back());
  14565. }
  14566. o->write_characters("],\"subtype\":", 12);
  14567. if (val.m_value.binary->has_subtype())
  14568. {
  14569. dump_integer(val.m_value.binary->subtype());
  14570. o->write_character('}');
  14571. }
  14572. else
  14573. {
  14574. o->write_characters("null}", 5);
  14575. }
  14576. }
  14577. return;
  14578. }
  14579. case value_t::boolean:
  14580. {
  14581. if (val.m_value.boolean)
  14582. {
  14583. o->write_characters("true", 4);
  14584. }
  14585. else
  14586. {
  14587. o->write_characters("false", 5);
  14588. }
  14589. return;
  14590. }
  14591. case value_t::number_integer:
  14592. {
  14593. dump_integer(val.m_value.number_integer);
  14594. return;
  14595. }
  14596. case value_t::number_unsigned:
  14597. {
  14598. dump_integer(val.m_value.number_unsigned);
  14599. return;
  14600. }
  14601. case value_t::number_float:
  14602. {
  14603. dump_float(val.m_value.number_float);
  14604. return;
  14605. }
  14606. case value_t::discarded:
  14607. {
  14608. o->write_characters("<discarded>", 11);
  14609. return;
  14610. }
  14611. case value_t::null:
  14612. {
  14613. o->write_characters("null", 4);
  14614. return;
  14615. }
  14616. default: // LCOV_EXCL_LINE
  14617. JSON_ASSERT(false); // NOLINT(cert-dcl03-c,hicpp-static-assert,misc-static-assert) LCOV_EXCL_LINE
  14618. }
  14619. }
  14620. JSON_PRIVATE_UNLESS_TESTED:
  14621. /*!
  14622. @brief dump escaped string
  14623. Escape a string by replacing certain special characters by a sequence of an
  14624. escape character (backslash) and another character and other control
  14625. characters by a sequence of "\u" followed by a four-digit hex
  14626. representation. The escaped string is written to output stream @a o.
  14627. @param[in] s the string to escape
  14628. @param[in] ensure_ascii whether to escape non-ASCII characters with
  14629. \uXXXX sequences
  14630. @complexity Linear in the length of string @a s.
  14631. */
  14632. void dump_escaped(const string_t& s, const bool ensure_ascii)
  14633. {
  14634. std::uint32_t codepoint{};
  14635. std::uint8_t state = UTF8_ACCEPT;
  14636. std::size_t bytes = 0; // number of bytes written to string_buffer
  14637. // number of bytes written at the point of the last valid byte
  14638. std::size_t bytes_after_last_accept = 0;
  14639. std::size_t undumped_chars = 0;
  14640. for (std::size_t i = 0; i < s.size(); ++i)
  14641. {
  14642. const auto byte = static_cast<std::uint8_t>(s[i]);
  14643. switch (decode(state, codepoint, byte))
  14644. {
  14645. case UTF8_ACCEPT: // decode found a new code point
  14646. {
  14647. switch (codepoint)
  14648. {
  14649. case 0x08: // backspace
  14650. {
  14651. string_buffer[bytes++] = '\\';
  14652. string_buffer[bytes++] = 'b';
  14653. break;
  14654. }
  14655. case 0x09: // horizontal tab
  14656. {
  14657. string_buffer[bytes++] = '\\';
  14658. string_buffer[bytes++] = 't';
  14659. break;
  14660. }
  14661. case 0x0A: // newline
  14662. {
  14663. string_buffer[bytes++] = '\\';
  14664. string_buffer[bytes++] = 'n';
  14665. break;
  14666. }
  14667. case 0x0C: // formfeed
  14668. {
  14669. string_buffer[bytes++] = '\\';
  14670. string_buffer[bytes++] = 'f';
  14671. break;
  14672. }
  14673. case 0x0D: // carriage return
  14674. {
  14675. string_buffer[bytes++] = '\\';
  14676. string_buffer[bytes++] = 'r';
  14677. break;
  14678. }
  14679. case 0x22: // quotation mark
  14680. {
  14681. string_buffer[bytes++] = '\\';
  14682. string_buffer[bytes++] = '\"';
  14683. break;
  14684. }
  14685. case 0x5C: // reverse solidus
  14686. {
  14687. string_buffer[bytes++] = '\\';
  14688. string_buffer[bytes++] = '\\';
  14689. break;
  14690. }
  14691. default:
  14692. {
  14693. // escape control characters (0x00..0x1F) or, if
  14694. // ensure_ascii parameter is used, non-ASCII characters
  14695. if ((codepoint <= 0x1F) || (ensure_ascii && (codepoint >= 0x7F)))
  14696. {
  14697. if (codepoint <= 0xFFFF)
  14698. {
  14699. // NOLINTNEXTLINE(cppcoreguidelines-pro-type-vararg,hicpp-vararg)
  14700. (std::snprintf)(string_buffer.data() + bytes, 7, "\\u%04x",
  14701. static_cast<std::uint16_t>(codepoint));
  14702. bytes += 6;
  14703. }
  14704. else
  14705. {
  14706. // NOLINTNEXTLINE(cppcoreguidelines-pro-type-vararg,hicpp-vararg)
  14707. (std::snprintf)(string_buffer.data() + bytes, 13, "\\u%04x\\u%04x",
  14708. static_cast<std::uint16_t>(0xD7C0u + (codepoint >> 10u)),
  14709. static_cast<std::uint16_t>(0xDC00u + (codepoint & 0x3FFu)));
  14710. bytes += 12;
  14711. }
  14712. }
  14713. else
  14714. {
  14715. // copy byte to buffer (all previous bytes
  14716. // been copied have in default case above)
  14717. string_buffer[bytes++] = s[i];
  14718. }
  14719. break;
  14720. }
  14721. }
  14722. // write buffer and reset index; there must be 13 bytes
  14723. // left, as this is the maximal number of bytes to be
  14724. // written ("\uxxxx\uxxxx\0") for one code point
  14725. if (string_buffer.size() - bytes < 13)
  14726. {
  14727. o->write_characters(string_buffer.data(), bytes);
  14728. bytes = 0;
  14729. }
  14730. // remember the byte position of this accept
  14731. bytes_after_last_accept = bytes;
  14732. undumped_chars = 0;
  14733. break;
  14734. }
  14735. case UTF8_REJECT: // decode found invalid UTF-8 byte
  14736. {
  14737. switch (error_handler)
  14738. {
  14739. case error_handler_t::strict:
  14740. {
  14741. std::string sn(9, '\0');
  14742. // NOLINTNEXTLINE(cppcoreguidelines-pro-type-vararg,hicpp-vararg)
  14743. (std::snprintf)(&sn[0], sn.size(), "%.2X", byte);
  14744. JSON_THROW(type_error::create(316, "invalid UTF-8 byte at index " + std::to_string(i) + ": 0x" + sn, BasicJsonType()));
  14745. }
  14746. case error_handler_t::ignore:
  14747. case error_handler_t::replace:
  14748. {
  14749. // in case we saw this character the first time, we
  14750. // would like to read it again, because the byte
  14751. // may be OK for itself, but just not OK for the
  14752. // previous sequence
  14753. if (undumped_chars > 0)
  14754. {
  14755. --i;
  14756. }
  14757. // reset length buffer to the last accepted index;
  14758. // thus removing/ignoring the invalid characters
  14759. bytes = bytes_after_last_accept;
  14760. if (error_handler == error_handler_t::replace)
  14761. {
  14762. // add a replacement character
  14763. if (ensure_ascii)
  14764. {
  14765. string_buffer[bytes++] = '\\';
  14766. string_buffer[bytes++] = 'u';
  14767. string_buffer[bytes++] = 'f';
  14768. string_buffer[bytes++] = 'f';
  14769. string_buffer[bytes++] = 'f';
  14770. string_buffer[bytes++] = 'd';
  14771. }
  14772. else
  14773. {
  14774. string_buffer[bytes++] = detail::binary_writer<BasicJsonType, char>::to_char_type('\xEF');
  14775. string_buffer[bytes++] = detail::binary_writer<BasicJsonType, char>::to_char_type('\xBF');
  14776. string_buffer[bytes++] = detail::binary_writer<BasicJsonType, char>::to_char_type('\xBD');
  14777. }
  14778. // write buffer and reset index; there must be 13 bytes
  14779. // left, as this is the maximal number of bytes to be
  14780. // written ("\uxxxx\uxxxx\0") for one code point
  14781. if (string_buffer.size() - bytes < 13)
  14782. {
  14783. o->write_characters(string_buffer.data(), bytes);
  14784. bytes = 0;
  14785. }
  14786. bytes_after_last_accept = bytes;
  14787. }
  14788. undumped_chars = 0;
  14789. // continue processing the string
  14790. state = UTF8_ACCEPT;
  14791. break;
  14792. }
  14793. default: // LCOV_EXCL_LINE
  14794. JSON_ASSERT(false); // NOLINT(cert-dcl03-c,hicpp-static-assert,misc-static-assert) LCOV_EXCL_LINE
  14795. }
  14796. break;
  14797. }
  14798. default: // decode found yet incomplete multi-byte code point
  14799. {
  14800. if (!ensure_ascii)
  14801. {
  14802. // code point will not be escaped - copy byte to buffer
  14803. string_buffer[bytes++] = s[i];
  14804. }
  14805. ++undumped_chars;
  14806. break;
  14807. }
  14808. }
  14809. }
  14810. // we finished processing the string
  14811. if (JSON_HEDLEY_LIKELY(state == UTF8_ACCEPT))
  14812. {
  14813. // write buffer
  14814. if (bytes > 0)
  14815. {
  14816. o->write_characters(string_buffer.data(), bytes);
  14817. }
  14818. }
  14819. else
  14820. {
  14821. // we finish reading, but do not accept: string was incomplete
  14822. switch (error_handler)
  14823. {
  14824. case error_handler_t::strict:
  14825. {
  14826. std::string sn(9, '\0');
  14827. // NOLINTNEXTLINE(cppcoreguidelines-pro-type-vararg,hicpp-vararg)
  14828. (std::snprintf)(&sn[0], sn.size(), "%.2X", static_cast<std::uint8_t>(s.back()));
  14829. JSON_THROW(type_error::create(316, "incomplete UTF-8 string; last byte: 0x" + sn, BasicJsonType()));
  14830. }
  14831. case error_handler_t::ignore:
  14832. {
  14833. // write all accepted bytes
  14834. o->write_characters(string_buffer.data(), bytes_after_last_accept);
  14835. break;
  14836. }
  14837. case error_handler_t::replace:
  14838. {
  14839. // write all accepted bytes
  14840. o->write_characters(string_buffer.data(), bytes_after_last_accept);
  14841. // add a replacement character
  14842. if (ensure_ascii)
  14843. {
  14844. o->write_characters("\\ufffd", 6);
  14845. }
  14846. else
  14847. {
  14848. o->write_characters("\xEF\xBF\xBD", 3);
  14849. }
  14850. break;
  14851. }
  14852. default: // LCOV_EXCL_LINE
  14853. JSON_ASSERT(false); // NOLINT(cert-dcl03-c,hicpp-static-assert,misc-static-assert) LCOV_EXCL_LINE
  14854. }
  14855. }
  14856. }
  14857. private:
  14858. /*!
  14859. @brief count digits
  14860. Count the number of decimal (base 10) digits for an input unsigned integer.
  14861. @param[in] x unsigned integer number to count its digits
  14862. @return number of decimal digits
  14863. */
  14864. inline unsigned int count_digits(number_unsigned_t x) noexcept
  14865. {
  14866. unsigned int n_digits = 1;
  14867. for (;;)
  14868. {
  14869. if (x < 10)
  14870. {
  14871. return n_digits;
  14872. }
  14873. if (x < 100)
  14874. {
  14875. return n_digits + 1;
  14876. }
  14877. if (x < 1000)
  14878. {
  14879. return n_digits + 2;
  14880. }
  14881. if (x < 10000)
  14882. {
  14883. return n_digits + 3;
  14884. }
  14885. x = x / 10000u;
  14886. n_digits += 4;
  14887. }
  14888. }
  14889. /*!
  14890. @brief dump an integer
  14891. Dump a given integer to output stream @a o. Works internally with
  14892. @a number_buffer.
  14893. @param[in] x integer number (signed or unsigned) to dump
  14894. @tparam NumberType either @a number_integer_t or @a number_unsigned_t
  14895. */
  14896. template < typename NumberType, detail::enable_if_t <
  14897. std::is_integral<NumberType>::value ||
  14898. std::is_same<NumberType, number_unsigned_t>::value ||
  14899. std::is_same<NumberType, number_integer_t>::value ||
  14900. std::is_same<NumberType, binary_char_t>::value,
  14901. int > = 0 >
  14902. void dump_integer(NumberType x)
  14903. {
  14904. static constexpr std::array<std::array<char, 2>, 100> digits_to_99
  14905. {
  14906. {
  14907. {{'0', '0'}}, {{'0', '1'}}, {{'0', '2'}}, {{'0', '3'}}, {{'0', '4'}}, {{'0', '5'}}, {{'0', '6'}}, {{'0', '7'}}, {{'0', '8'}}, {{'0', '9'}},
  14908. {{'1', '0'}}, {{'1', '1'}}, {{'1', '2'}}, {{'1', '3'}}, {{'1', '4'}}, {{'1', '5'}}, {{'1', '6'}}, {{'1', '7'}}, {{'1', '8'}}, {{'1', '9'}},
  14909. {{'2', '0'}}, {{'2', '1'}}, {{'2', '2'}}, {{'2', '3'}}, {{'2', '4'}}, {{'2', '5'}}, {{'2', '6'}}, {{'2', '7'}}, {{'2', '8'}}, {{'2', '9'}},
  14910. {{'3', '0'}}, {{'3', '1'}}, {{'3', '2'}}, {{'3', '3'}}, {{'3', '4'}}, {{'3', '5'}}, {{'3', '6'}}, {{'3', '7'}}, {{'3', '8'}}, {{'3', '9'}},
  14911. {{'4', '0'}}, {{'4', '1'}}, {{'4', '2'}}, {{'4', '3'}}, {{'4', '4'}}, {{'4', '5'}}, {{'4', '6'}}, {{'4', '7'}}, {{'4', '8'}}, {{'4', '9'}},
  14912. {{'5', '0'}}, {{'5', '1'}}, {{'5', '2'}}, {{'5', '3'}}, {{'5', '4'}}, {{'5', '5'}}, {{'5', '6'}}, {{'5', '7'}}, {{'5', '8'}}, {{'5', '9'}},
  14913. {{'6', '0'}}, {{'6', '1'}}, {{'6', '2'}}, {{'6', '3'}}, {{'6', '4'}}, {{'6', '5'}}, {{'6', '6'}}, {{'6', '7'}}, {{'6', '8'}}, {{'6', '9'}},
  14914. {{'7', '0'}}, {{'7', '1'}}, {{'7', '2'}}, {{'7', '3'}}, {{'7', '4'}}, {{'7', '5'}}, {{'7', '6'}}, {{'7', '7'}}, {{'7', '8'}}, {{'7', '9'}},
  14915. {{'8', '0'}}, {{'8', '1'}}, {{'8', '2'}}, {{'8', '3'}}, {{'8', '4'}}, {{'8', '5'}}, {{'8', '6'}}, {{'8', '7'}}, {{'8', '8'}}, {{'8', '9'}},
  14916. {{'9', '0'}}, {{'9', '1'}}, {{'9', '2'}}, {{'9', '3'}}, {{'9', '4'}}, {{'9', '5'}}, {{'9', '6'}}, {{'9', '7'}}, {{'9', '8'}}, {{'9', '9'}},
  14917. }
  14918. };
  14919. // special case for "0"
  14920. if (x == 0)
  14921. {
  14922. o->write_character('0');
  14923. return;
  14924. }
  14925. // use a pointer to fill the buffer
  14926. auto buffer_ptr = number_buffer.begin(); // NOLINT(llvm-qualified-auto,readability-qualified-auto,cppcoreguidelines-pro-type-vararg,hicpp-vararg)
  14927. const bool is_negative = std::is_signed<NumberType>::value && !(x >= 0); // see issue #755
  14928. number_unsigned_t abs_value;
  14929. unsigned int n_chars{};
  14930. if (is_negative)
  14931. {
  14932. *buffer_ptr = '-';
  14933. abs_value = remove_sign(static_cast<number_integer_t>(x));
  14934. // account one more byte for the minus sign
  14935. n_chars = 1 + count_digits(abs_value);
  14936. }
  14937. else
  14938. {
  14939. abs_value = static_cast<number_unsigned_t>(x);
  14940. n_chars = count_digits(abs_value);
  14941. }
  14942. // spare 1 byte for '\0'
  14943. JSON_ASSERT(n_chars < number_buffer.size() - 1);
  14944. // jump to the end to generate the string from backward
  14945. // so we later avoid reversing the result
  14946. buffer_ptr += n_chars;
  14947. // Fast int2ascii implementation inspired by "Fastware" talk by Andrei Alexandrescu
  14948. // See: https://www.youtube.com/watch?v=o4-CwDo2zpg
  14949. while (abs_value >= 100)
  14950. {
  14951. const auto digits_index = static_cast<unsigned>((abs_value % 100));
  14952. abs_value /= 100;
  14953. *(--buffer_ptr) = digits_to_99[digits_index][1];
  14954. *(--buffer_ptr) = digits_to_99[digits_index][0];
  14955. }
  14956. if (abs_value >= 10)
  14957. {
  14958. const auto digits_index = static_cast<unsigned>(abs_value);
  14959. *(--buffer_ptr) = digits_to_99[digits_index][1];
  14960. *(--buffer_ptr) = digits_to_99[digits_index][0];
  14961. }
  14962. else
  14963. {
  14964. *(--buffer_ptr) = static_cast<char>('0' + abs_value);
  14965. }
  14966. o->write_characters(number_buffer.data(), n_chars);
  14967. }
  14968. /*!
  14969. @brief dump a floating-point number
  14970. Dump a given floating-point number to output stream @a o. Works internally
  14971. with @a number_buffer.
  14972. @param[in] x floating-point number to dump
  14973. */
  14974. void dump_float(number_float_t x)
  14975. {
  14976. // NaN / inf
  14977. if (!std::isfinite(x))
  14978. {
  14979. o->write_characters("null", 4);
  14980. return;
  14981. }
  14982. // If number_float_t is an IEEE-754 single or double precision number,
  14983. // use the Grisu2 algorithm to produce short numbers which are
  14984. // guaranteed to round-trip, using strtof and strtod, resp.
  14985. //
  14986. // NB: The test below works if <long double> == <double>.
  14987. static constexpr bool is_ieee_single_or_double
  14988. = (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) ||
  14989. (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);
  14990. dump_float(x, std::integral_constant<bool, is_ieee_single_or_double>());
  14991. }
  14992. void dump_float(number_float_t x, std::true_type /*is_ieee_single_or_double*/)
  14993. {
  14994. auto* begin = number_buffer.data();
  14995. auto* end = ::nlohmann::detail::to_chars(begin, begin + number_buffer.size(), x);
  14996. o->write_characters(begin, static_cast<size_t>(end - begin));
  14997. }
  14998. void dump_float(number_float_t x, std::false_type /*is_ieee_single_or_double*/)
  14999. {
  15000. // get number of digits for a float -> text -> float round-trip
  15001. static constexpr auto d = std::numeric_limits<number_float_t>::max_digits10;
  15002. // the actual conversion
  15003. // NOLINTNEXTLINE(cppcoreguidelines-pro-type-vararg,hicpp-vararg)
  15004. std::ptrdiff_t len = (std::snprintf)(number_buffer.data(), number_buffer.size(), "%.*g", d, x);
  15005. // negative value indicates an error
  15006. JSON_ASSERT(len > 0);
  15007. // check if buffer was large enough
  15008. JSON_ASSERT(static_cast<std::size_t>(len) < number_buffer.size());
  15009. // erase thousands separator
  15010. if (thousands_sep != '\0')
  15011. {
  15012. // NOLINTNEXTLINE(readability-qualified-auto,llvm-qualified-auto): std::remove returns an iterator, see https://github.com/nlohmann/json/issues/3081
  15013. const auto end = std::remove(number_buffer.begin(), number_buffer.begin() + len, thousands_sep);
  15014. std::fill(end, number_buffer.end(), '\0');
  15015. JSON_ASSERT((end - number_buffer.begin()) <= len);
  15016. len = (end - number_buffer.begin());
  15017. }
  15018. // convert decimal point to '.'
  15019. if (decimal_point != '\0' && decimal_point != '.')
  15020. {
  15021. // NOLINTNEXTLINE(readability-qualified-auto,llvm-qualified-auto): std::find returns an iterator, see https://github.com/nlohmann/json/issues/3081
  15022. const auto dec_pos = std::find(number_buffer.begin(), number_buffer.end(), decimal_point);
  15023. if (dec_pos != number_buffer.end())
  15024. {
  15025. *dec_pos = '.';
  15026. }
  15027. }
  15028. o->write_characters(number_buffer.data(), static_cast<std::size_t>(len));
  15029. // determine if need to append ".0"
  15030. const bool value_is_int_like =
  15031. std::none_of(number_buffer.begin(), number_buffer.begin() + len + 1,
  15032. [](char c)
  15033. {
  15034. return c == '.' || c == 'e';
  15035. });
  15036. if (value_is_int_like)
  15037. {
  15038. o->write_characters(".0", 2);
  15039. }
  15040. }
  15041. /*!
  15042. @brief check whether a string is UTF-8 encoded
  15043. The function checks each byte of a string whether it is UTF-8 encoded. The
  15044. result of the check is stored in the @a state parameter. The function must
  15045. be called initially with state 0 (accept). State 1 means the string must
  15046. be rejected, because the current byte is not allowed. If the string is
  15047. completely processed, but the state is non-zero, the string ended
  15048. prematurely; that is, the last byte indicated more bytes should have
  15049. followed.
  15050. @param[in,out] state the state of the decoding
  15051. @param[in,out] codep codepoint (valid only if resulting state is UTF8_ACCEPT)
  15052. @param[in] byte next byte to decode
  15053. @return new state
  15054. @note The function has been edited: a std::array is used.
  15055. @copyright Copyright (c) 2008-2009 Bjoern Hoehrmann <[email protected]>
  15056. @sa http://bjoern.hoehrmann.de/utf-8/decoder/dfa/
  15057. */
  15058. static std::uint8_t decode(std::uint8_t& state, std::uint32_t& codep, const std::uint8_t byte) noexcept
  15059. {
  15060. static const std::array<std::uint8_t, 400> utf8d =
  15061. {
  15062. {
  15063. 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
  15064. 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
  15065. 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
  15066. 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
  15067. 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
  15068. 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
  15069. 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
  15070. 0xA, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x4, 0x3, 0x3, // E0..EF
  15071. 0xB, 0x6, 0x6, 0x6, 0x5, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, // F0..FF
  15072. 0x0, 0x1, 0x2, 0x3, 0x5, 0x8, 0x7, 0x1, 0x1, 0x1, 0x4, 0x6, 0x1, 0x1, 0x1, 0x1, // s0..s0
  15073. 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
  15074. 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
  15075. 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
  15076. 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
  15077. }
  15078. };
  15079. JSON_ASSERT(byte < utf8d.size());
  15080. const std::uint8_t type = utf8d[byte];
  15081. codep = (state != UTF8_ACCEPT)
  15082. ? (byte & 0x3fu) | (codep << 6u)
  15083. : (0xFFu >> type) & (byte);
  15084. std::size_t index = 256u + static_cast<size_t>(state) * 16u + static_cast<size_t>(type);
  15085. JSON_ASSERT(index < 400);
  15086. state = utf8d[index];
  15087. return state;
  15088. }
  15089. /*
  15090. * Overload to make the compiler happy while it is instantiating
  15091. * dump_integer for number_unsigned_t.
  15092. * Must never be called.
  15093. */
  15094. number_unsigned_t remove_sign(number_unsigned_t x)
  15095. {
  15096. JSON_ASSERT(false); // NOLINT(cert-dcl03-c,hicpp-static-assert,misc-static-assert) LCOV_EXCL_LINE
  15097. return x; // LCOV_EXCL_LINE
  15098. }
  15099. /*
  15100. * Helper function for dump_integer
  15101. *
  15102. * This function takes a negative signed integer and returns its absolute
  15103. * value as unsigned integer. The plus/minus shuffling is necessary as we can
  15104. * not directly remove the sign of an arbitrary signed integer as the
  15105. * absolute values of INT_MIN and INT_MAX are usually not the same. See
  15106. * #1708 for details.
  15107. */
  15108. inline number_unsigned_t remove_sign(number_integer_t x) noexcept
  15109. {
  15110. JSON_ASSERT(x < 0 && x < (std::numeric_limits<number_integer_t>::max)()); // NOLINT(misc-redundant-expression)
  15111. return static_cast<number_unsigned_t>(-(x + 1)) + 1;
  15112. }
  15113. private:
  15114. /// the output of the serializer
  15115. output_adapter_t<char> o = nullptr;
  15116. /// a (hopefully) large enough character buffer
  15117. std::array<char, 64> number_buffer{{}};
  15118. /// the locale
  15119. const std::lconv* loc = nullptr;
  15120. /// the locale's thousand separator character
  15121. const char thousands_sep = '\0';
  15122. /// the locale's decimal point character
  15123. const char decimal_point = '\0';
  15124. /// string buffer
  15125. std::array<char, 512> string_buffer{{}};
  15126. /// the indentation character
  15127. const char indent_char;
  15128. /// the indentation string
  15129. string_t indent_string;
  15130. /// error_handler how to react on decoding errors
  15131. const error_handler_t error_handler;
  15132. };
  15133. } // namespace detail
  15134. } // namespace nlohmann
  15135. // #include <nlohmann/detail/value_t.hpp>
  15136. // #include <nlohmann/json_fwd.hpp>
  15137. // #include <nlohmann/ordered_map.hpp>
  15138. #include <functional> // less
  15139. #include <initializer_list> // initializer_list
  15140. #include <iterator> // input_iterator_tag, iterator_traits
  15141. #include <memory> // allocator
  15142. #include <stdexcept> // for out_of_range
  15143. #include <type_traits> // enable_if, is_convertible
  15144. #include <utility> // pair
  15145. #include <vector> // vector
  15146. // #include <nlohmann/detail/macro_scope.hpp>
  15147. namespace nlohmann
  15148. {
  15149. /// ordered_map: a minimal map-like container that preserves insertion order
  15150. /// for use within nlohmann::basic_json<ordered_map>
  15151. template <class Key, class T, class IgnoredLess = std::less<Key>,
  15152. class Allocator = std::allocator<std::pair<const Key, T>>>
  15153. struct ordered_map : std::vector<std::pair<const Key, T>, Allocator>
  15154. {
  15155. using key_type = Key;
  15156. using mapped_type = T;
  15157. using Container = std::vector<std::pair<const Key, T>, Allocator>;
  15158. using typename Container::iterator;
  15159. using typename Container::const_iterator;
  15160. using typename Container::size_type;
  15161. using typename Container::value_type;
  15162. // Explicit constructors instead of `using Container::Container`
  15163. // otherwise older compilers choke on it (GCC <= 5.5, xcode <= 9.4)
  15164. ordered_map(const Allocator& alloc = Allocator()) : Container{alloc} {}
  15165. template <class It>
  15166. ordered_map(It first, It last, const Allocator& alloc = Allocator())
  15167. : Container{first, last, alloc} {}
  15168. ordered_map(std::initializer_list<T> init, const Allocator& alloc = Allocator() )
  15169. : Container{init, alloc} {}
  15170. std::pair<iterator, bool> emplace(const key_type& key, T&& t)
  15171. {
  15172. for (auto it = this->begin(); it != this->end(); ++it)
  15173. {
  15174. if (it->first == key)
  15175. {
  15176. return {it, false};
  15177. }
  15178. }
  15179. Container::emplace_back(key, t);
  15180. return {--this->end(), true};
  15181. }
  15182. T& operator[](const Key& key)
  15183. {
  15184. return emplace(key, T{}).first->second;
  15185. }
  15186. const T& operator[](const Key& key) const
  15187. {
  15188. return at(key);
  15189. }
  15190. T& at(const Key& key)
  15191. {
  15192. for (auto it = this->begin(); it != this->end(); ++it)
  15193. {
  15194. if (it->first == key)
  15195. {
  15196. return it->second;
  15197. }
  15198. }
  15199. JSON_THROW(std::out_of_range("key not found"));
  15200. }
  15201. const T& at(const Key& key) const
  15202. {
  15203. for (auto it = this->begin(); it != this->end(); ++it)
  15204. {
  15205. if (it->first == key)
  15206. {
  15207. return it->second;
  15208. }
  15209. }
  15210. JSON_THROW(std::out_of_range("key not found"));
  15211. }
  15212. size_type erase(const Key& key)
  15213. {
  15214. for (auto it = this->begin(); it != this->end(); ++it)
  15215. {
  15216. if (it->first == key)
  15217. {
  15218. // Since we cannot move const Keys, re-construct them in place
  15219. for (auto next = it; ++next != this->end(); ++it)
  15220. {
  15221. it->~value_type(); // Destroy but keep allocation
  15222. new (&*it) value_type{std::move(*next)};
  15223. }
  15224. Container::pop_back();
  15225. return 1;
  15226. }
  15227. }
  15228. return 0;
  15229. }
  15230. iterator erase(iterator pos)
  15231. {
  15232. auto it = pos;
  15233. // Since we cannot move const Keys, re-construct them in place
  15234. for (auto next = it; ++next != this->end(); ++it)
  15235. {
  15236. it->~value_type(); // Destroy but keep allocation
  15237. new (&*it) value_type{std::move(*next)};
  15238. }
  15239. Container::pop_back();
  15240. return pos;
  15241. }
  15242. size_type count(const Key& key) const
  15243. {
  15244. for (auto it = this->begin(); it != this->end(); ++it)
  15245. {
  15246. if (it->first == key)
  15247. {
  15248. return 1;
  15249. }
  15250. }
  15251. return 0;
  15252. }
  15253. iterator find(const Key& key)
  15254. {
  15255. for (auto it = this->begin(); it != this->end(); ++it)
  15256. {
  15257. if (it->first == key)
  15258. {
  15259. return it;
  15260. }
  15261. }
  15262. return Container::end();
  15263. }
  15264. const_iterator find(const Key& key) const
  15265. {
  15266. for (auto it = this->begin(); it != this->end(); ++it)
  15267. {
  15268. if (it->first == key)
  15269. {
  15270. return it;
  15271. }
  15272. }
  15273. return Container::end();
  15274. }
  15275. std::pair<iterator, bool> insert( value_type&& value )
  15276. {
  15277. return emplace(value.first, std::move(value.second));
  15278. }
  15279. std::pair<iterator, bool> insert( const value_type& value )
  15280. {
  15281. for (auto it = this->begin(); it != this->end(); ++it)
  15282. {
  15283. if (it->first == value.first)
  15284. {
  15285. return {it, false};
  15286. }
  15287. }
  15288. Container::push_back(value);
  15289. return {--this->end(), true};
  15290. }
  15291. template<typename InputIt>
  15292. using require_input_iter = typename std::enable_if<std::is_convertible<typename std::iterator_traits<InputIt>::iterator_category,
  15293. std::input_iterator_tag>::value>::type;
  15294. template<typename InputIt, typename = require_input_iter<InputIt>>
  15295. void insert(InputIt first, InputIt last)
  15296. {
  15297. for (auto it = first; it != last; ++it)
  15298. {
  15299. insert(*it);
  15300. }
  15301. }
  15302. };
  15303. } // namespace nlohmann
  15304. #if defined(JSON_HAS_CPP_17)
  15305. #include <string_view>
  15306. #endif
  15307. /*!
  15308. @brief namespace for Niels Lohmann
  15309. @see https://github.com/nlohmann
  15310. @since version 1.0.0
  15311. */
  15312. namespace nlohmann
  15313. {
  15314. /*!
  15315. @brief a class to store JSON values
  15316. @tparam ObjectType type for JSON objects (`std::map` by default; will be used
  15317. in @ref object_t)
  15318. @tparam ArrayType type for JSON arrays (`std::vector` by default; will be used
  15319. in @ref array_t)
  15320. @tparam StringType type for JSON strings and object keys (`std::string` by
  15321. default; will be used in @ref string_t)
  15322. @tparam BooleanType type for JSON booleans (`bool` by default; will be used
  15323. in @ref boolean_t)
  15324. @tparam NumberIntegerType type for JSON integer numbers (`int64_t` by
  15325. default; will be used in @ref number_integer_t)
  15326. @tparam NumberUnsignedType type for JSON unsigned integer numbers (@c
  15327. `uint64_t` by default; will be used in @ref number_unsigned_t)
  15328. @tparam NumberFloatType type for JSON floating-point numbers (`double` by
  15329. default; will be used in @ref number_float_t)
  15330. @tparam BinaryType type for packed binary data for compatibility with binary
  15331. serialization formats (`std::vector<std::uint8_t>` by default; will be used in
  15332. @ref binary_t)
  15333. @tparam AllocatorType type of the allocator to use (`std::allocator` by
  15334. default)
  15335. @tparam JSONSerializer the serializer to resolve internal calls to `to_json()`
  15336. and `from_json()` (@ref adl_serializer by default)
  15337. @requirement The class satisfies the following concept requirements:
  15338. - Basic
  15339. - [DefaultConstructible](https://en.cppreference.com/w/cpp/named_req/DefaultConstructible):
  15340. JSON values can be default constructed. The result will be a JSON null
  15341. value.
  15342. - [MoveConstructible](https://en.cppreference.com/w/cpp/named_req/MoveConstructible):
  15343. A JSON value can be constructed from an rvalue argument.
  15344. - [CopyConstructible](https://en.cppreference.com/w/cpp/named_req/CopyConstructible):
  15345. A JSON value can be copy-constructed from an lvalue expression.
  15346. - [MoveAssignable](https://en.cppreference.com/w/cpp/named_req/MoveAssignable):
  15347. A JSON value van be assigned from an rvalue argument.
  15348. - [CopyAssignable](https://en.cppreference.com/w/cpp/named_req/CopyAssignable):
  15349. A JSON value can be copy-assigned from an lvalue expression.
  15350. - [Destructible](https://en.cppreference.com/w/cpp/named_req/Destructible):
  15351. JSON values can be destructed.
  15352. - Layout
  15353. - [StandardLayoutType](https://en.cppreference.com/w/cpp/named_req/StandardLayoutType):
  15354. JSON values have
  15355. [standard layout](https://en.cppreference.com/w/cpp/language/data_members#Standard_layout):
  15356. All non-static data members are private and standard layout types, the
  15357. class has no virtual functions or (virtual) base classes.
  15358. - Library-wide
  15359. - [EqualityComparable](https://en.cppreference.com/w/cpp/named_req/EqualityComparable):
  15360. JSON values can be compared with `==`, see @ref
  15361. operator==(const_reference,const_reference).
  15362. - [LessThanComparable](https://en.cppreference.com/w/cpp/named_req/LessThanComparable):
  15363. JSON values can be compared with `<`, see @ref
  15364. operator<(const_reference,const_reference).
  15365. - [Swappable](https://en.cppreference.com/w/cpp/named_req/Swappable):
  15366. Any JSON lvalue or rvalue of can be swapped with any lvalue or rvalue of
  15367. other compatible types, using unqualified function call @ref swap().
  15368. - [NullablePointer](https://en.cppreference.com/w/cpp/named_req/NullablePointer):
  15369. JSON values can be compared against `std::nullptr_t` objects which are used
  15370. to model the `null` value.
  15371. - Container
  15372. - [Container](https://en.cppreference.com/w/cpp/named_req/Container):
  15373. JSON values can be used like STL containers and provide iterator access.
  15374. - [ReversibleContainer](https://en.cppreference.com/w/cpp/named_req/ReversibleContainer);
  15375. JSON values can be used like STL containers and provide reverse iterator
  15376. access.
  15377. @invariant The member variables @a m_value and @a m_type have the following
  15378. relationship:
  15379. - If `m_type == value_t::object`, then `m_value.object != nullptr`.
  15380. - If `m_type == value_t::array`, then `m_value.array != nullptr`.
  15381. - If `m_type == value_t::string`, then `m_value.string != nullptr`.
  15382. The invariants are checked by member function assert_invariant().
  15383. @internal
  15384. @note ObjectType trick from https://stackoverflow.com/a/9860911
  15385. @endinternal
  15386. @see [RFC 8259: The JavaScript Object Notation (JSON) Data Interchange
  15387. Format](https://tools.ietf.org/html/rfc8259)
  15388. @since version 1.0.0
  15389. @nosubgrouping
  15390. */
  15391. NLOHMANN_BASIC_JSON_TPL_DECLARATION
  15392. class basic_json // NOLINT(cppcoreguidelines-special-member-functions,hicpp-special-member-functions)
  15393. {
  15394. private:
  15395. template<detail::value_t> friend struct detail::external_constructor;
  15396. friend ::nlohmann::json_pointer<basic_json>;
  15397. template<typename BasicJsonType, typename InputType>
  15398. friend class ::nlohmann::detail::parser;
  15399. friend ::nlohmann::detail::serializer<basic_json>;
  15400. template<typename BasicJsonType>
  15401. friend class ::nlohmann::detail::iter_impl;
  15402. template<typename BasicJsonType, typename CharType>
  15403. friend class ::nlohmann::detail::binary_writer;
  15404. template<typename BasicJsonType, typename InputType, typename SAX>
  15405. friend class ::nlohmann::detail::binary_reader;
  15406. template<typename BasicJsonType>
  15407. friend class ::nlohmann::detail::json_sax_dom_parser;
  15408. template<typename BasicJsonType>
  15409. friend class ::nlohmann::detail::json_sax_dom_callback_parser;
  15410. friend class ::nlohmann::detail::exception;
  15411. /// workaround type for MSVC
  15412. using basic_json_t = NLOHMANN_BASIC_JSON_TPL;
  15413. JSON_PRIVATE_UNLESS_TESTED:
  15414. // convenience aliases for types residing in namespace detail;
  15415. using lexer = ::nlohmann::detail::lexer_base<basic_json>;
  15416. template<typename InputAdapterType>
  15417. static ::nlohmann::detail::parser<basic_json, InputAdapterType> parser(
  15418. InputAdapterType adapter,
  15419. detail::parser_callback_t<basic_json>cb = nullptr,
  15420. const bool allow_exceptions = true,
  15421. const bool ignore_comments = false
  15422. )
  15423. {
  15424. return ::nlohmann::detail::parser<basic_json, InputAdapterType>(std::move(adapter),
  15425. std::move(cb), allow_exceptions, ignore_comments);
  15426. }
  15427. private:
  15428. using primitive_iterator_t = ::nlohmann::detail::primitive_iterator_t;
  15429. template<typename BasicJsonType>
  15430. using internal_iterator = ::nlohmann::detail::internal_iterator<BasicJsonType>;
  15431. template<typename BasicJsonType>
  15432. using iter_impl = ::nlohmann::detail::iter_impl<BasicJsonType>;
  15433. template<typename Iterator>
  15434. using iteration_proxy = ::nlohmann::detail::iteration_proxy<Iterator>;
  15435. template<typename Base> using json_reverse_iterator = ::nlohmann::detail::json_reverse_iterator<Base>;
  15436. template<typename CharType>
  15437. using output_adapter_t = ::nlohmann::detail::output_adapter_t<CharType>;
  15438. template<typename InputType>
  15439. using binary_reader = ::nlohmann::detail::binary_reader<basic_json, InputType>;
  15440. template<typename CharType> using binary_writer = ::nlohmann::detail::binary_writer<basic_json, CharType>;
  15441. JSON_PRIVATE_UNLESS_TESTED:
  15442. using serializer = ::nlohmann::detail::serializer<basic_json>;
  15443. public:
  15444. using value_t = detail::value_t;
  15445. /// JSON Pointer, see @ref nlohmann::json_pointer
  15446. using json_pointer = ::nlohmann::json_pointer<basic_json>;
  15447. template<typename T, typename SFINAE>
  15448. using json_serializer = JSONSerializer<T, SFINAE>;
  15449. /// how to treat decoding errors
  15450. using error_handler_t = detail::error_handler_t;
  15451. /// how to treat CBOR tags
  15452. using cbor_tag_handler_t = detail::cbor_tag_handler_t;
  15453. /// helper type for initializer lists of basic_json values
  15454. using initializer_list_t = std::initializer_list<detail::json_ref<basic_json>>;
  15455. using input_format_t = detail::input_format_t;
  15456. /// SAX interface type, see @ref nlohmann::json_sax
  15457. using json_sax_t = json_sax<basic_json>;
  15458. ////////////////
  15459. // exceptions //
  15460. ////////////////
  15461. /// @name exceptions
  15462. /// Classes to implement user-defined exceptions.
  15463. /// @{
  15464. /// @copydoc detail::exception
  15465. using exception = detail::exception;
  15466. /// @copydoc detail::parse_error
  15467. using parse_error = detail::parse_error;
  15468. /// @copydoc detail::invalid_iterator
  15469. using invalid_iterator = detail::invalid_iterator;
  15470. /// @copydoc detail::type_error
  15471. using type_error = detail::type_error;
  15472. /// @copydoc detail::out_of_range
  15473. using out_of_range = detail::out_of_range;
  15474. /// @copydoc detail::other_error
  15475. using other_error = detail::other_error;
  15476. /// @}
  15477. /////////////////////
  15478. // container types //
  15479. /////////////////////
  15480. /// @name container types
  15481. /// The canonic container types to use @ref basic_json like any other STL
  15482. /// container.
  15483. /// @{
  15484. /// the type of elements in a basic_json container
  15485. using value_type = basic_json;
  15486. /// the type of an element reference
  15487. using reference = value_type&;
  15488. /// the type of an element const reference
  15489. using const_reference = const value_type&;
  15490. /// a type to represent differences between iterators
  15491. using difference_type = std::ptrdiff_t;
  15492. /// a type to represent container sizes
  15493. using size_type = std::size_t;
  15494. /// the allocator type
  15495. using allocator_type = AllocatorType<basic_json>;
  15496. /// the type of an element pointer
  15497. using pointer = typename std::allocator_traits<allocator_type>::pointer;
  15498. /// the type of an element const pointer
  15499. using const_pointer = typename std::allocator_traits<allocator_type>::const_pointer;
  15500. /// an iterator for a basic_json container
  15501. using iterator = iter_impl<basic_json>;
  15502. /// a const iterator for a basic_json container
  15503. using const_iterator = iter_impl<const basic_json>;
  15504. /// a reverse iterator for a basic_json container
  15505. using reverse_iterator = json_reverse_iterator<typename basic_json::iterator>;
  15506. /// a const reverse iterator for a basic_json container
  15507. using const_reverse_iterator = json_reverse_iterator<typename basic_json::const_iterator>;
  15508. /// @}
  15509. /*!
  15510. @brief returns the allocator associated with the container
  15511. */
  15512. static allocator_type get_allocator()
  15513. {
  15514. return allocator_type();
  15515. }
  15516. /*!
  15517. @brief returns version information on the library
  15518. This function returns a JSON object with information about the library,
  15519. including the version number and information on the platform and compiler.
  15520. @return JSON object holding version information
  15521. key | description
  15522. ----------- | ---------------
  15523. `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).
  15524. `copyright` | The copyright line for the library as string.
  15525. `name` | The name of the library as string.
  15526. `platform` | The used platform as string. Possible values are `win32`, `linux`, `apple`, `unix`, and `unknown`.
  15527. `url` | The URL of the project as string.
  15528. `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).
  15529. @liveexample{The following code shows an example output of the `meta()`
  15530. function.,meta}
  15531. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  15532. changes to any JSON value.
  15533. @complexity Constant.
  15534. @since 2.1.0
  15535. */
  15536. JSON_HEDLEY_WARN_UNUSED_RESULT
  15537. static basic_json meta()
  15538. {
  15539. basic_json result;
  15540. result["copyright"] = "(C) 2013-2021 Niels Lohmann";
  15541. result["name"] = "JSON for Modern C++";
  15542. result["url"] = "https://github.com/nlohmann/json";
  15543. result["version"]["string"] =
  15544. std::to_string(NLOHMANN_JSON_VERSION_MAJOR) + "." +
  15545. std::to_string(NLOHMANN_JSON_VERSION_MINOR) + "." +
  15546. std::to_string(NLOHMANN_JSON_VERSION_PATCH);
  15547. result["version"]["major"] = NLOHMANN_JSON_VERSION_MAJOR;
  15548. result["version"]["minor"] = NLOHMANN_JSON_VERSION_MINOR;
  15549. result["version"]["patch"] = NLOHMANN_JSON_VERSION_PATCH;
  15550. #ifdef _WIN32
  15551. result["platform"] = "win32";
  15552. #elif defined __linux__
  15553. result["platform"] = "linux";
  15554. #elif defined __APPLE__
  15555. result["platform"] = "apple";
  15556. #elif defined __unix__
  15557. result["platform"] = "unix";
  15558. #else
  15559. result["platform"] = "unknown";
  15560. #endif
  15561. #if defined(__ICC) || defined(__INTEL_COMPILER)
  15562. result["compiler"] = {{"family", "icc"}, {"version", __INTEL_COMPILER}};
  15563. #elif defined(__clang__)
  15564. result["compiler"] = {{"family", "clang"}, {"version", __clang_version__}};
  15565. #elif defined(__GNUC__) || defined(__GNUG__)
  15566. result["compiler"] = {{"family", "gcc"}, {"version", std::to_string(__GNUC__) + "." + std::to_string(__GNUC_MINOR__) + "." + std::to_string(__GNUC_PATCHLEVEL__)}};
  15567. #elif defined(__HP_cc) || defined(__HP_aCC)
  15568. result["compiler"] = "hp"
  15569. #elif defined(__IBMCPP__)
  15570. result["compiler"] = {{"family", "ilecpp"}, {"version", __IBMCPP__}};
  15571. #elif defined(_MSC_VER)
  15572. result["compiler"] = {{"family", "msvc"}, {"version", _MSC_VER}};
  15573. #elif defined(__PGI)
  15574. result["compiler"] = {{"family", "pgcpp"}, {"version", __PGI}};
  15575. #elif defined(__SUNPRO_CC)
  15576. result["compiler"] = {{"family", "sunpro"}, {"version", __SUNPRO_CC}};
  15577. #else
  15578. result["compiler"] = {{"family", "unknown"}, {"version", "unknown"}};
  15579. #endif
  15580. #ifdef __cplusplus
  15581. result["compiler"]["c++"] = std::to_string(__cplusplus);
  15582. #else
  15583. result["compiler"]["c++"] = "unknown";
  15584. #endif
  15585. return result;
  15586. }
  15587. ///////////////////////////
  15588. // JSON value data types //
  15589. ///////////////////////////
  15590. /// @name JSON value data types
  15591. /// The data types to store a JSON value. These types are derived from
  15592. /// the template arguments passed to class @ref basic_json.
  15593. /// @{
  15594. #if defined(JSON_HAS_CPP_14)
  15595. // Use transparent comparator if possible, combined with perfect forwarding
  15596. // on find() and count() calls prevents unnecessary string construction.
  15597. using object_comparator_t = std::less<>;
  15598. #else
  15599. using object_comparator_t = std::less<StringType>;
  15600. #endif
  15601. /*!
  15602. @brief a type for an object
  15603. [RFC 8259](https://tools.ietf.org/html/rfc8259) describes JSON objects as follows:
  15604. > An object is an unordered collection of zero or more name/value pairs,
  15605. > where a name is a string and a value is a string, number, boolean, null,
  15606. > object, or array.
  15607. To store objects in C++, a type is defined by the template parameters
  15608. described below.
  15609. @tparam ObjectType the container to store objects (e.g., `std::map` or
  15610. `std::unordered_map`)
  15611. @tparam StringType the type of the keys or names (e.g., `std::string`).
  15612. The comparison function `std::less<StringType>` is used to order elements
  15613. inside the container.
  15614. @tparam AllocatorType the allocator to use for objects (e.g.,
  15615. `std::allocator`)
  15616. #### Default type
  15617. With the default values for @a ObjectType (`std::map`), @a StringType
  15618. (`std::string`), and @a AllocatorType (`std::allocator`), the default
  15619. value for @a object_t is:
  15620. @code {.cpp}
  15621. std::map<
  15622. std::string, // key_type
  15623. basic_json, // value_type
  15624. std::less<std::string>, // key_compare
  15625. std::allocator<std::pair<const std::string, basic_json>> // allocator_type
  15626. >
  15627. @endcode
  15628. #### Behavior
  15629. The choice of @a object_t influences the behavior of the JSON class. With
  15630. the default type, objects have the following behavior:
  15631. - When all names are unique, objects will be interoperable in the sense
  15632. that all software implementations receiving that object will agree on
  15633. the name-value mappings.
  15634. - When the names within an object are not unique, it is unspecified which
  15635. one of the values for a given key will be chosen. For instance,
  15636. `{"key": 2, "key": 1}` could be equal to either `{"key": 1}` or
  15637. `{"key": 2}`.
  15638. - Internally, name/value pairs are stored in lexicographical order of the
  15639. names. Objects will also be serialized (see @ref dump) in this order.
  15640. For instance, `{"b": 1, "a": 2}` and `{"a": 2, "b": 1}` will be stored
  15641. and serialized as `{"a": 2, "b": 1}`.
  15642. - When comparing objects, the order of the name/value pairs is irrelevant.
  15643. This makes objects interoperable in the sense that they will not be
  15644. affected by these differences. For instance, `{"b": 1, "a": 2}` and
  15645. `{"a": 2, "b": 1}` will be treated as equal.
  15646. #### Limits
  15647. [RFC 8259](https://tools.ietf.org/html/rfc8259) specifies:
  15648. > An implementation may set limits on the maximum depth of nesting.
  15649. In this class, the object's limit of nesting is not explicitly constrained.
  15650. However, a maximum depth of nesting may be introduced by the compiler or
  15651. runtime environment. A theoretical limit can be queried by calling the
  15652. @ref max_size function of a JSON object.
  15653. #### Storage
  15654. Objects are stored as pointers in a @ref basic_json type. That is, for any
  15655. access to object values, a pointer of type `object_t*` must be
  15656. dereferenced.
  15657. @sa see @ref array_t -- type for an array value
  15658. @since version 1.0.0
  15659. @note The order name/value pairs are added to the object is *not*
  15660. preserved by the library. Therefore, iterating an object may return
  15661. name/value pairs in a different order than they were originally stored. In
  15662. fact, keys will be traversed in alphabetical order as `std::map` with
  15663. `std::less` is used by default. Please note this behavior conforms to [RFC
  15664. 8259](https://tools.ietf.org/html/rfc8259), because any order implements the
  15665. specified "unordered" nature of JSON objects.
  15666. */
  15667. using object_t = ObjectType<StringType,
  15668. basic_json,
  15669. object_comparator_t,
  15670. AllocatorType<std::pair<const StringType,
  15671. basic_json>>>;
  15672. /*!
  15673. @brief a type for an array
  15674. [RFC 8259](https://tools.ietf.org/html/rfc8259) describes JSON arrays as follows:
  15675. > An array is an ordered sequence of zero or more values.
  15676. To store objects in C++, a type is defined by the template parameters
  15677. explained below.
  15678. @tparam ArrayType container type to store arrays (e.g., `std::vector` or
  15679. `std::list`)
  15680. @tparam AllocatorType allocator to use for arrays (e.g., `std::allocator`)
  15681. #### Default type
  15682. With the default values for @a ArrayType (`std::vector`) and @a
  15683. AllocatorType (`std::allocator`), the default value for @a array_t is:
  15684. @code {.cpp}
  15685. std::vector<
  15686. basic_json, // value_type
  15687. std::allocator<basic_json> // allocator_type
  15688. >
  15689. @endcode
  15690. #### Limits
  15691. [RFC 8259](https://tools.ietf.org/html/rfc8259) specifies:
  15692. > An implementation may set limits on the maximum depth of nesting.
  15693. In this class, the array's limit of nesting is not explicitly constrained.
  15694. However, a maximum depth of nesting may be introduced by the compiler or
  15695. runtime environment. A theoretical limit can be queried by calling the
  15696. @ref max_size function of a JSON array.
  15697. #### Storage
  15698. Arrays are stored as pointers in a @ref basic_json type. That is, for any
  15699. access to array values, a pointer of type `array_t*` must be dereferenced.
  15700. @sa see @ref object_t -- type for an object value
  15701. @since version 1.0.0
  15702. */
  15703. using array_t = ArrayType<basic_json, AllocatorType<basic_json>>;
  15704. /*!
  15705. @brief a type for a string
  15706. [RFC 8259](https://tools.ietf.org/html/rfc8259) describes JSON strings as follows:
  15707. > A string is a sequence of zero or more Unicode characters.
  15708. To store objects in C++, a type is defined by the template parameter
  15709. described below. Unicode values are split by the JSON class into
  15710. byte-sized characters during deserialization.
  15711. @tparam StringType the container to store strings (e.g., `std::string`).
  15712. Note this container is used for keys/names in objects, see @ref object_t.
  15713. #### Default type
  15714. With the default values for @a StringType (`std::string`), the default
  15715. value for @a string_t is:
  15716. @code {.cpp}
  15717. std::string
  15718. @endcode
  15719. #### Encoding
  15720. Strings are stored in UTF-8 encoding. Therefore, functions like
  15721. `std::string::size()` or `std::string::length()` return the number of
  15722. bytes in the string rather than the number of characters or glyphs.
  15723. #### String comparison
  15724. [RFC 8259](https://tools.ietf.org/html/rfc8259) states:
  15725. > Software implementations are typically required to test names of object
  15726. > members for equality. Implementations that transform the textual
  15727. > representation into sequences of Unicode code units and then perform the
  15728. > comparison numerically, code unit by code unit, are interoperable in the
  15729. > sense that implementations will agree in all cases on equality or
  15730. > inequality of two strings. For example, implementations that compare
  15731. > strings with escaped characters unconverted may incorrectly find that
  15732. > `"a\\b"` and `"a\u005Cb"` are not equal.
  15733. This implementation is interoperable as it does compare strings code unit
  15734. by code unit.
  15735. #### Storage
  15736. String values are stored as pointers in a @ref basic_json type. That is,
  15737. for any access to string values, a pointer of type `string_t*` must be
  15738. dereferenced.
  15739. @since version 1.0.0
  15740. */
  15741. using string_t = StringType;
  15742. /*!
  15743. @brief a type for a boolean
  15744. [RFC 8259](https://tools.ietf.org/html/rfc8259) implicitly describes a boolean as a
  15745. type which differentiates the two literals `true` and `false`.
  15746. To store objects in C++, a type is defined by the template parameter @a
  15747. BooleanType which chooses the type to use.
  15748. #### Default type
  15749. With the default values for @a BooleanType (`bool`), the default value for
  15750. @a boolean_t is:
  15751. @code {.cpp}
  15752. bool
  15753. @endcode
  15754. #### Storage
  15755. Boolean values are stored directly inside a @ref basic_json type.
  15756. @since version 1.0.0
  15757. */
  15758. using boolean_t = BooleanType;
  15759. /*!
  15760. @brief a type for a number (integer)
  15761. [RFC 8259](https://tools.ietf.org/html/rfc8259) describes numbers as follows:
  15762. > The representation of numbers is similar to that used in most
  15763. > programming languages. A number is represented in base 10 using decimal
  15764. > digits. It contains an integer component that may be prefixed with an
  15765. > optional minus sign, which may be followed by a fraction part and/or an
  15766. > exponent part. Leading zeros are not allowed. (...) Numeric values that
  15767. > cannot be represented in the grammar below (such as Infinity and NaN)
  15768. > are not permitted.
  15769. This description includes both integer and floating-point numbers.
  15770. However, C++ allows more precise storage if it is known whether the number
  15771. is a signed integer, an unsigned integer or a floating-point number.
  15772. Therefore, three different types, @ref number_integer_t, @ref
  15773. number_unsigned_t and @ref number_float_t are used.
  15774. To store integer numbers in C++, a type is defined by the template
  15775. parameter @a NumberIntegerType which chooses the type to use.
  15776. #### Default type
  15777. With the default values for @a NumberIntegerType (`int64_t`), the default
  15778. value for @a number_integer_t is:
  15779. @code {.cpp}
  15780. int64_t
  15781. @endcode
  15782. #### Default behavior
  15783. - The restrictions about leading zeros is not enforced in C++. Instead,
  15784. leading zeros in integer literals lead to an interpretation as octal
  15785. number. Internally, the value will be stored as decimal number. For
  15786. instance, the C++ integer literal `010` will be serialized to `8`.
  15787. During deserialization, leading zeros yield an error.
  15788. - Not-a-number (NaN) values will be serialized to `null`.
  15789. #### Limits
  15790. [RFC 8259](https://tools.ietf.org/html/rfc8259) specifies:
  15791. > An implementation may set limits on the range and precision of numbers.
  15792. When the default type is used, the maximal integer number that can be
  15793. stored is `9223372036854775807` (INT64_MAX) and the minimal integer number
  15794. that can be stored is `-9223372036854775808` (INT64_MIN). Integer numbers
  15795. that are out of range will yield over/underflow when used in a
  15796. constructor. During deserialization, too large or small integer numbers
  15797. will be automatically be stored as @ref number_unsigned_t or @ref
  15798. number_float_t.
  15799. [RFC 8259](https://tools.ietf.org/html/rfc8259) further states:
  15800. > Note that when such software is used, numbers that are integers and are
  15801. > in the range \f$[-2^{53}+1, 2^{53}-1]\f$ are interoperable in the sense
  15802. > that implementations will agree exactly on their numeric values.
  15803. As this range is a subrange of the exactly supported range [INT64_MIN,
  15804. INT64_MAX], this class's integer type is interoperable.
  15805. #### Storage
  15806. Integer number values are stored directly inside a @ref basic_json type.
  15807. @sa see @ref number_float_t -- type for number values (floating-point)
  15808. @sa see @ref number_unsigned_t -- type for number values (unsigned integer)
  15809. @since version 1.0.0
  15810. */
  15811. using number_integer_t = NumberIntegerType;
  15812. /*!
  15813. @brief a type for a number (unsigned)
  15814. [RFC 8259](https://tools.ietf.org/html/rfc8259) describes numbers as follows:
  15815. > The representation of numbers is similar to that used in most
  15816. > programming languages. A number is represented in base 10 using decimal
  15817. > digits. It contains an integer component that may be prefixed with an
  15818. > optional minus sign, which may be followed by a fraction part and/or an
  15819. > exponent part. Leading zeros are not allowed. (...) Numeric values that
  15820. > cannot be represented in the grammar below (such as Infinity and NaN)
  15821. > are not permitted.
  15822. This description includes both integer and floating-point numbers.
  15823. However, C++ allows more precise storage if it is known whether the number
  15824. is a signed integer, an unsigned integer or a floating-point number.
  15825. Therefore, three different types, @ref number_integer_t, @ref
  15826. number_unsigned_t and @ref number_float_t are used.
  15827. To store unsigned integer numbers in C++, a type is defined by the
  15828. template parameter @a NumberUnsignedType which chooses the type to use.
  15829. #### Default type
  15830. With the default values for @a NumberUnsignedType (`uint64_t`), the
  15831. default value for @a number_unsigned_t is:
  15832. @code {.cpp}
  15833. uint64_t
  15834. @endcode
  15835. #### Default behavior
  15836. - The restrictions about leading zeros is not enforced in C++. Instead,
  15837. leading zeros in integer literals lead to an interpretation as octal
  15838. number. Internally, the value will be stored as decimal number. For
  15839. instance, the C++ integer literal `010` will be serialized to `8`.
  15840. During deserialization, leading zeros yield an error.
  15841. - Not-a-number (NaN) values will be serialized to `null`.
  15842. #### Limits
  15843. [RFC 8259](https://tools.ietf.org/html/rfc8259) specifies:
  15844. > An implementation may set limits on the range and precision of numbers.
  15845. When the default type is used, the maximal integer number that can be
  15846. stored is `18446744073709551615` (UINT64_MAX) and the minimal integer
  15847. number that can be stored is `0`. Integer numbers that are out of range
  15848. will yield over/underflow when used in a constructor. During
  15849. deserialization, too large or small integer numbers will be automatically
  15850. be stored as @ref number_integer_t or @ref number_float_t.
  15851. [RFC 8259](https://tools.ietf.org/html/rfc8259) further states:
  15852. > Note that when such software is used, numbers that are integers and are
  15853. > in the range \f$[-2^{53}+1, 2^{53}-1]\f$ are interoperable in the sense
  15854. > that implementations will agree exactly on their numeric values.
  15855. As this range is a subrange (when considered in conjunction with the
  15856. number_integer_t type) of the exactly supported range [0, UINT64_MAX],
  15857. this class's integer type is interoperable.
  15858. #### Storage
  15859. Integer number values are stored directly inside a @ref basic_json type.
  15860. @sa see @ref number_float_t -- type for number values (floating-point)
  15861. @sa see @ref number_integer_t -- type for number values (integer)
  15862. @since version 2.0.0
  15863. */
  15864. using number_unsigned_t = NumberUnsignedType;
  15865. /*!
  15866. @brief a type for a number (floating-point)
  15867. [RFC 8259](https://tools.ietf.org/html/rfc8259) describes numbers as follows:
  15868. > The representation of numbers is similar to that used in most
  15869. > programming languages. A number is represented in base 10 using decimal
  15870. > digits. It contains an integer component that may be prefixed with an
  15871. > optional minus sign, which may be followed by a fraction part and/or an
  15872. > exponent part. Leading zeros are not allowed. (...) Numeric values that
  15873. > cannot be represented in the grammar below (such as Infinity and NaN)
  15874. > are not permitted.
  15875. This description includes both integer and floating-point numbers.
  15876. However, C++ allows more precise storage if it is known whether the number
  15877. is a signed integer, an unsigned integer or a floating-point number.
  15878. Therefore, three different types, @ref number_integer_t, @ref
  15879. number_unsigned_t and @ref number_float_t are used.
  15880. To store floating-point numbers in C++, a type is defined by the template
  15881. parameter @a NumberFloatType which chooses the type to use.
  15882. #### Default type
  15883. With the default values for @a NumberFloatType (`double`), the default
  15884. value for @a number_float_t is:
  15885. @code {.cpp}
  15886. double
  15887. @endcode
  15888. #### Default behavior
  15889. - The restrictions about leading zeros is not enforced in C++. Instead,
  15890. leading zeros in floating-point literals will be ignored. Internally,
  15891. the value will be stored as decimal number. For instance, the C++
  15892. floating-point literal `01.2` will be serialized to `1.2`. During
  15893. deserialization, leading zeros yield an error.
  15894. - Not-a-number (NaN) values will be serialized to `null`.
  15895. #### Limits
  15896. [RFC 8259](https://tools.ietf.org/html/rfc8259) states:
  15897. > This specification allows implementations to set limits on the range and
  15898. > precision of numbers accepted. Since software that implements IEEE
  15899. > 754-2008 binary64 (double precision) numbers is generally available and
  15900. > widely used, good interoperability can be achieved by implementations
  15901. > that expect no more precision or range than these provide, in the sense
  15902. > that implementations will approximate JSON numbers within the expected
  15903. > precision.
  15904. This implementation does exactly follow this approach, as it uses double
  15905. precision floating-point numbers. Note values smaller than
  15906. `-1.79769313486232e+308` and values greater than `1.79769313486232e+308`
  15907. will be stored as NaN internally and be serialized to `null`.
  15908. #### Storage
  15909. Floating-point number values are stored directly inside a @ref basic_json
  15910. type.
  15911. @sa see @ref number_integer_t -- type for number values (integer)
  15912. @sa see @ref number_unsigned_t -- type for number values (unsigned integer)
  15913. @since version 1.0.0
  15914. */
  15915. using number_float_t = NumberFloatType;
  15916. /*!
  15917. @brief a type for a packed binary type
  15918. This type is a type designed to carry binary data that appears in various
  15919. serialized formats, such as CBOR's Major Type 2, MessagePack's bin, and
  15920. BSON's generic binary subtype. This type is NOT a part of standard JSON and
  15921. exists solely for compatibility with these binary types. As such, it is
  15922. simply defined as an ordered sequence of zero or more byte values.
  15923. Additionally, as an implementation detail, the subtype of the binary data is
  15924. carried around as a `std::uint8_t`, which is compatible with both of the
  15925. binary data formats that use binary subtyping, (though the specific
  15926. numbering is incompatible with each other, and it is up to the user to
  15927. translate between them).
  15928. [CBOR's RFC 7049](https://tools.ietf.org/html/rfc7049) describes this type
  15929. as:
  15930. > Major type 2: a byte string. The string's length in bytes is represented
  15931. > following the rules for positive integers (major type 0).
  15932. [MessagePack's documentation on the bin type
  15933. family](https://github.com/msgpack/msgpack/blob/master/spec.md#bin-format-family)
  15934. describes this type as:
  15935. > Bin format family stores an byte array in 2, 3, or 5 bytes of extra bytes
  15936. > in addition to the size of the byte array.
  15937. [BSON's specifications](http://bsonspec.org/spec.html) describe several
  15938. binary types; however, this type is intended to represent the generic binary
  15939. type which has the description:
  15940. > Generic binary subtype - This is the most commonly used binary subtype and
  15941. > should be the 'default' for drivers and tools.
  15942. None of these impose any limitations on the internal representation other
  15943. than the basic unit of storage be some type of array whose parts are
  15944. decomposable into bytes.
  15945. The default representation of this binary format is a
  15946. `std::vector<std::uint8_t>`, which is a very common way to represent a byte
  15947. array in modern C++.
  15948. #### Default type
  15949. The default values for @a BinaryType is `std::vector<std::uint8_t>`
  15950. #### Storage
  15951. Binary Arrays are stored as pointers in a @ref basic_json type. That is,
  15952. for any access to array values, a pointer of the type `binary_t*` must be
  15953. dereferenced.
  15954. #### Notes on subtypes
  15955. - CBOR
  15956. - Binary values are represented as byte strings. Subtypes are serialized
  15957. as tagged values.
  15958. - MessagePack
  15959. - If a subtype is given and the binary array contains exactly 1, 2, 4, 8,
  15960. or 16 elements, the fixext family (fixext1, fixext2, fixext4, fixext8)
  15961. is used. For other sizes, the ext family (ext8, ext16, ext32) is used.
  15962. The subtype is then added as singed 8-bit integer.
  15963. - If no subtype is given, the bin family (bin8, bin16, bin32) is used.
  15964. - BSON
  15965. - If a subtype is given, it is used and added as unsigned 8-bit integer.
  15966. - If no subtype is given, the generic binary subtype 0x00 is used.
  15967. @sa see @ref binary -- create a binary array
  15968. @since version 3.8.0
  15969. */
  15970. using binary_t = nlohmann::byte_container_with_subtype<BinaryType>;
  15971. /// @}
  15972. private:
  15973. /// helper for exception-safe object creation
  15974. template<typename T, typename... Args>
  15975. JSON_HEDLEY_RETURNS_NON_NULL
  15976. static T* create(Args&& ... args)
  15977. {
  15978. AllocatorType<T> alloc;
  15979. using AllocatorTraits = std::allocator_traits<AllocatorType<T>>;
  15980. auto deleter = [&](T * obj)
  15981. {
  15982. AllocatorTraits::deallocate(alloc, obj, 1);
  15983. };
  15984. std::unique_ptr<T, decltype(deleter)> obj(AllocatorTraits::allocate(alloc, 1), deleter);
  15985. AllocatorTraits::construct(alloc, obj.get(), std::forward<Args>(args)...);
  15986. JSON_ASSERT(obj != nullptr);
  15987. return obj.release();
  15988. }
  15989. ////////////////////////
  15990. // JSON value storage //
  15991. ////////////////////////
  15992. JSON_PRIVATE_UNLESS_TESTED:
  15993. /*!
  15994. @brief a JSON value
  15995. The actual storage for a JSON value of the @ref basic_json class. This
  15996. union combines the different storage types for the JSON value types
  15997. defined in @ref value_t.
  15998. JSON type | value_t type | used type
  15999. --------- | --------------- | ------------------------
  16000. object | object | pointer to @ref object_t
  16001. array | array | pointer to @ref array_t
  16002. string | string | pointer to @ref string_t
  16003. boolean | boolean | @ref boolean_t
  16004. number | number_integer | @ref number_integer_t
  16005. number | number_unsigned | @ref number_unsigned_t
  16006. number | number_float | @ref number_float_t
  16007. binary | binary | pointer to @ref binary_t
  16008. null | null | *no value is stored*
  16009. @note Variable-length types (objects, arrays, and strings) are stored as
  16010. pointers. The size of the union should not exceed 64 bits if the default
  16011. value types are used.
  16012. @since version 1.0.0
  16013. */
  16014. union json_value
  16015. {
  16016. /// object (stored with pointer to save storage)
  16017. object_t* object;
  16018. /// array (stored with pointer to save storage)
  16019. array_t* array;
  16020. /// string (stored with pointer to save storage)
  16021. string_t* string;
  16022. /// binary (stored with pointer to save storage)
  16023. binary_t* binary;
  16024. /// boolean
  16025. boolean_t boolean;
  16026. /// number (integer)
  16027. number_integer_t number_integer;
  16028. /// number (unsigned integer)
  16029. number_unsigned_t number_unsigned;
  16030. /// number (floating-point)
  16031. number_float_t number_float;
  16032. /// default constructor (for null values)
  16033. json_value() = default;
  16034. /// constructor for booleans
  16035. json_value(boolean_t v) noexcept : boolean(v) {}
  16036. /// constructor for numbers (integer)
  16037. json_value(number_integer_t v) noexcept : number_integer(v) {}
  16038. /// constructor for numbers (unsigned)
  16039. json_value(number_unsigned_t v) noexcept : number_unsigned(v) {}
  16040. /// constructor for numbers (floating-point)
  16041. json_value(number_float_t v) noexcept : number_float(v) {}
  16042. /// constructor for empty values of a given type
  16043. json_value(value_t t)
  16044. {
  16045. switch (t)
  16046. {
  16047. case value_t::object:
  16048. {
  16049. object = create<object_t>();
  16050. break;
  16051. }
  16052. case value_t::array:
  16053. {
  16054. array = create<array_t>();
  16055. break;
  16056. }
  16057. case value_t::string:
  16058. {
  16059. string = create<string_t>("");
  16060. break;
  16061. }
  16062. case value_t::binary:
  16063. {
  16064. binary = create<binary_t>();
  16065. break;
  16066. }
  16067. case value_t::boolean:
  16068. {
  16069. boolean = boolean_t(false);
  16070. break;
  16071. }
  16072. case value_t::number_integer:
  16073. {
  16074. number_integer = number_integer_t(0);
  16075. break;
  16076. }
  16077. case value_t::number_unsigned:
  16078. {
  16079. number_unsigned = number_unsigned_t(0);
  16080. break;
  16081. }
  16082. case value_t::number_float:
  16083. {
  16084. number_float = number_float_t(0.0);
  16085. break;
  16086. }
  16087. case value_t::null:
  16088. {
  16089. object = nullptr; // silence warning, see #821
  16090. break;
  16091. }
  16092. case value_t::discarded:
  16093. default:
  16094. {
  16095. object = nullptr; // silence warning, see #821
  16096. if (JSON_HEDLEY_UNLIKELY(t == value_t::null))
  16097. {
  16098. JSON_THROW(other_error::create(500, "961c151d2e87f2686a955a9be24d316f1362bf21 3.10.4", basic_json())); // LCOV_EXCL_LINE
  16099. }
  16100. break;
  16101. }
  16102. }
  16103. }
  16104. /// constructor for strings
  16105. json_value(const string_t& value)
  16106. {
  16107. string = create<string_t>(value);
  16108. }
  16109. /// constructor for rvalue strings
  16110. json_value(string_t&& value)
  16111. {
  16112. string = create<string_t>(std::move(value));
  16113. }
  16114. /// constructor for objects
  16115. json_value(const object_t& value)
  16116. {
  16117. object = create<object_t>(value);
  16118. }
  16119. /// constructor for rvalue objects
  16120. json_value(object_t&& value)
  16121. {
  16122. object = create<object_t>(std::move(value));
  16123. }
  16124. /// constructor for arrays
  16125. json_value(const array_t& value)
  16126. {
  16127. array = create<array_t>(value);
  16128. }
  16129. /// constructor for rvalue arrays
  16130. json_value(array_t&& value)
  16131. {
  16132. array = create<array_t>(std::move(value));
  16133. }
  16134. /// constructor for binary arrays
  16135. json_value(const typename binary_t::container_type& value)
  16136. {
  16137. binary = create<binary_t>(value);
  16138. }
  16139. /// constructor for rvalue binary arrays
  16140. json_value(typename binary_t::container_type&& value)
  16141. {
  16142. binary = create<binary_t>(std::move(value));
  16143. }
  16144. /// constructor for binary arrays (internal type)
  16145. json_value(const binary_t& value)
  16146. {
  16147. binary = create<binary_t>(value);
  16148. }
  16149. /// constructor for rvalue binary arrays (internal type)
  16150. json_value(binary_t&& value)
  16151. {
  16152. binary = create<binary_t>(std::move(value));
  16153. }
  16154. void destroy(value_t t)
  16155. {
  16156. if (t == value_t::array || t == value_t::object)
  16157. {
  16158. // flatten the current json_value to a heap-allocated stack
  16159. std::vector<basic_json> stack;
  16160. // move the top-level items to stack
  16161. if (t == value_t::array)
  16162. {
  16163. stack.reserve(array->size());
  16164. std::move(array->begin(), array->end(), std::back_inserter(stack));
  16165. }
  16166. else
  16167. {
  16168. stack.reserve(object->size());
  16169. for (auto&& it : *object)
  16170. {
  16171. stack.push_back(std::move(it.second));
  16172. }
  16173. }
  16174. while (!stack.empty())
  16175. {
  16176. // move the last item to local variable to be processed
  16177. basic_json current_item(std::move(stack.back()));
  16178. stack.pop_back();
  16179. // if current_item is array/object, move
  16180. // its children to the stack to be processed later
  16181. if (current_item.is_array())
  16182. {
  16183. std::move(current_item.m_value.array->begin(), current_item.m_value.array->end(), std::back_inserter(stack));
  16184. current_item.m_value.array->clear();
  16185. }
  16186. else if (current_item.is_object())
  16187. {
  16188. for (auto&& it : *current_item.m_value.object)
  16189. {
  16190. stack.push_back(std::move(it.second));
  16191. }
  16192. current_item.m_value.object->clear();
  16193. }
  16194. // it's now safe that current_item get destructed
  16195. // since it doesn't have any children
  16196. }
  16197. }
  16198. switch (t)
  16199. {
  16200. case value_t::object:
  16201. {
  16202. AllocatorType<object_t> alloc;
  16203. std::allocator_traits<decltype(alloc)>::destroy(alloc, object);
  16204. std::allocator_traits<decltype(alloc)>::deallocate(alloc, object, 1);
  16205. break;
  16206. }
  16207. case value_t::array:
  16208. {
  16209. AllocatorType<array_t> alloc;
  16210. std::allocator_traits<decltype(alloc)>::destroy(alloc, array);
  16211. std::allocator_traits<decltype(alloc)>::deallocate(alloc, array, 1);
  16212. break;
  16213. }
  16214. case value_t::string:
  16215. {
  16216. AllocatorType<string_t> alloc;
  16217. std::allocator_traits<decltype(alloc)>::destroy(alloc, string);
  16218. std::allocator_traits<decltype(alloc)>::deallocate(alloc, string, 1);
  16219. break;
  16220. }
  16221. case value_t::binary:
  16222. {
  16223. AllocatorType<binary_t> alloc;
  16224. std::allocator_traits<decltype(alloc)>::destroy(alloc, binary);
  16225. std::allocator_traits<decltype(alloc)>::deallocate(alloc, binary, 1);
  16226. break;
  16227. }
  16228. case value_t::null:
  16229. case value_t::boolean:
  16230. case value_t::number_integer:
  16231. case value_t::number_unsigned:
  16232. case value_t::number_float:
  16233. case value_t::discarded:
  16234. default:
  16235. {
  16236. break;
  16237. }
  16238. }
  16239. }
  16240. };
  16241. private:
  16242. /*!
  16243. @brief checks the class invariants
  16244. This function asserts the class invariants. It needs to be called at the
  16245. end of every constructor to make sure that created objects respect the
  16246. invariant. Furthermore, it has to be called each time the type of a JSON
  16247. value is changed, because the invariant expresses a relationship between
  16248. @a m_type and @a m_value.
  16249. Furthermore, the parent relation is checked for arrays and objects: If
  16250. @a check_parents true and the value is an array or object, then the
  16251. container's elements must have the current value as parent.
  16252. @param[in] check_parents whether the parent relation should be checked.
  16253. The value is true by default and should only be set to false
  16254. during destruction of objects when the invariant does not
  16255. need to hold.
  16256. */
  16257. void assert_invariant(bool check_parents = true) const noexcept
  16258. {
  16259. JSON_ASSERT(m_type != value_t::object || m_value.object != nullptr);
  16260. JSON_ASSERT(m_type != value_t::array || m_value.array != nullptr);
  16261. JSON_ASSERT(m_type != value_t::string || m_value.string != nullptr);
  16262. JSON_ASSERT(m_type != value_t::binary || m_value.binary != nullptr);
  16263. #if JSON_DIAGNOSTICS
  16264. JSON_TRY
  16265. {
  16266. // cppcheck-suppress assertWithSideEffect
  16267. JSON_ASSERT(!check_parents || !is_structured() || std::all_of(begin(), end(), [this](const basic_json & j)
  16268. {
  16269. return j.m_parent == this;
  16270. }));
  16271. }
  16272. JSON_CATCH(...) {} // LCOV_EXCL_LINE
  16273. #endif
  16274. static_cast<void>(check_parents);
  16275. }
  16276. void set_parents()
  16277. {
  16278. #if JSON_DIAGNOSTICS
  16279. switch (m_type)
  16280. {
  16281. case value_t::array:
  16282. {
  16283. for (auto& element : *m_value.array)
  16284. {
  16285. element.m_parent = this;
  16286. }
  16287. break;
  16288. }
  16289. case value_t::object:
  16290. {
  16291. for (auto& element : *m_value.object)
  16292. {
  16293. element.second.m_parent = this;
  16294. }
  16295. break;
  16296. }
  16297. case value_t::null:
  16298. case value_t::string:
  16299. case value_t::boolean:
  16300. case value_t::number_integer:
  16301. case value_t::number_unsigned:
  16302. case value_t::number_float:
  16303. case value_t::binary:
  16304. case value_t::discarded:
  16305. default:
  16306. break;
  16307. }
  16308. #endif
  16309. }
  16310. iterator set_parents(iterator it, typename iterator::difference_type count)
  16311. {
  16312. #if JSON_DIAGNOSTICS
  16313. for (typename iterator::difference_type i = 0; i < count; ++i)
  16314. {
  16315. (it + i)->m_parent = this;
  16316. }
  16317. #else
  16318. static_cast<void>(count);
  16319. #endif
  16320. return it;
  16321. }
  16322. reference set_parent(reference j, std::size_t old_capacity = std::size_t(-1))
  16323. {
  16324. #if JSON_DIAGNOSTICS
  16325. if (old_capacity != std::size_t(-1))
  16326. {
  16327. // see https://github.com/nlohmann/json/issues/2838
  16328. JSON_ASSERT(type() == value_t::array);
  16329. if (JSON_HEDLEY_UNLIKELY(m_value.array->capacity() != old_capacity))
  16330. {
  16331. // capacity has changed: update all parents
  16332. set_parents();
  16333. return j;
  16334. }
  16335. }
  16336. // ordered_json uses a vector internally, so pointers could have
  16337. // been invalidated; see https://github.com/nlohmann/json/issues/2962
  16338. #ifdef JSON_HEDLEY_MSVC_VERSION
  16339. #pragma warning(push )
  16340. #pragma warning(disable : 4127) // ignore warning to replace if with if constexpr
  16341. #endif
  16342. if (detail::is_ordered_map<object_t>::value)
  16343. {
  16344. set_parents();
  16345. return j;
  16346. }
  16347. #ifdef JSON_HEDLEY_MSVC_VERSION
  16348. #pragma warning( pop )
  16349. #endif
  16350. j.m_parent = this;
  16351. #else
  16352. static_cast<void>(j);
  16353. static_cast<void>(old_capacity);
  16354. #endif
  16355. return j;
  16356. }
  16357. public:
  16358. //////////////////////////
  16359. // JSON parser callback //
  16360. //////////////////////////
  16361. /*!
  16362. @brief parser event types
  16363. The parser callback distinguishes the following events:
  16364. - `object_start`: the parser read `{` and started to process a JSON object
  16365. - `key`: the parser read a key of a value in an object
  16366. - `object_end`: the parser read `}` and finished processing a JSON object
  16367. - `array_start`: the parser read `[` and started to process a JSON array
  16368. - `array_end`: the parser read `]` and finished processing a JSON array
  16369. - `value`: the parser finished reading a JSON value
  16370. @image html callback_events.png "Example when certain parse events are triggered"
  16371. @sa see @ref parser_callback_t for more information and examples
  16372. */
  16373. using parse_event_t = detail::parse_event_t;
  16374. /*!
  16375. @brief per-element parser callback type
  16376. With a parser callback function, the result of parsing a JSON text can be
  16377. influenced. When passed to @ref parse, it is called on certain events
  16378. (passed as @ref parse_event_t via parameter @a event) with a set recursion
  16379. depth @a depth and context JSON value @a parsed. The return value of the
  16380. callback function is a boolean indicating whether the element that emitted
  16381. the callback shall be kept or not.
  16382. We distinguish six scenarios (determined by the event type) in which the
  16383. callback function can be called. The following table describes the values
  16384. of the parameters @a depth, @a event, and @a parsed.
  16385. parameter @a event | description | parameter @a depth | parameter @a parsed
  16386. ------------------ | ----------- | ------------------ | -------------------
  16387. 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
  16388. 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
  16389. 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
  16390. 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
  16391. 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
  16392. parse_event_t::value | the parser finished reading a JSON value | depth of the value | the parsed JSON value
  16393. @image html callback_events.png "Example when certain parse events are triggered"
  16394. Discarding a value (i.e., returning `false`) has different effects
  16395. depending on the context in which function was called:
  16396. - Discarded values in structured types are skipped. That is, the parser
  16397. will behave as if the discarded value was never read.
  16398. - In case a value outside a structured type is skipped, it is replaced
  16399. with `null`. This case happens if the top-level element is skipped.
  16400. @param[in] depth the depth of the recursion during parsing
  16401. @param[in] event an event of type parse_event_t indicating the context in
  16402. the callback function has been called
  16403. @param[in,out] parsed the current intermediate parse result; note that
  16404. writing to this value has no effect for parse_event_t::key events
  16405. @return Whether the JSON value which called the function during parsing
  16406. should be kept (`true`) or not (`false`). In the latter case, it is either
  16407. skipped completely or replaced by an empty discarded object.
  16408. @sa see @ref parse for examples
  16409. @since version 1.0.0
  16410. */
  16411. using parser_callback_t = detail::parser_callback_t<basic_json>;
  16412. //////////////////
  16413. // constructors //
  16414. //////////////////
  16415. /// @name constructors and destructors
  16416. /// Constructors of class @ref basic_json, copy/move constructor, copy
  16417. /// assignment, static functions creating objects, and the destructor.
  16418. /// @{
  16419. /*!
  16420. @brief create an empty value with a given type
  16421. Create an empty JSON value with a given type. The value will be default
  16422. initialized with an empty value which depends on the type:
  16423. Value type | initial value
  16424. ----------- | -------------
  16425. null | `null`
  16426. boolean | `false`
  16427. string | `""`
  16428. number | `0`
  16429. object | `{}`
  16430. array | `[]`
  16431. binary | empty array
  16432. @param[in] v the type of the value to create
  16433. @complexity Constant.
  16434. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  16435. changes to any JSON value.
  16436. @liveexample{The following code shows the constructor for different @ref
  16437. value_t values,basic_json__value_t}
  16438. @sa see @ref clear() -- restores the postcondition of this constructor
  16439. @since version 1.0.0
  16440. */
  16441. basic_json(const value_t v)
  16442. : m_type(v), m_value(v)
  16443. {
  16444. assert_invariant();
  16445. }
  16446. /*!
  16447. @brief create a null object
  16448. Create a `null` JSON value. It either takes a null pointer as parameter
  16449. (explicitly creating `null`) or no parameter (implicitly creating `null`).
  16450. The passed null pointer itself is not read -- it is only used to choose
  16451. the right constructor.
  16452. @complexity Constant.
  16453. @exceptionsafety No-throw guarantee: this constructor never throws
  16454. exceptions.
  16455. @liveexample{The following code shows the constructor with and without a
  16456. null pointer parameter.,basic_json__nullptr_t}
  16457. @since version 1.0.0
  16458. */
  16459. basic_json(std::nullptr_t = nullptr) noexcept
  16460. : basic_json(value_t::null)
  16461. {
  16462. assert_invariant();
  16463. }
  16464. /*!
  16465. @brief create a JSON value
  16466. This is a "catch all" constructor for all compatible JSON types; that is,
  16467. types for which a `to_json()` method exists. The constructor forwards the
  16468. parameter @a val to that method (to `json_serializer<U>::to_json` method
  16469. with `U = uncvref_t<CompatibleType>`, to be exact).
  16470. Template type @a CompatibleType includes, but is not limited to, the
  16471. following types:
  16472. - **arrays**: @ref array_t and all kinds of compatible containers such as
  16473. `std::vector`, `std::deque`, `std::list`, `std::forward_list`,
  16474. `std::array`, `std::valarray`, `std::set`, `std::unordered_set`,
  16475. `std::multiset`, and `std::unordered_multiset` with a `value_type` from
  16476. which a @ref basic_json value can be constructed.
  16477. - **objects**: @ref object_t and all kinds of compatible associative
  16478. containers such as `std::map`, `std::unordered_map`, `std::multimap`,
  16479. and `std::unordered_multimap` with a `key_type` compatible to
  16480. @ref string_t and a `value_type` from which a @ref basic_json value can
  16481. be constructed.
  16482. - **strings**: @ref string_t, string literals, and all compatible string
  16483. containers can be used.
  16484. - **numbers**: @ref number_integer_t, @ref number_unsigned_t,
  16485. @ref number_float_t, and all convertible number types such as `int`,
  16486. `size_t`, `int64_t`, `float` or `double` can be used.
  16487. - **boolean**: @ref boolean_t / `bool` can be used.
  16488. - **binary**: @ref binary_t / `std::vector<std::uint8_t>` may be used,
  16489. unfortunately because string literals cannot be distinguished from binary
  16490. character arrays by the C++ type system, all types compatible with `const
  16491. char*` will be directed to the string constructor instead. This is both
  16492. for backwards compatibility, and due to the fact that a binary type is not
  16493. a standard JSON type.
  16494. See the examples below.
  16495. @tparam CompatibleType a type such that:
  16496. - @a CompatibleType is not derived from `std::istream`,
  16497. - @a CompatibleType is not @ref basic_json (to avoid hijacking copy/move
  16498. constructors),
  16499. - @a CompatibleType is not a different @ref basic_json type (i.e. with different template arguments)
  16500. - @a CompatibleType is not a @ref basic_json nested type (e.g.,
  16501. @ref json_pointer, @ref iterator, etc ...)
  16502. - `json_serializer<U>` has a `to_json(basic_json_t&, CompatibleType&&)` method
  16503. @tparam U = `uncvref_t<CompatibleType>`
  16504. @param[in] val the value to be forwarded to the respective constructor
  16505. @complexity Usually linear in the size of the passed @a val, also
  16506. depending on the implementation of the called `to_json()`
  16507. method.
  16508. @exceptionsafety Depends on the called constructor. For types directly
  16509. supported by the library (i.e., all types for which no `to_json()` function
  16510. was provided), strong guarantee holds: if an exception is thrown, there are
  16511. no changes to any JSON value.
  16512. @liveexample{The following code shows the constructor with several
  16513. compatible types.,basic_json__CompatibleType}
  16514. @since version 2.1.0
  16515. */
  16516. template < typename CompatibleType,
  16517. typename U = detail::uncvref_t<CompatibleType>,
  16518. detail::enable_if_t <
  16519. !detail::is_basic_json<U>::value && detail::is_compatible_type<basic_json_t, U>::value, int > = 0 >
  16520. basic_json(CompatibleType && val) noexcept(noexcept( // NOLINT(bugprone-forwarding-reference-overload,bugprone-exception-escape)
  16521. JSONSerializer<U>::to_json(std::declval<basic_json_t&>(),
  16522. std::forward<CompatibleType>(val))))
  16523. {
  16524. JSONSerializer<U>::to_json(*this, std::forward<CompatibleType>(val));
  16525. set_parents();
  16526. assert_invariant();
  16527. }
  16528. /*!
  16529. @brief create a JSON value from an existing one
  16530. This is a constructor for existing @ref basic_json types.
  16531. It does not hijack copy/move constructors, since the parameter has different
  16532. template arguments than the current ones.
  16533. The constructor tries to convert the internal @ref m_value of the parameter.
  16534. @tparam BasicJsonType a type such that:
  16535. - @a BasicJsonType is a @ref basic_json type.
  16536. - @a BasicJsonType has different template arguments than @ref basic_json_t.
  16537. @param[in] val the @ref basic_json value to be converted.
  16538. @complexity Usually linear in the size of the passed @a val, also
  16539. depending on the implementation of the called `to_json()`
  16540. method.
  16541. @exceptionsafety Depends on the called constructor. For types directly
  16542. supported by the library (i.e., all types for which no `to_json()` function
  16543. was provided), strong guarantee holds: if an exception is thrown, there are
  16544. no changes to any JSON value.
  16545. @since version 3.2.0
  16546. */
  16547. template < typename BasicJsonType,
  16548. detail::enable_if_t <
  16549. detail::is_basic_json<BasicJsonType>::value&& !std::is_same<basic_json, BasicJsonType>::value, int > = 0 >
  16550. basic_json(const BasicJsonType& val)
  16551. {
  16552. using other_boolean_t = typename BasicJsonType::boolean_t;
  16553. using other_number_float_t = typename BasicJsonType::number_float_t;
  16554. using other_number_integer_t = typename BasicJsonType::number_integer_t;
  16555. using other_number_unsigned_t = typename BasicJsonType::number_unsigned_t;
  16556. using other_string_t = typename BasicJsonType::string_t;
  16557. using other_object_t = typename BasicJsonType::object_t;
  16558. using other_array_t = typename BasicJsonType::array_t;
  16559. using other_binary_t = typename BasicJsonType::binary_t;
  16560. switch (val.type())
  16561. {
  16562. case value_t::boolean:
  16563. JSONSerializer<other_boolean_t>::to_json(*this, val.template get<other_boolean_t>());
  16564. break;
  16565. case value_t::number_float:
  16566. JSONSerializer<other_number_float_t>::to_json(*this, val.template get<other_number_float_t>());
  16567. break;
  16568. case value_t::number_integer:
  16569. JSONSerializer<other_number_integer_t>::to_json(*this, val.template get<other_number_integer_t>());
  16570. break;
  16571. case value_t::number_unsigned:
  16572. JSONSerializer<other_number_unsigned_t>::to_json(*this, val.template get<other_number_unsigned_t>());
  16573. break;
  16574. case value_t::string:
  16575. JSONSerializer<other_string_t>::to_json(*this, val.template get_ref<const other_string_t&>());
  16576. break;
  16577. case value_t::object:
  16578. JSONSerializer<other_object_t>::to_json(*this, val.template get_ref<const other_object_t&>());
  16579. break;
  16580. case value_t::array:
  16581. JSONSerializer<other_array_t>::to_json(*this, val.template get_ref<const other_array_t&>());
  16582. break;
  16583. case value_t::binary:
  16584. JSONSerializer<other_binary_t>::to_json(*this, val.template get_ref<const other_binary_t&>());
  16585. break;
  16586. case value_t::null:
  16587. *this = nullptr;
  16588. break;
  16589. case value_t::discarded:
  16590. m_type = value_t::discarded;
  16591. break;
  16592. default: // LCOV_EXCL_LINE
  16593. JSON_ASSERT(false); // NOLINT(cert-dcl03-c,hicpp-static-assert,misc-static-assert) LCOV_EXCL_LINE
  16594. }
  16595. set_parents();
  16596. assert_invariant();
  16597. }
  16598. /*!
  16599. @brief create a container (array or object) from an initializer list
  16600. Creates a JSON value of type array or object from the passed initializer
  16601. list @a init. In case @a type_deduction is `true` (default), the type of
  16602. the JSON value to be created is deducted from the initializer list @a init
  16603. according to the following rules:
  16604. 1. If the list is empty, an empty JSON object value `{}` is created.
  16605. 2. If the list consists of pairs whose first element is a string, a JSON
  16606. object value is created where the first elements of the pairs are
  16607. treated as keys and the second elements are as values.
  16608. 3. In all other cases, an array is created.
  16609. The rules aim to create the best fit between a C++ initializer list and
  16610. JSON values. The rationale is as follows:
  16611. 1. The empty initializer list is written as `{}` which is exactly an empty
  16612. JSON object.
  16613. 2. C++ has no way of describing mapped types other than to list a list of
  16614. pairs. As JSON requires that keys must be of type string, rule 2 is the
  16615. weakest constraint one can pose on initializer lists to interpret them
  16616. as an object.
  16617. 3. In all other cases, the initializer list could not be interpreted as
  16618. JSON object type, so interpreting it as JSON array type is safe.
  16619. With the rules described above, the following JSON values cannot be
  16620. expressed by an initializer list:
  16621. - the empty array (`[]`): use @ref array(initializer_list_t)
  16622. with an empty initializer list in this case
  16623. - arrays whose elements satisfy rule 2: use @ref
  16624. array(initializer_list_t) with the same initializer list
  16625. in this case
  16626. @note When used without parentheses around an empty initializer list, @ref
  16627. basic_json() is called instead of this function, yielding the JSON null
  16628. value.
  16629. @param[in] init initializer list with JSON values
  16630. @param[in] type_deduction internal parameter; when set to `true`, the type
  16631. of the JSON value is deducted from the initializer list @a init; when set
  16632. to `false`, the type provided via @a manual_type is forced. This mode is
  16633. used by the functions @ref array(initializer_list_t) and
  16634. @ref object(initializer_list_t).
  16635. @param[in] manual_type internal parameter; when @a type_deduction is set
  16636. to `false`, the created JSON value will use the provided type (only @ref
  16637. value_t::array and @ref value_t::object are valid); when @a type_deduction
  16638. is set to `true`, this parameter has no effect
  16639. @throw type_error.301 if @a type_deduction is `false`, @a manual_type is
  16640. `value_t::object`, but @a init contains an element which is not a pair
  16641. whose first element is a string. In this case, the constructor could not
  16642. create an object. If @a type_deduction would have be `true`, an array
  16643. would have been created. See @ref object(initializer_list_t)
  16644. for an example.
  16645. @complexity Linear in the size of the initializer list @a init.
  16646. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  16647. changes to any JSON value.
  16648. @liveexample{The example below shows how JSON values are created from
  16649. initializer lists.,basic_json__list_init_t}
  16650. @sa see @ref array(initializer_list_t) -- create a JSON array
  16651. value from an initializer list
  16652. @sa see @ref object(initializer_list_t) -- create a JSON object
  16653. value from an initializer list
  16654. @since version 1.0.0
  16655. */
  16656. basic_json(initializer_list_t init,
  16657. bool type_deduction = true,
  16658. value_t manual_type = value_t::array)
  16659. {
  16660. // check if each element is an array with two elements whose first
  16661. // element is a string
  16662. bool is_an_object = std::all_of(init.begin(), init.end(),
  16663. [](const detail::json_ref<basic_json>& element_ref)
  16664. {
  16665. return element_ref->is_array() && element_ref->size() == 2 && (*element_ref)[0].is_string();
  16666. });
  16667. // adjust type if type deduction is not wanted
  16668. if (!type_deduction)
  16669. {
  16670. // if array is wanted, do not create an object though possible
  16671. if (manual_type == value_t::array)
  16672. {
  16673. is_an_object = false;
  16674. }
  16675. // if object is wanted but impossible, throw an exception
  16676. if (JSON_HEDLEY_UNLIKELY(manual_type == value_t::object && !is_an_object))
  16677. {
  16678. JSON_THROW(type_error::create(301, "cannot create object from initializer list", basic_json()));
  16679. }
  16680. }
  16681. if (is_an_object)
  16682. {
  16683. // the initializer list is a list of pairs -> create object
  16684. m_type = value_t::object;
  16685. m_value = value_t::object;
  16686. for (auto& element_ref : init)
  16687. {
  16688. auto element = element_ref.moved_or_copied();
  16689. m_value.object->emplace(
  16690. std::move(*((*element.m_value.array)[0].m_value.string)),
  16691. std::move((*element.m_value.array)[1]));
  16692. }
  16693. }
  16694. else
  16695. {
  16696. // the initializer list describes an array -> create array
  16697. m_type = value_t::array;
  16698. m_value.array = create<array_t>(init.begin(), init.end());
  16699. }
  16700. set_parents();
  16701. assert_invariant();
  16702. }
  16703. /*!
  16704. @brief explicitly create a binary array (without subtype)
  16705. Creates a JSON binary array value from a given binary container. Binary
  16706. values are part of various binary formats, such as CBOR, MessagePack, and
  16707. BSON. This constructor is used to create a value for serialization to those
  16708. formats.
  16709. @note Note, this function exists because of the difficulty in correctly
  16710. specifying the correct template overload in the standard value ctor, as both
  16711. JSON arrays and JSON binary arrays are backed with some form of a
  16712. `std::vector`. Because JSON binary arrays are a non-standard extension it
  16713. was decided that it would be best to prevent automatic initialization of a
  16714. binary array type, for backwards compatibility and so it does not happen on
  16715. accident.
  16716. @param[in] init container containing bytes to use as binary type
  16717. @return JSON binary array value
  16718. @complexity Linear in the size of @a init.
  16719. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  16720. changes to any JSON value.
  16721. @since version 3.8.0
  16722. */
  16723. JSON_HEDLEY_WARN_UNUSED_RESULT
  16724. static basic_json binary(const typename binary_t::container_type& init)
  16725. {
  16726. auto res = basic_json();
  16727. res.m_type = value_t::binary;
  16728. res.m_value = init;
  16729. return res;
  16730. }
  16731. /*!
  16732. @brief explicitly create a binary array (with subtype)
  16733. Creates a JSON binary array value from a given binary container. Binary
  16734. values are part of various binary formats, such as CBOR, MessagePack, and
  16735. BSON. This constructor is used to create a value for serialization to those
  16736. formats.
  16737. @note Note, this function exists because of the difficulty in correctly
  16738. specifying the correct template overload in the standard value ctor, as both
  16739. JSON arrays and JSON binary arrays are backed with some form of a
  16740. `std::vector`. Because JSON binary arrays are a non-standard extension it
  16741. was decided that it would be best to prevent automatic initialization of a
  16742. binary array type, for backwards compatibility and so it does not happen on
  16743. accident.
  16744. @param[in] init container containing bytes to use as binary type
  16745. @param[in] subtype subtype to use in MessagePack and BSON
  16746. @return JSON binary array value
  16747. @complexity Linear in the size of @a init.
  16748. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  16749. changes to any JSON value.
  16750. @since version 3.8.0
  16751. */
  16752. JSON_HEDLEY_WARN_UNUSED_RESULT
  16753. static basic_json binary(const typename binary_t::container_type& init, typename binary_t::subtype_type subtype)
  16754. {
  16755. auto res = basic_json();
  16756. res.m_type = value_t::binary;
  16757. res.m_value = binary_t(init, subtype);
  16758. return res;
  16759. }
  16760. /// @copydoc binary(const typename binary_t::container_type&)
  16761. JSON_HEDLEY_WARN_UNUSED_RESULT
  16762. static basic_json binary(typename binary_t::container_type&& init)
  16763. {
  16764. auto res = basic_json();
  16765. res.m_type = value_t::binary;
  16766. res.m_value = std::move(init);
  16767. return res;
  16768. }
  16769. /// @copydoc binary(const typename binary_t::container_type&, typename binary_t::subtype_type)
  16770. JSON_HEDLEY_WARN_UNUSED_RESULT
  16771. static basic_json binary(typename binary_t::container_type&& init, typename binary_t::subtype_type subtype)
  16772. {
  16773. auto res = basic_json();
  16774. res.m_type = value_t::binary;
  16775. res.m_value = binary_t(std::move(init), subtype);
  16776. return res;
  16777. }
  16778. /*!
  16779. @brief explicitly create an array from an initializer list
  16780. Creates a JSON array value from a given initializer list. That is, given a
  16781. list of values `a, b, c`, creates the JSON value `[a, b, c]`. If the
  16782. initializer list is empty, the empty array `[]` is created.
  16783. @note This function is only needed to express two edge cases that cannot
  16784. be realized with the initializer list constructor (@ref
  16785. basic_json(initializer_list_t, bool, value_t)). These cases
  16786. are:
  16787. 1. creating an array whose elements are all pairs whose first element is a
  16788. string -- in this case, the initializer list constructor would create an
  16789. object, taking the first elements as keys
  16790. 2. creating an empty array -- passing the empty initializer list to the
  16791. initializer list constructor yields an empty object
  16792. @param[in] init initializer list with JSON values to create an array from
  16793. (optional)
  16794. @return JSON array value
  16795. @complexity Linear in the size of @a init.
  16796. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  16797. changes to any JSON value.
  16798. @liveexample{The following code shows an example for the `array`
  16799. function.,array}
  16800. @sa see @ref basic_json(initializer_list_t, bool, value_t) --
  16801. create a JSON value from an initializer list
  16802. @sa see @ref object(initializer_list_t) -- create a JSON object
  16803. value from an initializer list
  16804. @since version 1.0.0
  16805. */
  16806. JSON_HEDLEY_WARN_UNUSED_RESULT
  16807. static basic_json array(initializer_list_t init = {})
  16808. {
  16809. return basic_json(init, false, value_t::array);
  16810. }
  16811. /*!
  16812. @brief explicitly create an object from an initializer list
  16813. Creates a JSON object value from a given initializer list. The initializer
  16814. lists elements must be pairs, and their first elements must be strings. If
  16815. the initializer list is empty, the empty object `{}` is created.
  16816. @note This function is only added for symmetry reasons. In contrast to the
  16817. related function @ref array(initializer_list_t), there are
  16818. no cases which can only be expressed by this function. That is, any
  16819. initializer list @a init can also be passed to the initializer list
  16820. constructor @ref basic_json(initializer_list_t, bool, value_t).
  16821. @param[in] init initializer list to create an object from (optional)
  16822. @return JSON object value
  16823. @throw type_error.301 if @a init is not a list of pairs whose first
  16824. elements are strings. In this case, no object can be created. When such a
  16825. value is passed to @ref basic_json(initializer_list_t, bool, value_t),
  16826. an array would have been created from the passed initializer list @a init.
  16827. See example below.
  16828. @complexity Linear in the size of @a init.
  16829. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  16830. changes to any JSON value.
  16831. @liveexample{The following code shows an example for the `object`
  16832. function.,object}
  16833. @sa see @ref basic_json(initializer_list_t, bool, value_t) --
  16834. create a JSON value from an initializer list
  16835. @sa see @ref array(initializer_list_t) -- create a JSON array
  16836. value from an initializer list
  16837. @since version 1.0.0
  16838. */
  16839. JSON_HEDLEY_WARN_UNUSED_RESULT
  16840. static basic_json object(initializer_list_t init = {})
  16841. {
  16842. return basic_json(init, false, value_t::object);
  16843. }
  16844. /*!
  16845. @brief construct an array with count copies of given value
  16846. Constructs a JSON array value by creating @a cnt copies of a passed value.
  16847. In case @a cnt is `0`, an empty array is created.
  16848. @param[in] cnt the number of JSON copies of @a val to create
  16849. @param[in] val the JSON value to copy
  16850. @post `std::distance(begin(),end()) == cnt` holds.
  16851. @complexity Linear in @a cnt.
  16852. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  16853. changes to any JSON value.
  16854. @liveexample{The following code shows examples for the @ref
  16855. basic_json(size_type\, const basic_json&)
  16856. constructor.,basic_json__size_type_basic_json}
  16857. @since version 1.0.0
  16858. */
  16859. basic_json(size_type cnt, const basic_json& val)
  16860. : m_type(value_t::array)
  16861. {
  16862. m_value.array = create<array_t>(cnt, val);
  16863. set_parents();
  16864. assert_invariant();
  16865. }
  16866. /*!
  16867. @brief construct a JSON container given an iterator range
  16868. Constructs the JSON value with the contents of the range `[first, last)`.
  16869. The semantics depends on the different types a JSON value can have:
  16870. - In case of a null type, invalid_iterator.206 is thrown.
  16871. - In case of other primitive types (number, boolean, or string), @a first
  16872. must be `begin()` and @a last must be `end()`. In this case, the value is
  16873. copied. Otherwise, invalid_iterator.204 is thrown.
  16874. - In case of structured types (array, object), the constructor behaves as
  16875. similar versions for `std::vector` or `std::map`; that is, a JSON array
  16876. or object is constructed from the values in the range.
  16877. @tparam InputIT an input iterator type (@ref iterator or @ref
  16878. const_iterator)
  16879. @param[in] first begin of the range to copy from (included)
  16880. @param[in] last end of the range to copy from (excluded)
  16881. @pre Iterators @a first and @a last must be initialized. **This
  16882. precondition is enforced with an assertion (see warning).** If
  16883. assertions are switched off, a violation of this precondition yields
  16884. undefined behavior.
  16885. @pre Range `[first, last)` is valid. Usually, this precondition cannot be
  16886. checked efficiently. Only certain edge cases are detected; see the
  16887. description of the exceptions below. A violation of this precondition
  16888. yields undefined behavior.
  16889. @warning A precondition is enforced with a runtime assertion that will
  16890. result in calling `std::abort` if this precondition is not met.
  16891. Assertions can be disabled by defining `NDEBUG` at compile time.
  16892. See https://en.cppreference.com/w/cpp/error/assert for more
  16893. information.
  16894. @throw invalid_iterator.201 if iterators @a first and @a last are not
  16895. compatible (i.e., do not belong to the same JSON value). In this case,
  16896. the range `[first, last)` is undefined.
  16897. @throw invalid_iterator.204 if iterators @a first and @a last belong to a
  16898. primitive type (number, boolean, or string), but @a first does not point
  16899. to the first element any more. In this case, the range `[first, last)` is
  16900. undefined. See example code below.
  16901. @throw invalid_iterator.206 if iterators @a first and @a last belong to a
  16902. null value. In this case, the range `[first, last)` is undefined.
  16903. @complexity Linear in distance between @a first and @a last.
  16904. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  16905. changes to any JSON value.
  16906. @liveexample{The example below shows several ways to create JSON values by
  16907. specifying a subrange with iterators.,basic_json__InputIt_InputIt}
  16908. @since version 1.0.0
  16909. */
  16910. template < class InputIT, typename std::enable_if <
  16911. std::is_same<InputIT, typename basic_json_t::iterator>::value ||
  16912. std::is_same<InputIT, typename basic_json_t::const_iterator>::value, int >::type = 0 >
  16913. basic_json(InputIT first, InputIT last)
  16914. {
  16915. JSON_ASSERT(first.m_object != nullptr);
  16916. JSON_ASSERT(last.m_object != nullptr);
  16917. // make sure iterator fits the current value
  16918. if (JSON_HEDLEY_UNLIKELY(first.m_object != last.m_object))
  16919. {
  16920. JSON_THROW(invalid_iterator::create(201, "iterators are not compatible", basic_json()));
  16921. }
  16922. // copy type from first iterator
  16923. m_type = first.m_object->m_type;
  16924. // check if iterator range is complete for primitive values
  16925. switch (m_type)
  16926. {
  16927. case value_t::boolean:
  16928. case value_t::number_float:
  16929. case value_t::number_integer:
  16930. case value_t::number_unsigned:
  16931. case value_t::string:
  16932. {
  16933. if (JSON_HEDLEY_UNLIKELY(!first.m_it.primitive_iterator.is_begin()
  16934. || !last.m_it.primitive_iterator.is_end()))
  16935. {
  16936. JSON_THROW(invalid_iterator::create(204, "iterators out of range", *first.m_object));
  16937. }
  16938. break;
  16939. }
  16940. case value_t::null:
  16941. case value_t::object:
  16942. case value_t::array:
  16943. case value_t::binary:
  16944. case value_t::discarded:
  16945. default:
  16946. break;
  16947. }
  16948. switch (m_type)
  16949. {
  16950. case value_t::number_integer:
  16951. {
  16952. m_value.number_integer = first.m_object->m_value.number_integer;
  16953. break;
  16954. }
  16955. case value_t::number_unsigned:
  16956. {
  16957. m_value.number_unsigned = first.m_object->m_value.number_unsigned;
  16958. break;
  16959. }
  16960. case value_t::number_float:
  16961. {
  16962. m_value.number_float = first.m_object->m_value.number_float;
  16963. break;
  16964. }
  16965. case value_t::boolean:
  16966. {
  16967. m_value.boolean = first.m_object->m_value.boolean;
  16968. break;
  16969. }
  16970. case value_t::string:
  16971. {
  16972. m_value = *first.m_object->m_value.string;
  16973. break;
  16974. }
  16975. case value_t::object:
  16976. {
  16977. m_value.object = create<object_t>(first.m_it.object_iterator,
  16978. last.m_it.object_iterator);
  16979. break;
  16980. }
  16981. case value_t::array:
  16982. {
  16983. m_value.array = create<array_t>(first.m_it.array_iterator,
  16984. last.m_it.array_iterator);
  16985. break;
  16986. }
  16987. case value_t::binary:
  16988. {
  16989. m_value = *first.m_object->m_value.binary;
  16990. break;
  16991. }
  16992. case value_t::null:
  16993. case value_t::discarded:
  16994. default:
  16995. JSON_THROW(invalid_iterator::create(206, "cannot construct with iterators from " + std::string(first.m_object->type_name()), *first.m_object));
  16996. }
  16997. set_parents();
  16998. assert_invariant();
  16999. }
  17000. ///////////////////////////////////////
  17001. // other constructors and destructor //
  17002. ///////////////////////////////////////
  17003. template<typename JsonRef,
  17004. detail::enable_if_t<detail::conjunction<detail::is_json_ref<JsonRef>,
  17005. std::is_same<typename JsonRef::value_type, basic_json>>::value, int> = 0 >
  17006. basic_json(const JsonRef& ref) : basic_json(ref.moved_or_copied()) {}
  17007. /*!
  17008. @brief copy constructor
  17009. Creates a copy of a given JSON value.
  17010. @param[in] other the JSON value to copy
  17011. @post `*this == other`
  17012. @complexity Linear in the size of @a other.
  17013. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  17014. changes to any JSON value.
  17015. @requirement This function helps `basic_json` satisfying the
  17016. [Container](https://en.cppreference.com/w/cpp/named_req/Container)
  17017. requirements:
  17018. - The complexity is linear.
  17019. - As postcondition, it holds: `other == basic_json(other)`.
  17020. @liveexample{The following code shows an example for the copy
  17021. constructor.,basic_json__basic_json}
  17022. @since version 1.0.0
  17023. */
  17024. basic_json(const basic_json& other)
  17025. : m_type(other.m_type)
  17026. {
  17027. // check of passed value is valid
  17028. other.assert_invariant();
  17029. switch (m_type)
  17030. {
  17031. case value_t::object:
  17032. {
  17033. m_value = *other.m_value.object;
  17034. break;
  17035. }
  17036. case value_t::array:
  17037. {
  17038. m_value = *other.m_value.array;
  17039. break;
  17040. }
  17041. case value_t::string:
  17042. {
  17043. m_value = *other.m_value.string;
  17044. break;
  17045. }
  17046. case value_t::boolean:
  17047. {
  17048. m_value = other.m_value.boolean;
  17049. break;
  17050. }
  17051. case value_t::number_integer:
  17052. {
  17053. m_value = other.m_value.number_integer;
  17054. break;
  17055. }
  17056. case value_t::number_unsigned:
  17057. {
  17058. m_value = other.m_value.number_unsigned;
  17059. break;
  17060. }
  17061. case value_t::number_float:
  17062. {
  17063. m_value = other.m_value.number_float;
  17064. break;
  17065. }
  17066. case value_t::binary:
  17067. {
  17068. m_value = *other.m_value.binary;
  17069. break;
  17070. }
  17071. case value_t::null:
  17072. case value_t::discarded:
  17073. default:
  17074. break;
  17075. }
  17076. set_parents();
  17077. assert_invariant();
  17078. }
  17079. /*!
  17080. @brief move constructor
  17081. Move constructor. Constructs a JSON value with the contents of the given
  17082. value @a other using move semantics. It "steals" the resources from @a
  17083. other and leaves it as JSON null value.
  17084. @param[in,out] other value to move to this object
  17085. @post `*this` has the same value as @a other before the call.
  17086. @post @a other is a JSON null value.
  17087. @complexity Constant.
  17088. @exceptionsafety No-throw guarantee: this constructor never throws
  17089. exceptions.
  17090. @requirement This function helps `basic_json` satisfying the
  17091. [MoveConstructible](https://en.cppreference.com/w/cpp/named_req/MoveConstructible)
  17092. requirements.
  17093. @liveexample{The code below shows the move constructor explicitly called
  17094. via std::move.,basic_json__moveconstructor}
  17095. @since version 1.0.0
  17096. */
  17097. basic_json(basic_json&& other) noexcept
  17098. : m_type(std::move(other.m_type)),
  17099. m_value(std::move(other.m_value))
  17100. {
  17101. // check that passed value is valid
  17102. other.assert_invariant(false);
  17103. // invalidate payload
  17104. other.m_type = value_t::null;
  17105. other.m_value = {};
  17106. set_parents();
  17107. assert_invariant();
  17108. }
  17109. /*!
  17110. @brief copy assignment
  17111. Copy assignment operator. Copies a JSON value via the "copy and swap"
  17112. strategy: It is expressed in terms of the copy constructor, destructor,
  17113. and the `swap()` member function.
  17114. @param[in] other value to copy from
  17115. @complexity Linear.
  17116. @requirement This function helps `basic_json` satisfying the
  17117. [Container](https://en.cppreference.com/w/cpp/named_req/Container)
  17118. requirements:
  17119. - The complexity is linear.
  17120. @liveexample{The code below shows and example for the copy assignment. It
  17121. creates a copy of value `a` which is then swapped with `b`. Finally\, the
  17122. copy of `a` (which is the null value after the swap) is
  17123. destroyed.,basic_json__copyassignment}
  17124. @since version 1.0.0
  17125. */
  17126. basic_json& operator=(basic_json other) noexcept (
  17127. std::is_nothrow_move_constructible<value_t>::value&&
  17128. std::is_nothrow_move_assignable<value_t>::value&&
  17129. std::is_nothrow_move_constructible<json_value>::value&&
  17130. std::is_nothrow_move_assignable<json_value>::value
  17131. )
  17132. {
  17133. // check that passed value is valid
  17134. other.assert_invariant();
  17135. using std::swap;
  17136. swap(m_type, other.m_type);
  17137. swap(m_value, other.m_value);
  17138. set_parents();
  17139. assert_invariant();
  17140. return *this;
  17141. }
  17142. /*!
  17143. @brief destructor
  17144. Destroys the JSON value and frees all allocated memory.
  17145. @complexity Linear.
  17146. @requirement This function helps `basic_json` satisfying the
  17147. [Container](https://en.cppreference.com/w/cpp/named_req/Container)
  17148. requirements:
  17149. - The complexity is linear.
  17150. - All stored elements are destroyed and all memory is freed.
  17151. @since version 1.0.0
  17152. */
  17153. ~basic_json() noexcept
  17154. {
  17155. assert_invariant(false);
  17156. m_value.destroy(m_type);
  17157. }
  17158. /// @}
  17159. public:
  17160. ///////////////////////
  17161. // object inspection //
  17162. ///////////////////////
  17163. /// @name object inspection
  17164. /// Functions to inspect the type of a JSON value.
  17165. /// @{
  17166. /*!
  17167. @brief serialization
  17168. Serialization function for JSON values. The function tries to mimic
  17169. Python's `json.dumps()` function, and currently supports its @a indent
  17170. and @a ensure_ascii parameters.
  17171. @param[in] indent If indent is nonnegative, then array elements and object
  17172. members will be pretty-printed with that indent level. An indent level of
  17173. `0` will only insert newlines. `-1` (the default) selects the most compact
  17174. representation.
  17175. @param[in] indent_char The character to use for indentation if @a indent is
  17176. greater than `0`. The default is ` ` (space).
  17177. @param[in] ensure_ascii If @a ensure_ascii is true, all non-ASCII characters
  17178. in the output are escaped with `\uXXXX` sequences, and the result consists
  17179. of ASCII characters only.
  17180. @param[in] error_handler how to react on decoding errors; there are three
  17181. possible values: `strict` (throws and exception in case a decoding error
  17182. occurs; default), `replace` (replace invalid UTF-8 sequences with U+FFFD),
  17183. and `ignore` (ignore invalid UTF-8 sequences during serialization; all
  17184. bytes are copied to the output unchanged).
  17185. @return string containing the serialization of the JSON value
  17186. @throw type_error.316 if a string stored inside the JSON value is not
  17187. UTF-8 encoded and @a error_handler is set to strict
  17188. @note Binary values are serialized as object containing two keys:
  17189. - "bytes": an array of bytes as integers
  17190. - "subtype": the subtype as integer or "null" if the binary has no subtype
  17191. @complexity Linear.
  17192. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  17193. changes in the JSON value.
  17194. @liveexample{The following example shows the effect of different @a indent\,
  17195. @a indent_char\, and @a ensure_ascii parameters to the result of the
  17196. serialization.,dump}
  17197. @see https://docs.python.org/2/library/json.html#json.dump
  17198. @since version 1.0.0; indentation character @a indent_char, option
  17199. @a ensure_ascii and exceptions added in version 3.0.0; error
  17200. handlers added in version 3.4.0; serialization of binary values added
  17201. in version 3.8.0.
  17202. */
  17203. string_t dump(const int indent = -1,
  17204. const char indent_char = ' ',
  17205. const bool ensure_ascii = false,
  17206. const error_handler_t error_handler = error_handler_t::strict) const
  17207. {
  17208. string_t result;
  17209. serializer s(detail::output_adapter<char, string_t>(result), indent_char, error_handler);
  17210. if (indent >= 0)
  17211. {
  17212. s.dump(*this, true, ensure_ascii, static_cast<unsigned int>(indent));
  17213. }
  17214. else
  17215. {
  17216. s.dump(*this, false, ensure_ascii, 0);
  17217. }
  17218. return result;
  17219. }
  17220. /*!
  17221. @brief return the type of the JSON value (explicit)
  17222. Return the type of the JSON value as a value from the @ref value_t
  17223. enumeration.
  17224. @return the type of the JSON value
  17225. Value type | return value
  17226. ------------------------- | -------------------------
  17227. null | value_t::null
  17228. boolean | value_t::boolean
  17229. string | value_t::string
  17230. number (integer) | value_t::number_integer
  17231. number (unsigned integer) | value_t::number_unsigned
  17232. number (floating-point) | value_t::number_float
  17233. object | value_t::object
  17234. array | value_t::array
  17235. binary | value_t::binary
  17236. discarded | value_t::discarded
  17237. @complexity Constant.
  17238. @exceptionsafety No-throw guarantee: this member function never throws
  17239. exceptions.
  17240. @liveexample{The following code exemplifies `type()` for all JSON
  17241. types.,type}
  17242. @sa see @ref operator value_t() -- return the type of the JSON value (implicit)
  17243. @sa see @ref type_name() -- return the type as string
  17244. @since version 1.0.0
  17245. */
  17246. constexpr value_t type() const noexcept
  17247. {
  17248. return m_type;
  17249. }
  17250. /*!
  17251. @brief return whether type is primitive
  17252. This function returns true if and only if the JSON type is primitive
  17253. (string, number, boolean, or null).
  17254. @return `true` if type is primitive (string, number, boolean, or null),
  17255. `false` otherwise.
  17256. @complexity Constant.
  17257. @exceptionsafety No-throw guarantee: this member function never throws
  17258. exceptions.
  17259. @liveexample{The following code exemplifies `is_primitive()` for all JSON
  17260. types.,is_primitive}
  17261. @sa see @ref is_structured() -- returns whether JSON value is structured
  17262. @sa see @ref is_null() -- returns whether JSON value is `null`
  17263. @sa see @ref is_string() -- returns whether JSON value is a string
  17264. @sa see @ref is_boolean() -- returns whether JSON value is a boolean
  17265. @sa see @ref is_number() -- returns whether JSON value is a number
  17266. @sa see @ref is_binary() -- returns whether JSON value is a binary array
  17267. @since version 1.0.0
  17268. */
  17269. constexpr bool is_primitive() const noexcept
  17270. {
  17271. return is_null() || is_string() || is_boolean() || is_number() || is_binary();
  17272. }
  17273. /*!
  17274. @brief return whether type is structured
  17275. This function returns true if and only if the JSON type is structured
  17276. (array or object).
  17277. @return `true` if type is structured (array or object), `false` otherwise.
  17278. @complexity Constant.
  17279. @exceptionsafety No-throw guarantee: this member function never throws
  17280. exceptions.
  17281. @liveexample{The following code exemplifies `is_structured()` for all JSON
  17282. types.,is_structured}
  17283. @sa see @ref is_primitive() -- returns whether value is primitive
  17284. @sa see @ref is_array() -- returns whether value is an array
  17285. @sa see @ref is_object() -- returns whether value is an object
  17286. @since version 1.0.0
  17287. */
  17288. constexpr bool is_structured() const noexcept
  17289. {
  17290. return is_array() || is_object();
  17291. }
  17292. /*!
  17293. @brief return whether value is null
  17294. This function returns true if and only if the JSON value is null.
  17295. @return `true` if type is null, `false` otherwise.
  17296. @complexity Constant.
  17297. @exceptionsafety No-throw guarantee: this member function never throws
  17298. exceptions.
  17299. @liveexample{The following code exemplifies `is_null()` for all JSON
  17300. types.,is_null}
  17301. @since version 1.0.0
  17302. */
  17303. constexpr bool is_null() const noexcept
  17304. {
  17305. return m_type == value_t::null;
  17306. }
  17307. /*!
  17308. @brief return whether value is a boolean
  17309. This function returns true if and only if the JSON value is a boolean.
  17310. @return `true` if type is boolean, `false` otherwise.
  17311. @complexity Constant.
  17312. @exceptionsafety No-throw guarantee: this member function never throws
  17313. exceptions.
  17314. @liveexample{The following code exemplifies `is_boolean()` for all JSON
  17315. types.,is_boolean}
  17316. @since version 1.0.0
  17317. */
  17318. constexpr bool is_boolean() const noexcept
  17319. {
  17320. return m_type == value_t::boolean;
  17321. }
  17322. /*!
  17323. @brief return whether value is a number
  17324. This function returns true if and only if the JSON value is a number. This
  17325. includes both integer (signed and unsigned) and floating-point values.
  17326. @return `true` if type is number (regardless whether integer, unsigned
  17327. integer or floating-type), `false` otherwise.
  17328. @complexity Constant.
  17329. @exceptionsafety No-throw guarantee: this member function never throws
  17330. exceptions.
  17331. @liveexample{The following code exemplifies `is_number()` for all JSON
  17332. types.,is_number}
  17333. @sa see @ref is_number_integer() -- check if value is an integer or unsigned
  17334. integer number
  17335. @sa see @ref is_number_unsigned() -- check if value is an unsigned integer
  17336. number
  17337. @sa see @ref is_number_float() -- check if value is a floating-point number
  17338. @since version 1.0.0
  17339. */
  17340. constexpr bool is_number() const noexcept
  17341. {
  17342. return is_number_integer() || is_number_float();
  17343. }
  17344. /*!
  17345. @brief return whether value is an integer number
  17346. This function returns true if and only if the JSON value is a signed or
  17347. unsigned integer number. This excludes floating-point values.
  17348. @return `true` if type is an integer or unsigned integer number, `false`
  17349. otherwise.
  17350. @complexity Constant.
  17351. @exceptionsafety No-throw guarantee: this member function never throws
  17352. exceptions.
  17353. @liveexample{The following code exemplifies `is_number_integer()` for all
  17354. JSON types.,is_number_integer}
  17355. @sa see @ref is_number() -- check if value is a number
  17356. @sa see @ref is_number_unsigned() -- check if value is an unsigned integer
  17357. number
  17358. @sa see @ref is_number_float() -- check if value is a floating-point number
  17359. @since version 1.0.0
  17360. */
  17361. constexpr bool is_number_integer() const noexcept
  17362. {
  17363. return m_type == value_t::number_integer || m_type == value_t::number_unsigned;
  17364. }
  17365. /*!
  17366. @brief return whether value is an unsigned integer number
  17367. This function returns true if and only if the JSON value is an unsigned
  17368. integer number. This excludes floating-point and signed integer values.
  17369. @return `true` if type is an unsigned integer number, `false` otherwise.
  17370. @complexity Constant.
  17371. @exceptionsafety No-throw guarantee: this member function never throws
  17372. exceptions.
  17373. @liveexample{The following code exemplifies `is_number_unsigned()` for all
  17374. JSON types.,is_number_unsigned}
  17375. @sa see @ref is_number() -- check if value is a number
  17376. @sa see @ref is_number_integer() -- check if value is an integer or unsigned
  17377. integer number
  17378. @sa see @ref is_number_float() -- check if value is a floating-point number
  17379. @since version 2.0.0
  17380. */
  17381. constexpr bool is_number_unsigned() const noexcept
  17382. {
  17383. return m_type == value_t::number_unsigned;
  17384. }
  17385. /*!
  17386. @brief return whether value is a floating-point number
  17387. This function returns true if and only if the JSON value is a
  17388. floating-point number. This excludes signed and unsigned integer values.
  17389. @return `true` if type is a floating-point number, `false` otherwise.
  17390. @complexity Constant.
  17391. @exceptionsafety No-throw guarantee: this member function never throws
  17392. exceptions.
  17393. @liveexample{The following code exemplifies `is_number_float()` for all
  17394. JSON types.,is_number_float}
  17395. @sa see @ref is_number() -- check if value is number
  17396. @sa see @ref is_number_integer() -- check if value is an integer number
  17397. @sa see @ref is_number_unsigned() -- check if value is an unsigned integer
  17398. number
  17399. @since version 1.0.0
  17400. */
  17401. constexpr bool is_number_float() const noexcept
  17402. {
  17403. return m_type == value_t::number_float;
  17404. }
  17405. /*!
  17406. @brief return whether value is an object
  17407. This function returns true if and only if the JSON value is an object.
  17408. @return `true` if type is object, `false` otherwise.
  17409. @complexity Constant.
  17410. @exceptionsafety No-throw guarantee: this member function never throws
  17411. exceptions.
  17412. @liveexample{The following code exemplifies `is_object()` for all JSON
  17413. types.,is_object}
  17414. @since version 1.0.0
  17415. */
  17416. constexpr bool is_object() const noexcept
  17417. {
  17418. return m_type == value_t::object;
  17419. }
  17420. /*!
  17421. @brief return whether value is an array
  17422. This function returns true if and only if the JSON value is an array.
  17423. @return `true` if type is array, `false` otherwise.
  17424. @complexity Constant.
  17425. @exceptionsafety No-throw guarantee: this member function never throws
  17426. exceptions.
  17427. @liveexample{The following code exemplifies `is_array()` for all JSON
  17428. types.,is_array}
  17429. @since version 1.0.0
  17430. */
  17431. constexpr bool is_array() const noexcept
  17432. {
  17433. return m_type == value_t::array;
  17434. }
  17435. /*!
  17436. @brief return whether value is a string
  17437. This function returns true if and only if the JSON value is a string.
  17438. @return `true` if type is string, `false` otherwise.
  17439. @complexity Constant.
  17440. @exceptionsafety No-throw guarantee: this member function never throws
  17441. exceptions.
  17442. @liveexample{The following code exemplifies `is_string()` for all JSON
  17443. types.,is_string}
  17444. @since version 1.0.0
  17445. */
  17446. constexpr bool is_string() const noexcept
  17447. {
  17448. return m_type == value_t::string;
  17449. }
  17450. /*!
  17451. @brief return whether value is a binary array
  17452. This function returns true if and only if the JSON value is a binary array.
  17453. @return `true` if type is binary array, `false` otherwise.
  17454. @complexity Constant.
  17455. @exceptionsafety No-throw guarantee: this member function never throws
  17456. exceptions.
  17457. @liveexample{The following code exemplifies `is_binary()` for all JSON
  17458. types.,is_binary}
  17459. @since version 3.8.0
  17460. */
  17461. constexpr bool is_binary() const noexcept
  17462. {
  17463. return m_type == value_t::binary;
  17464. }
  17465. /*!
  17466. @brief return whether value is discarded
  17467. This function returns true if and only if the JSON value was discarded
  17468. during parsing with a callback function (see @ref parser_callback_t).
  17469. @note This function will always be `false` for JSON values after parsing.
  17470. That is, discarded values can only occur during parsing, but will be
  17471. removed when inside a structured value or replaced by null in other cases.
  17472. @return `true` if type is discarded, `false` otherwise.
  17473. @complexity Constant.
  17474. @exceptionsafety No-throw guarantee: this member function never throws
  17475. exceptions.
  17476. @liveexample{The following code exemplifies `is_discarded()` for all JSON
  17477. types.,is_discarded}
  17478. @since version 1.0.0
  17479. */
  17480. constexpr bool is_discarded() const noexcept
  17481. {
  17482. return m_type == value_t::discarded;
  17483. }
  17484. /*!
  17485. @brief return the type of the JSON value (implicit)
  17486. Implicitly return the type of the JSON value as a value from the @ref
  17487. value_t enumeration.
  17488. @return the type of the JSON value
  17489. @complexity Constant.
  17490. @exceptionsafety No-throw guarantee: this member function never throws
  17491. exceptions.
  17492. @liveexample{The following code exemplifies the @ref value_t operator for
  17493. all JSON types.,operator__value_t}
  17494. @sa see @ref type() -- return the type of the JSON value (explicit)
  17495. @sa see @ref type_name() -- return the type as string
  17496. @since version 1.0.0
  17497. */
  17498. constexpr operator value_t() const noexcept
  17499. {
  17500. return m_type;
  17501. }
  17502. /// @}
  17503. private:
  17504. //////////////////
  17505. // value access //
  17506. //////////////////
  17507. /// get a boolean (explicit)
  17508. boolean_t get_impl(boolean_t* /*unused*/) const
  17509. {
  17510. if (JSON_HEDLEY_LIKELY(is_boolean()))
  17511. {
  17512. return m_value.boolean;
  17513. }
  17514. JSON_THROW(type_error::create(302, "type must be boolean, but is " + std::string(type_name()), *this));
  17515. }
  17516. /// get a pointer to the value (object)
  17517. object_t* get_impl_ptr(object_t* /*unused*/) noexcept
  17518. {
  17519. return is_object() ? m_value.object : nullptr;
  17520. }
  17521. /// get a pointer to the value (object)
  17522. constexpr const object_t* get_impl_ptr(const object_t* /*unused*/) const noexcept
  17523. {
  17524. return is_object() ? m_value.object : nullptr;
  17525. }
  17526. /// get a pointer to the value (array)
  17527. array_t* get_impl_ptr(array_t* /*unused*/) noexcept
  17528. {
  17529. return is_array() ? m_value.array : nullptr;
  17530. }
  17531. /// get a pointer to the value (array)
  17532. constexpr const array_t* get_impl_ptr(const array_t* /*unused*/) const noexcept
  17533. {
  17534. return is_array() ? m_value.array : nullptr;
  17535. }
  17536. /// get a pointer to the value (string)
  17537. string_t* get_impl_ptr(string_t* /*unused*/) noexcept
  17538. {
  17539. return is_string() ? m_value.string : nullptr;
  17540. }
  17541. /// get a pointer to the value (string)
  17542. constexpr const string_t* get_impl_ptr(const string_t* /*unused*/) const noexcept
  17543. {
  17544. return is_string() ? m_value.string : nullptr;
  17545. }
  17546. /// get a pointer to the value (boolean)
  17547. boolean_t* get_impl_ptr(boolean_t* /*unused*/) noexcept
  17548. {
  17549. return is_boolean() ? &m_value.boolean : nullptr;
  17550. }
  17551. /// get a pointer to the value (boolean)
  17552. constexpr const boolean_t* get_impl_ptr(const boolean_t* /*unused*/) const noexcept
  17553. {
  17554. return is_boolean() ? &m_value.boolean : nullptr;
  17555. }
  17556. /// get a pointer to the value (integer number)
  17557. number_integer_t* get_impl_ptr(number_integer_t* /*unused*/) noexcept
  17558. {
  17559. return is_number_integer() ? &m_value.number_integer : nullptr;
  17560. }
  17561. /// get a pointer to the value (integer number)
  17562. constexpr const number_integer_t* get_impl_ptr(const number_integer_t* /*unused*/) const noexcept
  17563. {
  17564. return is_number_integer() ? &m_value.number_integer : nullptr;
  17565. }
  17566. /// get a pointer to the value (unsigned number)
  17567. number_unsigned_t* get_impl_ptr(number_unsigned_t* /*unused*/) noexcept
  17568. {
  17569. return is_number_unsigned() ? &m_value.number_unsigned : nullptr;
  17570. }
  17571. /// get a pointer to the value (unsigned number)
  17572. constexpr const number_unsigned_t* get_impl_ptr(const number_unsigned_t* /*unused*/) const noexcept
  17573. {
  17574. return is_number_unsigned() ? &m_value.number_unsigned : nullptr;
  17575. }
  17576. /// get a pointer to the value (floating-point number)
  17577. number_float_t* get_impl_ptr(number_float_t* /*unused*/) noexcept
  17578. {
  17579. return is_number_float() ? &m_value.number_float : nullptr;
  17580. }
  17581. /// get a pointer to the value (floating-point number)
  17582. constexpr const number_float_t* get_impl_ptr(const number_float_t* /*unused*/) const noexcept
  17583. {
  17584. return is_number_float() ? &m_value.number_float : nullptr;
  17585. }
  17586. /// get a pointer to the value (binary)
  17587. binary_t* get_impl_ptr(binary_t* /*unused*/) noexcept
  17588. {
  17589. return is_binary() ? m_value.binary : nullptr;
  17590. }
  17591. /// get a pointer to the value (binary)
  17592. constexpr const binary_t* get_impl_ptr(const binary_t* /*unused*/) const noexcept
  17593. {
  17594. return is_binary() ? m_value.binary : nullptr;
  17595. }
  17596. /*!
  17597. @brief helper function to implement get_ref()
  17598. This function helps to implement get_ref() without code duplication for
  17599. const and non-const overloads
  17600. @tparam ThisType will be deduced as `basic_json` or `const basic_json`
  17601. @throw type_error.303 if ReferenceType does not match underlying value
  17602. type of the current JSON
  17603. */
  17604. template<typename ReferenceType, typename ThisType>
  17605. static ReferenceType get_ref_impl(ThisType& obj)
  17606. {
  17607. // delegate the call to get_ptr<>()
  17608. auto* ptr = obj.template get_ptr<typename std::add_pointer<ReferenceType>::type>();
  17609. if (JSON_HEDLEY_LIKELY(ptr != nullptr))
  17610. {
  17611. return *ptr;
  17612. }
  17613. JSON_THROW(type_error::create(303, "incompatible ReferenceType for get_ref, actual type is " + std::string(obj.type_name()), obj));
  17614. }
  17615. public:
  17616. /// @name value access
  17617. /// Direct access to the stored value of a JSON value.
  17618. /// @{
  17619. /*!
  17620. @brief get a pointer value (implicit)
  17621. Implicit pointer access to the internally stored JSON value. No copies are
  17622. made.
  17623. @warning Writing data to the pointee of the result yields an undefined
  17624. state.
  17625. @tparam PointerType pointer type; must be a pointer to @ref array_t, @ref
  17626. object_t, @ref string_t, @ref boolean_t, @ref number_integer_t,
  17627. @ref number_unsigned_t, or @ref number_float_t. Enforced by a static
  17628. assertion.
  17629. @return pointer to the internally stored JSON value if the requested
  17630. pointer type @a PointerType fits to the JSON value; `nullptr` otherwise
  17631. @complexity Constant.
  17632. @liveexample{The example below shows how pointers to internal values of a
  17633. JSON value can be requested. Note that no type conversions are made and a
  17634. `nullptr` is returned if the value and the requested pointer type does not
  17635. match.,get_ptr}
  17636. @since version 1.0.0
  17637. */
  17638. template<typename PointerType, typename std::enable_if<
  17639. std::is_pointer<PointerType>::value, int>::type = 0>
  17640. auto get_ptr() noexcept -> decltype(std::declval<basic_json_t&>().get_impl_ptr(std::declval<PointerType>()))
  17641. {
  17642. // delegate the call to get_impl_ptr<>()
  17643. return get_impl_ptr(static_cast<PointerType>(nullptr));
  17644. }
  17645. /*!
  17646. @brief get a pointer value (implicit)
  17647. @copydoc get_ptr()
  17648. */
  17649. template < typename PointerType, typename std::enable_if <
  17650. std::is_pointer<PointerType>::value&&
  17651. std::is_const<typename std::remove_pointer<PointerType>::type>::value, int >::type = 0 >
  17652. constexpr auto get_ptr() const noexcept -> decltype(std::declval<const basic_json_t&>().get_impl_ptr(std::declval<PointerType>()))
  17653. {
  17654. // delegate the call to get_impl_ptr<>() const
  17655. return get_impl_ptr(static_cast<PointerType>(nullptr));
  17656. }
  17657. private:
  17658. /*!
  17659. @brief get a value (explicit)
  17660. Explicit type conversion between the JSON value and a compatible value
  17661. which is [CopyConstructible](https://en.cppreference.com/w/cpp/named_req/CopyConstructible)
  17662. and [DefaultConstructible](https://en.cppreference.com/w/cpp/named_req/DefaultConstructible).
  17663. The value is converted by calling the @ref json_serializer<ValueType>
  17664. `from_json()` method.
  17665. The function is equivalent to executing
  17666. @code {.cpp}
  17667. ValueType ret;
  17668. JSONSerializer<ValueType>::from_json(*this, ret);
  17669. return ret;
  17670. @endcode
  17671. This overloads is chosen if:
  17672. - @a ValueType is not @ref basic_json,
  17673. - @ref json_serializer<ValueType> has a `from_json()` method of the form
  17674. `void from_json(const basic_json&, ValueType&)`, and
  17675. - @ref json_serializer<ValueType> does not have a `from_json()` method of
  17676. the form `ValueType from_json(const basic_json&)`
  17677. @tparam ValueType the returned value type
  17678. @return copy of the JSON value, converted to @a ValueType
  17679. @throw what @ref json_serializer<ValueType> `from_json()` method throws
  17680. @liveexample{The example below shows several conversions from JSON values
  17681. to other types. There a few things to note: (1) Floating-point numbers can
  17682. be converted to integers\, (2) A JSON array can be converted to a standard
  17683. `std::vector<short>`\, (3) A JSON object can be converted to C++
  17684. associative containers such as `std::unordered_map<std::string\,
  17685. json>`.,get__ValueType_const}
  17686. @since version 2.1.0
  17687. */
  17688. template < typename ValueType,
  17689. detail::enable_if_t <
  17690. detail::is_default_constructible<ValueType>::value&&
  17691. detail::has_from_json<basic_json_t, ValueType>::value,
  17692. int > = 0 >
  17693. ValueType get_impl(detail::priority_tag<0> /*unused*/) const noexcept(noexcept(
  17694. JSONSerializer<ValueType>::from_json(std::declval<const basic_json_t&>(), std::declval<ValueType&>())))
  17695. {
  17696. auto ret = ValueType();
  17697. JSONSerializer<ValueType>::from_json(*this, ret);
  17698. return ret;
  17699. }
  17700. /*!
  17701. @brief get a value (explicit); special case
  17702. Explicit type conversion between the JSON value and a compatible value
  17703. which is **not** [CopyConstructible](https://en.cppreference.com/w/cpp/named_req/CopyConstructible)
  17704. and **not** [DefaultConstructible](https://en.cppreference.com/w/cpp/named_req/DefaultConstructible).
  17705. The value is converted by calling the @ref json_serializer<ValueType>
  17706. `from_json()` method.
  17707. The function is equivalent to executing
  17708. @code {.cpp}
  17709. return JSONSerializer<ValueType>::from_json(*this);
  17710. @endcode
  17711. This overloads is chosen if:
  17712. - @a ValueType is not @ref basic_json and
  17713. - @ref json_serializer<ValueType> has a `from_json()` method of the form
  17714. `ValueType from_json(const basic_json&)`
  17715. @note If @ref json_serializer<ValueType> has both overloads of
  17716. `from_json()`, this one is chosen.
  17717. @tparam ValueType the returned value type
  17718. @return copy of the JSON value, converted to @a ValueType
  17719. @throw what @ref json_serializer<ValueType> `from_json()` method throws
  17720. @since version 2.1.0
  17721. */
  17722. template < typename ValueType,
  17723. detail::enable_if_t <
  17724. detail::has_non_default_from_json<basic_json_t, ValueType>::value,
  17725. int > = 0 >
  17726. ValueType get_impl(detail::priority_tag<1> /*unused*/) const noexcept(noexcept(
  17727. JSONSerializer<ValueType>::from_json(std::declval<const basic_json_t&>())))
  17728. {
  17729. return JSONSerializer<ValueType>::from_json(*this);
  17730. }
  17731. /*!
  17732. @brief get special-case overload
  17733. This overloads converts the current @ref basic_json in a different
  17734. @ref basic_json type
  17735. @tparam BasicJsonType == @ref basic_json
  17736. @return a copy of *this, converted into @a BasicJsonType
  17737. @complexity Depending on the implementation of the called `from_json()`
  17738. method.
  17739. @since version 3.2.0
  17740. */
  17741. template < typename BasicJsonType,
  17742. detail::enable_if_t <
  17743. detail::is_basic_json<BasicJsonType>::value,
  17744. int > = 0 >
  17745. BasicJsonType get_impl(detail::priority_tag<2> /*unused*/) const
  17746. {
  17747. return *this;
  17748. }
  17749. /*!
  17750. @brief get special-case overload
  17751. This overloads avoids a lot of template boilerplate, it can be seen as the
  17752. identity method
  17753. @tparam BasicJsonType == @ref basic_json
  17754. @return a copy of *this
  17755. @complexity Constant.
  17756. @since version 2.1.0
  17757. */
  17758. template<typename BasicJsonType,
  17759. detail::enable_if_t<
  17760. std::is_same<BasicJsonType, basic_json_t>::value,
  17761. int> = 0>
  17762. basic_json get_impl(detail::priority_tag<3> /*unused*/) const
  17763. {
  17764. return *this;
  17765. }
  17766. /*!
  17767. @brief get a pointer value (explicit)
  17768. @copydoc get()
  17769. */
  17770. template<typename PointerType,
  17771. detail::enable_if_t<
  17772. std::is_pointer<PointerType>::value,
  17773. int> = 0>
  17774. constexpr auto get_impl(detail::priority_tag<4> /*unused*/) const noexcept
  17775. -> decltype(std::declval<const basic_json_t&>().template get_ptr<PointerType>())
  17776. {
  17777. // delegate the call to get_ptr
  17778. return get_ptr<PointerType>();
  17779. }
  17780. public:
  17781. /*!
  17782. @brief get a (pointer) value (explicit)
  17783. Performs explicit type conversion between the JSON value and a compatible value if required.
  17784. - If the requested type is a pointer to the internally stored JSON value that pointer is returned.
  17785. No copies are made.
  17786. - If the requested type is the current @ref basic_json, or a different @ref basic_json convertible
  17787. from the current @ref basic_json.
  17788. - Otherwise the value is converted by calling the @ref json_serializer<ValueType> `from_json()`
  17789. method.
  17790. @tparam ValueTypeCV the provided value type
  17791. @tparam ValueType the returned value type
  17792. @return copy of the JSON value, converted to @tparam ValueType if necessary
  17793. @throw what @ref json_serializer<ValueType> `from_json()` method throws if conversion is required
  17794. @since version 2.1.0
  17795. */
  17796. template < typename ValueTypeCV, typename ValueType = detail::uncvref_t<ValueTypeCV>>
  17797. #if defined(JSON_HAS_CPP_14)
  17798. constexpr
  17799. #endif
  17800. auto get() const noexcept(
  17801. noexcept(std::declval<const basic_json_t&>().template get_impl<ValueType>(detail::priority_tag<4> {})))
  17802. -> decltype(std::declval<const basic_json_t&>().template get_impl<ValueType>(detail::priority_tag<4> {}))
  17803. {
  17804. // we cannot static_assert on ValueTypeCV being non-const, because
  17805. // there is support for get<const basic_json_t>(), which is why we
  17806. // still need the uncvref
  17807. static_assert(!std::is_reference<ValueTypeCV>::value,
  17808. "get() cannot be used with reference types, you might want to use get_ref()");
  17809. return get_impl<ValueType>(detail::priority_tag<4> {});
  17810. }
  17811. /*!
  17812. @brief get a pointer value (explicit)
  17813. Explicit pointer access to the internally stored JSON value. No copies are
  17814. made.
  17815. @warning The pointer becomes invalid if the underlying JSON object
  17816. changes.
  17817. @tparam PointerType pointer type; must be a pointer to @ref array_t, @ref
  17818. object_t, @ref string_t, @ref boolean_t, @ref number_integer_t,
  17819. @ref number_unsigned_t, or @ref number_float_t.
  17820. @return pointer to the internally stored JSON value if the requested
  17821. pointer type @a PointerType fits to the JSON value; `nullptr` otherwise
  17822. @complexity Constant.
  17823. @liveexample{The example below shows how pointers to internal values of a
  17824. JSON value can be requested. Note that no type conversions are made and a
  17825. `nullptr` is returned if the value and the requested pointer type does not
  17826. match.,get__PointerType}
  17827. @sa see @ref get_ptr() for explicit pointer-member access
  17828. @since version 1.0.0
  17829. */
  17830. template<typename PointerType, typename std::enable_if<
  17831. std::is_pointer<PointerType>::value, int>::type = 0>
  17832. auto get() noexcept -> decltype(std::declval<basic_json_t&>().template get_ptr<PointerType>())
  17833. {
  17834. // delegate the call to get_ptr
  17835. return get_ptr<PointerType>();
  17836. }
  17837. /*!
  17838. @brief get a value (explicit)
  17839. Explicit type conversion between the JSON value and a compatible value.
  17840. The value is filled into the input parameter by calling the @ref json_serializer<ValueType>
  17841. `from_json()` method.
  17842. The function is equivalent to executing
  17843. @code {.cpp}
  17844. ValueType v;
  17845. JSONSerializer<ValueType>::from_json(*this, v);
  17846. @endcode
  17847. This overloads is chosen if:
  17848. - @a ValueType is not @ref basic_json,
  17849. - @ref json_serializer<ValueType> has a `from_json()` method of the form
  17850. `void from_json(const basic_json&, ValueType&)`, and
  17851. @tparam ValueType the input parameter type.
  17852. @return the input parameter, allowing chaining calls.
  17853. @throw what @ref json_serializer<ValueType> `from_json()` method throws
  17854. @liveexample{The example below shows several conversions from JSON values
  17855. to other types. There a few things to note: (1) Floating-point numbers can
  17856. be converted to integers\, (2) A JSON array can be converted to a standard
  17857. `std::vector<short>`\, (3) A JSON object can be converted to C++
  17858. associative containers such as `std::unordered_map<std::string\,
  17859. json>`.,get_to}
  17860. @since version 3.3.0
  17861. */
  17862. template < typename ValueType,
  17863. detail::enable_if_t <
  17864. !detail::is_basic_json<ValueType>::value&&
  17865. detail::has_from_json<basic_json_t, ValueType>::value,
  17866. int > = 0 >
  17867. ValueType & get_to(ValueType& v) const noexcept(noexcept(
  17868. JSONSerializer<ValueType>::from_json(std::declval<const basic_json_t&>(), v)))
  17869. {
  17870. JSONSerializer<ValueType>::from_json(*this, v);
  17871. return v;
  17872. }
  17873. // specialization to allow to call get_to with a basic_json value
  17874. // see https://github.com/nlohmann/json/issues/2175
  17875. template<typename ValueType,
  17876. detail::enable_if_t <
  17877. detail::is_basic_json<ValueType>::value,
  17878. int> = 0>
  17879. ValueType & get_to(ValueType& v) const
  17880. {
  17881. v = *this;
  17882. return v;
  17883. }
  17884. template <
  17885. typename T, std::size_t N,
  17886. typename Array = T (&)[N], // NOLINT(cppcoreguidelines-avoid-c-arrays,hicpp-avoid-c-arrays,modernize-avoid-c-arrays)
  17887. detail::enable_if_t <
  17888. detail::has_from_json<basic_json_t, Array>::value, int > = 0 >
  17889. Array get_to(T (&v)[N]) const // NOLINT(cppcoreguidelines-avoid-c-arrays,hicpp-avoid-c-arrays,modernize-avoid-c-arrays)
  17890. noexcept(noexcept(JSONSerializer<Array>::from_json(
  17891. std::declval<const basic_json_t&>(), v)))
  17892. {
  17893. JSONSerializer<Array>::from_json(*this, v);
  17894. return v;
  17895. }
  17896. /*!
  17897. @brief get a reference value (implicit)
  17898. Implicit reference access to the internally stored JSON value. No copies
  17899. are made.
  17900. @warning Writing data to the referee of the result yields an undefined
  17901. state.
  17902. @tparam ReferenceType reference type; must be a reference to @ref array_t,
  17903. @ref object_t, @ref string_t, @ref boolean_t, @ref number_integer_t, or
  17904. @ref number_float_t. Enforced by static assertion.
  17905. @return reference to the internally stored JSON value if the requested
  17906. reference type @a ReferenceType fits to the JSON value; throws
  17907. type_error.303 otherwise
  17908. @throw type_error.303 in case passed type @a ReferenceType is incompatible
  17909. with the stored JSON value; see example below
  17910. @complexity Constant.
  17911. @liveexample{The example shows several calls to `get_ref()`.,get_ref}
  17912. @since version 1.1.0
  17913. */
  17914. template<typename ReferenceType, typename std::enable_if<
  17915. std::is_reference<ReferenceType>::value, int>::type = 0>
  17916. ReferenceType get_ref()
  17917. {
  17918. // delegate call to get_ref_impl
  17919. return get_ref_impl<ReferenceType>(*this);
  17920. }
  17921. /*!
  17922. @brief get a reference value (implicit)
  17923. @copydoc get_ref()
  17924. */
  17925. template < typename ReferenceType, typename std::enable_if <
  17926. std::is_reference<ReferenceType>::value&&
  17927. std::is_const<typename std::remove_reference<ReferenceType>::type>::value, int >::type = 0 >
  17928. ReferenceType get_ref() const
  17929. {
  17930. // delegate call to get_ref_impl
  17931. return get_ref_impl<ReferenceType>(*this);
  17932. }
  17933. /*!
  17934. @brief get a value (implicit)
  17935. Implicit type conversion between the JSON value and a compatible value.
  17936. The call is realized by calling @ref get() const.
  17937. @tparam ValueType non-pointer type compatible to the JSON value, for
  17938. instance `int` for JSON integer numbers, `bool` for JSON booleans, or
  17939. `std::vector` types for JSON arrays. The character type of @ref string_t
  17940. as well as an initializer list of this type is excluded to avoid
  17941. ambiguities as these types implicitly convert to `std::string`.
  17942. @return copy of the JSON value, converted to type @a ValueType
  17943. @throw type_error.302 in case passed type @a ValueType is incompatible
  17944. to the JSON value type (e.g., the JSON value is of type boolean, but a
  17945. string is requested); see example below
  17946. @complexity Linear in the size of the JSON value.
  17947. @liveexample{The example below shows several conversions from JSON values
  17948. to other types. There a few things to note: (1) Floating-point numbers can
  17949. be converted to integers\, (2) A JSON array can be converted to a standard
  17950. `std::vector<short>`\, (3) A JSON object can be converted to C++
  17951. associative containers such as `std::unordered_map<std::string\,
  17952. json>`.,operator__ValueType}
  17953. @since version 1.0.0
  17954. */
  17955. template < typename ValueType, typename std::enable_if <
  17956. detail::conjunction <
  17957. detail::negation<std::is_pointer<ValueType>>,
  17958. detail::negation<std::is_same<ValueType, detail::json_ref<basic_json>>>,
  17959. detail::negation<std::is_same<ValueType, typename string_t::value_type>>,
  17960. detail::negation<detail::is_basic_json<ValueType>>,
  17961. detail::negation<std::is_same<ValueType, std::initializer_list<typename string_t::value_type>>>,
  17962. #if defined(JSON_HAS_CPP_17) && (defined(__GNUC__) || (defined(_MSC_VER) && _MSC_VER >= 1910 && _MSC_VER <= 1914))
  17963. detail::negation<std::is_same<ValueType, std::string_view>>,
  17964. #endif
  17965. detail::is_detected_lazy<detail::get_template_function, const basic_json_t&, ValueType>
  17966. >::value, int >::type = 0 >
  17967. JSON_EXPLICIT operator ValueType() const
  17968. {
  17969. // delegate the call to get<>() const
  17970. return get<ValueType>();
  17971. }
  17972. /*!
  17973. @return reference to the binary value
  17974. @throw type_error.302 if the value is not binary
  17975. @sa see @ref is_binary() to check if the value is binary
  17976. @since version 3.8.0
  17977. */
  17978. binary_t& get_binary()
  17979. {
  17980. if (!is_binary())
  17981. {
  17982. JSON_THROW(type_error::create(302, "type must be binary, but is " + std::string(type_name()), *this));
  17983. }
  17984. return *get_ptr<binary_t*>();
  17985. }
  17986. /// @copydoc get_binary()
  17987. const binary_t& get_binary() const
  17988. {
  17989. if (!is_binary())
  17990. {
  17991. JSON_THROW(type_error::create(302, "type must be binary, but is " + std::string(type_name()), *this));
  17992. }
  17993. return *get_ptr<const binary_t*>();
  17994. }
  17995. /// @}
  17996. ////////////////////
  17997. // element access //
  17998. ////////////////////
  17999. /// @name element access
  18000. /// Access to the JSON value.
  18001. /// @{
  18002. /*!
  18003. @brief access specified array element with bounds checking
  18004. Returns a reference to the element at specified location @a idx, with
  18005. bounds checking.
  18006. @param[in] idx index of the element to access
  18007. @return reference to the element at index @a idx
  18008. @throw type_error.304 if the JSON value is not an array; in this case,
  18009. calling `at` with an index makes no sense. See example below.
  18010. @throw out_of_range.401 if the index @a idx is out of range of the array;
  18011. that is, `idx >= size()`. See example below.
  18012. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  18013. changes in the JSON value.
  18014. @complexity Constant.
  18015. @since version 1.0.0
  18016. @liveexample{The example below shows how array elements can be read and
  18017. written using `at()`. It also demonstrates the different exceptions that
  18018. can be thrown.,at__size_type}
  18019. */
  18020. reference at(size_type idx)
  18021. {
  18022. // at only works for arrays
  18023. if (JSON_HEDLEY_LIKELY(is_array()))
  18024. {
  18025. JSON_TRY
  18026. {
  18027. return set_parent(m_value.array->at(idx));
  18028. }
  18029. JSON_CATCH (std::out_of_range&)
  18030. {
  18031. // create better exception explanation
  18032. JSON_THROW(out_of_range::create(401, "array index " + std::to_string(idx) + " is out of range", *this));
  18033. }
  18034. }
  18035. else
  18036. {
  18037. JSON_THROW(type_error::create(304, "cannot use at() with " + std::string(type_name()), *this));
  18038. }
  18039. }
  18040. /*!
  18041. @brief access specified array element with bounds checking
  18042. Returns a const reference to the element at specified location @a idx,
  18043. with bounds checking.
  18044. @param[in] idx index of the element to access
  18045. @return const reference to the element at index @a idx
  18046. @throw type_error.304 if the JSON value is not an array; in this case,
  18047. calling `at` with an index makes no sense. See example below.
  18048. @throw out_of_range.401 if the index @a idx is out of range of the array;
  18049. that is, `idx >= size()`. See example below.
  18050. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  18051. changes in the JSON value.
  18052. @complexity Constant.
  18053. @since version 1.0.0
  18054. @liveexample{The example below shows how array elements can be read using
  18055. `at()`. It also demonstrates the different exceptions that can be thrown.,
  18056. at__size_type_const}
  18057. */
  18058. const_reference at(size_type idx) const
  18059. {
  18060. // at only works for arrays
  18061. if (JSON_HEDLEY_LIKELY(is_array()))
  18062. {
  18063. JSON_TRY
  18064. {
  18065. return m_value.array->at(idx);
  18066. }
  18067. JSON_CATCH (std::out_of_range&)
  18068. {
  18069. // create better exception explanation
  18070. JSON_THROW(out_of_range::create(401, "array index " + std::to_string(idx) + " is out of range", *this));
  18071. }
  18072. }
  18073. else
  18074. {
  18075. JSON_THROW(type_error::create(304, "cannot use at() with " + std::string(type_name()), *this));
  18076. }
  18077. }
  18078. /*!
  18079. @brief access specified object element with bounds checking
  18080. Returns a reference to the element at with specified key @a key, with
  18081. bounds checking.
  18082. @param[in] key key of the element to access
  18083. @return reference to the element at key @a key
  18084. @throw type_error.304 if the JSON value is not an object; in this case,
  18085. calling `at` with a key makes no sense. See example below.
  18086. @throw out_of_range.403 if the key @a key is is not stored in the object;
  18087. that is, `find(key) == end()`. See example below.
  18088. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  18089. changes in the JSON value.
  18090. @complexity Logarithmic in the size of the container.
  18091. @sa see @ref operator[](const typename object_t::key_type&) for unchecked
  18092. access by reference
  18093. @sa see @ref value() for access by value with a default value
  18094. @since version 1.0.0
  18095. @liveexample{The example below shows how object elements can be read and
  18096. written using `at()`. It also demonstrates the different exceptions that
  18097. can be thrown.,at__object_t_key_type}
  18098. */
  18099. reference at(const typename object_t::key_type& key)
  18100. {
  18101. // at only works for objects
  18102. if (JSON_HEDLEY_LIKELY(is_object()))
  18103. {
  18104. JSON_TRY
  18105. {
  18106. return set_parent(m_value.object->at(key));
  18107. }
  18108. JSON_CATCH (std::out_of_range&)
  18109. {
  18110. // create better exception explanation
  18111. JSON_THROW(out_of_range::create(403, "key '" + key + "' not found", *this));
  18112. }
  18113. }
  18114. else
  18115. {
  18116. JSON_THROW(type_error::create(304, "cannot use at() with " + std::string(type_name()), *this));
  18117. }
  18118. }
  18119. /*!
  18120. @brief access specified object element with bounds checking
  18121. Returns a const reference to the element at with specified key @a key,
  18122. with bounds checking.
  18123. @param[in] key key of the element to access
  18124. @return const reference to the element at key @a key
  18125. @throw type_error.304 if the JSON value is not an object; in this case,
  18126. calling `at` with a key makes no sense. See example below.
  18127. @throw out_of_range.403 if the key @a key is is not stored in the object;
  18128. that is, `find(key) == end()`. See example below.
  18129. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  18130. changes in the JSON value.
  18131. @complexity Logarithmic in the size of the container.
  18132. @sa see @ref operator[](const typename object_t::key_type&) for unchecked
  18133. access by reference
  18134. @sa see @ref value() for access by value with a default value
  18135. @since version 1.0.0
  18136. @liveexample{The example below shows how object elements can be read using
  18137. `at()`. It also demonstrates the different exceptions that can be thrown.,
  18138. at__object_t_key_type_const}
  18139. */
  18140. const_reference at(const typename object_t::key_type& key) const
  18141. {
  18142. // at only works for objects
  18143. if (JSON_HEDLEY_LIKELY(is_object()))
  18144. {
  18145. JSON_TRY
  18146. {
  18147. return m_value.object->at(key);
  18148. }
  18149. JSON_CATCH (std::out_of_range&)
  18150. {
  18151. // create better exception explanation
  18152. JSON_THROW(out_of_range::create(403, "key '" + key + "' not found", *this));
  18153. }
  18154. }
  18155. else
  18156. {
  18157. JSON_THROW(type_error::create(304, "cannot use at() with " + std::string(type_name()), *this));
  18158. }
  18159. }
  18160. /*!
  18161. @brief access specified array element
  18162. Returns a reference to the element at specified location @a idx.
  18163. @note If @a idx is beyond the range of the array (i.e., `idx >= size()`),
  18164. then the array is silently filled up with `null` values to make `idx` a
  18165. valid reference to the last stored element.
  18166. @param[in] idx index of the element to access
  18167. @return reference to the element at index @a idx
  18168. @throw type_error.305 if the JSON value is not an array or null; in that
  18169. cases, using the [] operator with an index makes no sense.
  18170. @complexity Constant if @a idx is in the range of the array. Otherwise
  18171. linear in `idx - size()`.
  18172. @liveexample{The example below shows how array elements can be read and
  18173. written using `[]` operator. Note the addition of `null`
  18174. values.,operatorarray__size_type}
  18175. @since version 1.0.0
  18176. */
  18177. reference operator[](size_type idx)
  18178. {
  18179. // implicitly convert null value to an empty array
  18180. if (is_null())
  18181. {
  18182. m_type = value_t::array;
  18183. m_value.array = create<array_t>();
  18184. assert_invariant();
  18185. }
  18186. // operator[] only works for arrays
  18187. if (JSON_HEDLEY_LIKELY(is_array()))
  18188. {
  18189. // fill up array with null values if given idx is outside range
  18190. if (idx >= m_value.array->size())
  18191. {
  18192. #if JSON_DIAGNOSTICS
  18193. // remember array size & capacity before resizing
  18194. const auto old_size = m_value.array->size();
  18195. const auto old_capacity = m_value.array->capacity();
  18196. #endif
  18197. m_value.array->resize(idx + 1);
  18198. #if JSON_DIAGNOSTICS
  18199. if (JSON_HEDLEY_UNLIKELY(m_value.array->capacity() != old_capacity))
  18200. {
  18201. // capacity has changed: update all parents
  18202. set_parents();
  18203. }
  18204. else
  18205. {
  18206. // set parent for values added above
  18207. set_parents(begin() + static_cast<typename iterator::difference_type>(old_size), static_cast<typename iterator::difference_type>(idx + 1 - old_size));
  18208. }
  18209. #endif
  18210. assert_invariant();
  18211. }
  18212. return m_value.array->operator[](idx);
  18213. }
  18214. JSON_THROW(type_error::create(305, "cannot use operator[] with a numeric argument with " + std::string(type_name()), *this));
  18215. }
  18216. /*!
  18217. @brief access specified array element
  18218. Returns a const reference to the element at specified location @a idx.
  18219. @param[in] idx index of the element to access
  18220. @return const reference to the element at index @a idx
  18221. @throw type_error.305 if the JSON value is not an array; in that case,
  18222. using the [] operator with an index makes no sense.
  18223. @complexity Constant.
  18224. @liveexample{The example below shows how array elements can be read using
  18225. the `[]` operator.,operatorarray__size_type_const}
  18226. @since version 1.0.0
  18227. */
  18228. const_reference operator[](size_type idx) const
  18229. {
  18230. // const operator[] only works for arrays
  18231. if (JSON_HEDLEY_LIKELY(is_array()))
  18232. {
  18233. return m_value.array->operator[](idx);
  18234. }
  18235. JSON_THROW(type_error::create(305, "cannot use operator[] with a numeric argument with " + std::string(type_name()), *this));
  18236. }
  18237. /*!
  18238. @brief access specified object element
  18239. Returns a reference to the element at with specified key @a key.
  18240. @note If @a key is not found in the object, then it is silently added to
  18241. the object and filled with a `null` value to make `key` a valid reference.
  18242. In case the value was `null` before, it is converted to an object.
  18243. @param[in] key key of the element to access
  18244. @return reference to the element at key @a key
  18245. @throw type_error.305 if the JSON value is not an object or null; in that
  18246. cases, using the [] operator with a key makes no sense.
  18247. @complexity Logarithmic in the size of the container.
  18248. @liveexample{The example below shows how object elements can be read and
  18249. written using the `[]` operator.,operatorarray__key_type}
  18250. @sa see @ref at(const typename object_t::key_type&) for access by reference
  18251. with range checking
  18252. @sa see @ref value() for access by value with a default value
  18253. @since version 1.0.0
  18254. */
  18255. reference operator[](const typename object_t::key_type& key)
  18256. {
  18257. // implicitly convert null value to an empty object
  18258. if (is_null())
  18259. {
  18260. m_type = value_t::object;
  18261. m_value.object = create<object_t>();
  18262. assert_invariant();
  18263. }
  18264. // operator[] only works for objects
  18265. if (JSON_HEDLEY_LIKELY(is_object()))
  18266. {
  18267. return set_parent(m_value.object->operator[](key));
  18268. }
  18269. JSON_THROW(type_error::create(305, "cannot use operator[] with a string argument with " + std::string(type_name()), *this));
  18270. }
  18271. /*!
  18272. @brief read-only access specified object element
  18273. Returns a const reference to the element at with specified key @a key. No
  18274. bounds checking is performed.
  18275. @warning If the element with key @a key does not exist, the behavior is
  18276. undefined.
  18277. @param[in] key key of the element to access
  18278. @return const reference to the element at key @a key
  18279. @pre The element with key @a key must exist. **This precondition is
  18280. enforced with an assertion.**
  18281. @throw type_error.305 if the JSON value is not an object; in that case,
  18282. using the [] operator with a key makes no sense.
  18283. @complexity Logarithmic in the size of the container.
  18284. @liveexample{The example below shows how object elements can be read using
  18285. the `[]` operator.,operatorarray__key_type_const}
  18286. @sa see @ref at(const typename object_t::key_type&) for access by reference
  18287. with range checking
  18288. @sa see @ref value() for access by value with a default value
  18289. @since version 1.0.0
  18290. */
  18291. const_reference operator[](const typename object_t::key_type& key) const
  18292. {
  18293. // const operator[] only works for objects
  18294. if (JSON_HEDLEY_LIKELY(is_object()))
  18295. {
  18296. JSON_ASSERT(m_value.object->find(key) != m_value.object->end());
  18297. return m_value.object->find(key)->second;
  18298. }
  18299. JSON_THROW(type_error::create(305, "cannot use operator[] with a string argument with " + std::string(type_name()), *this));
  18300. }
  18301. /*!
  18302. @brief access specified object element
  18303. Returns a reference to the element at with specified key @a key.
  18304. @note If @a key is not found in the object, then it is silently added to
  18305. the object and filled with a `null` value to make `key` a valid reference.
  18306. In case the value was `null` before, it is converted to an object.
  18307. @param[in] key key of the element to access
  18308. @return reference to the element at key @a key
  18309. @throw type_error.305 if the JSON value is not an object or null; in that
  18310. cases, using the [] operator with a key makes no sense.
  18311. @complexity Logarithmic in the size of the container.
  18312. @liveexample{The example below shows how object elements can be read and
  18313. written using the `[]` operator.,operatorarray__key_type}
  18314. @sa see @ref at(const typename object_t::key_type&) for access by reference
  18315. with range checking
  18316. @sa see @ref value() for access by value with a default value
  18317. @since version 1.1.0
  18318. */
  18319. template<typename T>
  18320. JSON_HEDLEY_NON_NULL(2)
  18321. reference operator[](T* key)
  18322. {
  18323. // implicitly convert null to object
  18324. if (is_null())
  18325. {
  18326. m_type = value_t::object;
  18327. m_value = value_t::object;
  18328. assert_invariant();
  18329. }
  18330. // at only works for objects
  18331. if (JSON_HEDLEY_LIKELY(is_object()))
  18332. {
  18333. return set_parent(m_value.object->operator[](key));
  18334. }
  18335. JSON_THROW(type_error::create(305, "cannot use operator[] with a string argument with " + std::string(type_name()), *this));
  18336. }
  18337. /*!
  18338. @brief read-only access specified object element
  18339. Returns a const reference to the element at with specified key @a key. No
  18340. bounds checking is performed.
  18341. @warning If the element with key @a key does not exist, the behavior is
  18342. undefined.
  18343. @param[in] key key of the element to access
  18344. @return const reference to the element at key @a key
  18345. @pre The element with key @a key must exist. **This precondition is
  18346. enforced with an assertion.**
  18347. @throw type_error.305 if the JSON value is not an object; in that case,
  18348. using the [] operator with a key makes no sense.
  18349. @complexity Logarithmic in the size of the container.
  18350. @liveexample{The example below shows how object elements can be read using
  18351. the `[]` operator.,operatorarray__key_type_const}
  18352. @sa see @ref at(const typename object_t::key_type&) for access by reference
  18353. with range checking
  18354. @sa see @ref value() for access by value with a default value
  18355. @since version 1.1.0
  18356. */
  18357. template<typename T>
  18358. JSON_HEDLEY_NON_NULL(2)
  18359. const_reference operator[](T* key) const
  18360. {
  18361. // at only works for objects
  18362. if (JSON_HEDLEY_LIKELY(is_object()))
  18363. {
  18364. JSON_ASSERT(m_value.object->find(key) != m_value.object->end());
  18365. return m_value.object->find(key)->second;
  18366. }
  18367. JSON_THROW(type_error::create(305, "cannot use operator[] with a string argument with " + std::string(type_name()), *this));
  18368. }
  18369. /*!
  18370. @brief access specified object element with default value
  18371. Returns either a copy of an object's element at the specified key @a key
  18372. or a given default value if no element with key @a key exists.
  18373. The function is basically equivalent to executing
  18374. @code {.cpp}
  18375. try {
  18376. return at(key);
  18377. } catch(out_of_range) {
  18378. return default_value;
  18379. }
  18380. @endcode
  18381. @note Unlike @ref at(const typename object_t::key_type&), this function
  18382. does not throw if the given key @a key was not found.
  18383. @note Unlike @ref operator[](const typename object_t::key_type& key), this
  18384. function does not implicitly add an element to the position defined by @a
  18385. key. This function is furthermore also applicable to const objects.
  18386. @param[in] key key of the element to access
  18387. @param[in] default_value the value to return if @a key is not found
  18388. @tparam ValueType type compatible to JSON values, for instance `int` for
  18389. JSON integer numbers, `bool` for JSON booleans, or `std::vector` types for
  18390. JSON arrays. Note the type of the expected value at @a key and the default
  18391. value @a default_value must be compatible.
  18392. @return copy of the element at key @a key or @a default_value if @a key
  18393. is not found
  18394. @throw type_error.302 if @a default_value does not match the type of the
  18395. value at @a key
  18396. @throw type_error.306 if the JSON value is not an object; in that case,
  18397. using `value()` with a key makes no sense.
  18398. @complexity Logarithmic in the size of the container.
  18399. @liveexample{The example below shows how object elements can be queried
  18400. with a default value.,basic_json__value}
  18401. @sa see @ref at(const typename object_t::key_type&) for access by reference
  18402. with range checking
  18403. @sa see @ref operator[](const typename object_t::key_type&) for unchecked
  18404. access by reference
  18405. @since version 1.0.0
  18406. */
  18407. // using std::is_convertible in a std::enable_if will fail when using explicit conversions
  18408. template < class ValueType, typename std::enable_if <
  18409. detail::is_getable<basic_json_t, ValueType>::value
  18410. && !std::is_same<value_t, ValueType>::value, int >::type = 0 >
  18411. ValueType value(const typename object_t::key_type& key, const ValueType& default_value) const
  18412. {
  18413. // at only works for objects
  18414. if (JSON_HEDLEY_LIKELY(is_object()))
  18415. {
  18416. // if key is found, return value and given default value otherwise
  18417. const auto it = find(key);
  18418. if (it != end())
  18419. {
  18420. return it->template get<ValueType>();
  18421. }
  18422. return default_value;
  18423. }
  18424. JSON_THROW(type_error::create(306, "cannot use value() with " + std::string(type_name()), *this));
  18425. }
  18426. /*!
  18427. @brief overload for a default value of type const char*
  18428. @copydoc basic_json::value(const typename object_t::key_type&, const ValueType&) const
  18429. */
  18430. string_t value(const typename object_t::key_type& key, const char* default_value) const
  18431. {
  18432. return value(key, string_t(default_value));
  18433. }
  18434. /*!
  18435. @brief access specified object element via JSON Pointer with default value
  18436. Returns either a copy of an object's element at the specified key @a key
  18437. or a given default value if no element with key @a key exists.
  18438. The function is basically equivalent to executing
  18439. @code {.cpp}
  18440. try {
  18441. return at(ptr);
  18442. } catch(out_of_range) {
  18443. return default_value;
  18444. }
  18445. @endcode
  18446. @note Unlike @ref at(const json_pointer&), this function does not throw
  18447. if the given key @a key was not found.
  18448. @param[in] ptr a JSON pointer to the element to access
  18449. @param[in] default_value the value to return if @a ptr found no value
  18450. @tparam ValueType type compatible to JSON values, for instance `int` for
  18451. JSON integer numbers, `bool` for JSON booleans, or `std::vector` types for
  18452. JSON arrays. Note the type of the expected value at @a key and the default
  18453. value @a default_value must be compatible.
  18454. @return copy of the element at key @a key or @a default_value if @a key
  18455. is not found
  18456. @throw type_error.302 if @a default_value does not match the type of the
  18457. value at @a ptr
  18458. @throw type_error.306 if the JSON value is not an object; in that case,
  18459. using `value()` with a key makes no sense.
  18460. @complexity Logarithmic in the size of the container.
  18461. @liveexample{The example below shows how object elements can be queried
  18462. with a default value.,basic_json__value_ptr}
  18463. @sa see @ref operator[](const json_pointer&) for unchecked access by reference
  18464. @since version 2.0.2
  18465. */
  18466. template<class ValueType, typename std::enable_if<
  18467. detail::is_getable<basic_json_t, ValueType>::value, int>::type = 0>
  18468. ValueType value(const json_pointer& ptr, const ValueType& default_value) const
  18469. {
  18470. // at only works for objects
  18471. if (JSON_HEDLEY_LIKELY(is_object()))
  18472. {
  18473. // if pointer resolves a value, return it or use default value
  18474. JSON_TRY
  18475. {
  18476. return ptr.get_checked(this).template get<ValueType>();
  18477. }
  18478. JSON_INTERNAL_CATCH (out_of_range&)
  18479. {
  18480. return default_value;
  18481. }
  18482. }
  18483. JSON_THROW(type_error::create(306, "cannot use value() with " + std::string(type_name()), *this));
  18484. }
  18485. /*!
  18486. @brief overload for a default value of type const char*
  18487. @copydoc basic_json::value(const json_pointer&, ValueType) const
  18488. */
  18489. JSON_HEDLEY_NON_NULL(3)
  18490. string_t value(const json_pointer& ptr, const char* default_value) const
  18491. {
  18492. return value(ptr, string_t(default_value));
  18493. }
  18494. /*!
  18495. @brief access the first element
  18496. Returns a reference to the first element in the container. For a JSON
  18497. container `c`, the expression `c.front()` is equivalent to `*c.begin()`.
  18498. @return In case of a structured type (array or object), a reference to the
  18499. first element is returned. In case of number, string, boolean, or binary
  18500. values, a reference to the value is returned.
  18501. @complexity Constant.
  18502. @pre The JSON value must not be `null` (would throw `std::out_of_range`)
  18503. or an empty array or object (undefined behavior, **guarded by
  18504. assertions**).
  18505. @post The JSON value remains unchanged.
  18506. @throw invalid_iterator.214 when called on `null` value
  18507. @liveexample{The following code shows an example for `front()`.,front}
  18508. @sa see @ref back() -- access the last element
  18509. @since version 1.0.0
  18510. */
  18511. reference front()
  18512. {
  18513. return *begin();
  18514. }
  18515. /*!
  18516. @copydoc basic_json::front()
  18517. */
  18518. const_reference front() const
  18519. {
  18520. return *cbegin();
  18521. }
  18522. /*!
  18523. @brief access the last element
  18524. Returns a reference to the last element in the container. For a JSON
  18525. container `c`, the expression `c.back()` is equivalent to
  18526. @code {.cpp}
  18527. auto tmp = c.end();
  18528. --tmp;
  18529. return *tmp;
  18530. @endcode
  18531. @return In case of a structured type (array or object), a reference to the
  18532. last element is returned. In case of number, string, boolean, or binary
  18533. values, a reference to the value is returned.
  18534. @complexity Constant.
  18535. @pre The JSON value must not be `null` (would throw `std::out_of_range`)
  18536. or an empty array or object (undefined behavior, **guarded by
  18537. assertions**).
  18538. @post The JSON value remains unchanged.
  18539. @throw invalid_iterator.214 when called on a `null` value. See example
  18540. below.
  18541. @liveexample{The following code shows an example for `back()`.,back}
  18542. @sa see @ref front() -- access the first element
  18543. @since version 1.0.0
  18544. */
  18545. reference back()
  18546. {
  18547. auto tmp = end();
  18548. --tmp;
  18549. return *tmp;
  18550. }
  18551. /*!
  18552. @copydoc basic_json::back()
  18553. */
  18554. const_reference back() const
  18555. {
  18556. auto tmp = cend();
  18557. --tmp;
  18558. return *tmp;
  18559. }
  18560. /*!
  18561. @brief remove element given an iterator
  18562. Removes the element specified by iterator @a pos. The iterator @a pos must
  18563. be valid and dereferenceable. Thus the `end()` iterator (which is valid,
  18564. but is not dereferenceable) cannot be used as a value for @a pos.
  18565. If called on a primitive type other than `null`, the resulting JSON value
  18566. will be `null`.
  18567. @param[in] pos iterator to the element to remove
  18568. @return Iterator following the last removed element. If the iterator @a
  18569. pos refers to the last element, the `end()` iterator is returned.
  18570. @tparam IteratorType an @ref iterator or @ref const_iterator
  18571. @post Invalidates iterators and references at or after the point of the
  18572. erase, including the `end()` iterator.
  18573. @throw type_error.307 if called on a `null` value; example: `"cannot use
  18574. erase() with null"`
  18575. @throw invalid_iterator.202 if called on an iterator which does not belong
  18576. to the current JSON value; example: `"iterator does not fit current
  18577. value"`
  18578. @throw invalid_iterator.205 if called on a primitive type with invalid
  18579. iterator (i.e., any iterator which is not `begin()`); example: `"iterator
  18580. out of range"`
  18581. @complexity The complexity depends on the type:
  18582. - objects: amortized constant
  18583. - arrays: linear in distance between @a pos and the end of the container
  18584. - strings and binary: linear in the length of the member
  18585. - other types: constant
  18586. @liveexample{The example shows the result of `erase()` for different JSON
  18587. types.,erase__IteratorType}
  18588. @sa see @ref erase(IteratorType, IteratorType) -- removes the elements in
  18589. the given range
  18590. @sa see @ref erase(const typename object_t::key_type&) -- removes the element
  18591. from an object at the given key
  18592. @sa see @ref erase(const size_type) -- removes the element from an array at
  18593. the given index
  18594. @since version 1.0.0
  18595. */
  18596. template < class IteratorType, typename std::enable_if <
  18597. std::is_same<IteratorType, typename basic_json_t::iterator>::value ||
  18598. std::is_same<IteratorType, typename basic_json_t::const_iterator>::value, int >::type
  18599. = 0 >
  18600. IteratorType erase(IteratorType pos)
  18601. {
  18602. // make sure iterator fits the current value
  18603. if (JSON_HEDLEY_UNLIKELY(this != pos.m_object))
  18604. {
  18605. JSON_THROW(invalid_iterator::create(202, "iterator does not fit current value", *this));
  18606. }
  18607. IteratorType result = end();
  18608. switch (m_type)
  18609. {
  18610. case value_t::boolean:
  18611. case value_t::number_float:
  18612. case value_t::number_integer:
  18613. case value_t::number_unsigned:
  18614. case value_t::string:
  18615. case value_t::binary:
  18616. {
  18617. if (JSON_HEDLEY_UNLIKELY(!pos.m_it.primitive_iterator.is_begin()))
  18618. {
  18619. JSON_THROW(invalid_iterator::create(205, "iterator out of range", *this));
  18620. }
  18621. if (is_string())
  18622. {
  18623. AllocatorType<string_t> alloc;
  18624. std::allocator_traits<decltype(alloc)>::destroy(alloc, m_value.string);
  18625. std::allocator_traits<decltype(alloc)>::deallocate(alloc, m_value.string, 1);
  18626. m_value.string = nullptr;
  18627. }
  18628. else if (is_binary())
  18629. {
  18630. AllocatorType<binary_t> alloc;
  18631. std::allocator_traits<decltype(alloc)>::destroy(alloc, m_value.binary);
  18632. std::allocator_traits<decltype(alloc)>::deallocate(alloc, m_value.binary, 1);
  18633. m_value.binary = nullptr;
  18634. }
  18635. m_type = value_t::null;
  18636. assert_invariant();
  18637. break;
  18638. }
  18639. case value_t::object:
  18640. {
  18641. result.m_it.object_iterator = m_value.object->erase(pos.m_it.object_iterator);
  18642. break;
  18643. }
  18644. case value_t::array:
  18645. {
  18646. result.m_it.array_iterator = m_value.array->erase(pos.m_it.array_iterator);
  18647. break;
  18648. }
  18649. case value_t::null:
  18650. case value_t::discarded:
  18651. default:
  18652. JSON_THROW(type_error::create(307, "cannot use erase() with " + std::string(type_name()), *this));
  18653. }
  18654. return result;
  18655. }
  18656. /*!
  18657. @brief remove elements given an iterator range
  18658. Removes the element specified by the range `[first; last)`. The iterator
  18659. @a first does not need to be dereferenceable if `first == last`: erasing
  18660. an empty range is a no-op.
  18661. If called on a primitive type other than `null`, the resulting JSON value
  18662. will be `null`.
  18663. @param[in] first iterator to the beginning of the range to remove
  18664. @param[in] last iterator past the end of the range to remove
  18665. @return Iterator following the last removed element. If the iterator @a
  18666. second refers to the last element, the `end()` iterator is returned.
  18667. @tparam IteratorType an @ref iterator or @ref const_iterator
  18668. @post Invalidates iterators and references at or after the point of the
  18669. erase, including the `end()` iterator.
  18670. @throw type_error.307 if called on a `null` value; example: `"cannot use
  18671. erase() with null"`
  18672. @throw invalid_iterator.203 if called on iterators which does not belong
  18673. to the current JSON value; example: `"iterators do not fit current value"`
  18674. @throw invalid_iterator.204 if called on a primitive type with invalid
  18675. iterators (i.e., if `first != begin()` and `last != end()`); example:
  18676. `"iterators out of range"`
  18677. @complexity The complexity depends on the type:
  18678. - objects: `log(size()) + std::distance(first, last)`
  18679. - arrays: linear in the distance between @a first and @a last, plus linear
  18680. in the distance between @a last and end of the container
  18681. - strings and binary: linear in the length of the member
  18682. - other types: constant
  18683. @liveexample{The example shows the result of `erase()` for different JSON
  18684. types.,erase__IteratorType_IteratorType}
  18685. @sa see @ref erase(IteratorType) -- removes the element at a given position
  18686. @sa see @ref erase(const typename object_t::key_type&) -- removes the element
  18687. from an object at the given key
  18688. @sa see @ref erase(const size_type) -- removes the element from an array at
  18689. the given index
  18690. @since version 1.0.0
  18691. */
  18692. template < class IteratorType, typename std::enable_if <
  18693. std::is_same<IteratorType, typename basic_json_t::iterator>::value ||
  18694. std::is_same<IteratorType, typename basic_json_t::const_iterator>::value, int >::type
  18695. = 0 >
  18696. IteratorType erase(IteratorType first, IteratorType last)
  18697. {
  18698. // make sure iterator fits the current value
  18699. if (JSON_HEDLEY_UNLIKELY(this != first.m_object || this != last.m_object))
  18700. {
  18701. JSON_THROW(invalid_iterator::create(203, "iterators do not fit current value", *this));
  18702. }
  18703. IteratorType result = end();
  18704. switch (m_type)
  18705. {
  18706. case value_t::boolean:
  18707. case value_t::number_float:
  18708. case value_t::number_integer:
  18709. case value_t::number_unsigned:
  18710. case value_t::string:
  18711. case value_t::binary:
  18712. {
  18713. if (JSON_HEDLEY_LIKELY(!first.m_it.primitive_iterator.is_begin()
  18714. || !last.m_it.primitive_iterator.is_end()))
  18715. {
  18716. JSON_THROW(invalid_iterator::create(204, "iterators out of range", *this));
  18717. }
  18718. if (is_string())
  18719. {
  18720. AllocatorType<string_t> alloc;
  18721. std::allocator_traits<decltype(alloc)>::destroy(alloc, m_value.string);
  18722. std::allocator_traits<decltype(alloc)>::deallocate(alloc, m_value.string, 1);
  18723. m_value.string = nullptr;
  18724. }
  18725. else if (is_binary())
  18726. {
  18727. AllocatorType<binary_t> alloc;
  18728. std::allocator_traits<decltype(alloc)>::destroy(alloc, m_value.binary);
  18729. std::allocator_traits<decltype(alloc)>::deallocate(alloc, m_value.binary, 1);
  18730. m_value.binary = nullptr;
  18731. }
  18732. m_type = value_t::null;
  18733. assert_invariant();
  18734. break;
  18735. }
  18736. case value_t::object:
  18737. {
  18738. result.m_it.object_iterator = m_value.object->erase(first.m_it.object_iterator,
  18739. last.m_it.object_iterator);
  18740. break;
  18741. }
  18742. case value_t::array:
  18743. {
  18744. result.m_it.array_iterator = m_value.array->erase(first.m_it.array_iterator,
  18745. last.m_it.array_iterator);
  18746. break;
  18747. }
  18748. case value_t::null:
  18749. case value_t::discarded:
  18750. default:
  18751. JSON_THROW(type_error::create(307, "cannot use erase() with " + std::string(type_name()), *this));
  18752. }
  18753. return result;
  18754. }
  18755. /*!
  18756. @brief remove element from a JSON object given a key
  18757. Removes elements from a JSON object with the key value @a key.
  18758. @param[in] key value of the elements to remove
  18759. @return Number of elements removed. If @a ObjectType is the default
  18760. `std::map` type, the return value will always be `0` (@a key was not
  18761. found) or `1` (@a key was found).
  18762. @post References and iterators to the erased elements are invalidated.
  18763. Other references and iterators are not affected.
  18764. @throw type_error.307 when called on a type other than JSON object;
  18765. example: `"cannot use erase() with null"`
  18766. @complexity `log(size()) + count(key)`
  18767. @liveexample{The example shows the effect of `erase()`.,erase__key_type}
  18768. @sa see @ref erase(IteratorType) -- removes the element at a given position
  18769. @sa see @ref erase(IteratorType, IteratorType) -- removes the elements in
  18770. the given range
  18771. @sa see @ref erase(const size_type) -- removes the element from an array at
  18772. the given index
  18773. @since version 1.0.0
  18774. */
  18775. size_type erase(const typename object_t::key_type& key)
  18776. {
  18777. // this erase only works for objects
  18778. if (JSON_HEDLEY_LIKELY(is_object()))
  18779. {
  18780. return m_value.object->erase(key);
  18781. }
  18782. JSON_THROW(type_error::create(307, "cannot use erase() with " + std::string(type_name()), *this));
  18783. }
  18784. /*!
  18785. @brief remove element from a JSON array given an index
  18786. Removes element from a JSON array at the index @a idx.
  18787. @param[in] idx index of the element to remove
  18788. @throw type_error.307 when called on a type other than JSON object;
  18789. example: `"cannot use erase() with null"`
  18790. @throw out_of_range.401 when `idx >= size()`; example: `"array index 17
  18791. is out of range"`
  18792. @complexity Linear in distance between @a idx and the end of the container.
  18793. @liveexample{The example shows the effect of `erase()`.,erase__size_type}
  18794. @sa see @ref erase(IteratorType) -- removes the element at a given position
  18795. @sa see @ref erase(IteratorType, IteratorType) -- removes the elements in
  18796. the given range
  18797. @sa see @ref erase(const typename object_t::key_type&) -- removes the element
  18798. from an object at the given key
  18799. @since version 1.0.0
  18800. */
  18801. void erase(const size_type idx)
  18802. {
  18803. // this erase only works for arrays
  18804. if (JSON_HEDLEY_LIKELY(is_array()))
  18805. {
  18806. if (JSON_HEDLEY_UNLIKELY(idx >= size()))
  18807. {
  18808. JSON_THROW(out_of_range::create(401, "array index " + std::to_string(idx) + " is out of range", *this));
  18809. }
  18810. m_value.array->erase(m_value.array->begin() + static_cast<difference_type>(idx));
  18811. }
  18812. else
  18813. {
  18814. JSON_THROW(type_error::create(307, "cannot use erase() with " + std::string(type_name()), *this));
  18815. }
  18816. }
  18817. /// @}
  18818. ////////////
  18819. // lookup //
  18820. ////////////
  18821. /// @name lookup
  18822. /// @{
  18823. /*!
  18824. @brief find an element in a JSON object
  18825. Finds an element in a JSON object with key equivalent to @a key. If the
  18826. element is not found or the JSON value is not an object, end() is
  18827. returned.
  18828. @note This method always returns @ref end() when executed on a JSON type
  18829. that is not an object.
  18830. @param[in] key key value of the element to search for.
  18831. @return Iterator to an element with key equivalent to @a key. If no such
  18832. element is found or the JSON value is not an object, past-the-end (see
  18833. @ref end()) iterator is returned.
  18834. @complexity Logarithmic in the size of the JSON object.
  18835. @liveexample{The example shows how `find()` is used.,find__key_type}
  18836. @sa see @ref contains(KeyT&&) const -- checks whether a key exists
  18837. @since version 1.0.0
  18838. */
  18839. template<typename KeyT>
  18840. iterator find(KeyT&& key)
  18841. {
  18842. auto result = end();
  18843. if (is_object())
  18844. {
  18845. result.m_it.object_iterator = m_value.object->find(std::forward<KeyT>(key));
  18846. }
  18847. return result;
  18848. }
  18849. /*!
  18850. @brief find an element in a JSON object
  18851. @copydoc find(KeyT&&)
  18852. */
  18853. template<typename KeyT>
  18854. const_iterator find(KeyT&& key) const
  18855. {
  18856. auto result = cend();
  18857. if (is_object())
  18858. {
  18859. result.m_it.object_iterator = m_value.object->find(std::forward<KeyT>(key));
  18860. }
  18861. return result;
  18862. }
  18863. /*!
  18864. @brief returns the number of occurrences of a key in a JSON object
  18865. Returns the number of elements with key @a key. If ObjectType is the
  18866. default `std::map` type, the return value will always be `0` (@a key was
  18867. not found) or `1` (@a key was found).
  18868. @note This method always returns `0` when executed on a JSON type that is
  18869. not an object.
  18870. @param[in] key key value of the element to count
  18871. @return Number of elements with key @a key. If the JSON value is not an
  18872. object, the return value will be `0`.
  18873. @complexity Logarithmic in the size of the JSON object.
  18874. @liveexample{The example shows how `count()` is used.,count}
  18875. @since version 1.0.0
  18876. */
  18877. template<typename KeyT>
  18878. size_type count(KeyT&& key) const
  18879. {
  18880. // return 0 for all nonobject types
  18881. return is_object() ? m_value.object->count(std::forward<KeyT>(key)) : 0;
  18882. }
  18883. /*!
  18884. @brief check the existence of an element in a JSON object
  18885. Check whether an element exists in a JSON object with key equivalent to
  18886. @a key. If the element is not found or the JSON value is not an object,
  18887. false is returned.
  18888. @note This method always returns false when executed on a JSON type
  18889. that is not an object.
  18890. @param[in] key key value to check its existence.
  18891. @return true if an element with specified @a key exists. If no such
  18892. element with such key is found or the JSON value is not an object,
  18893. false is returned.
  18894. @complexity Logarithmic in the size of the JSON object.
  18895. @liveexample{The following code shows an example for `contains()`.,contains}
  18896. @sa see @ref find(KeyT&&) -- returns an iterator to an object element
  18897. @sa see @ref contains(const json_pointer&) const -- checks the existence for a JSON pointer
  18898. @since version 3.6.0
  18899. */
  18900. template < typename KeyT, typename std::enable_if <
  18901. !std::is_same<typename std::decay<KeyT>::type, json_pointer>::value, int >::type = 0 >
  18902. bool contains(KeyT && key) const
  18903. {
  18904. return is_object() && m_value.object->find(std::forward<KeyT>(key)) != m_value.object->end();
  18905. }
  18906. /*!
  18907. @brief check the existence of an element in a JSON object given a JSON pointer
  18908. Check whether the given JSON pointer @a ptr can be resolved in the current
  18909. JSON value.
  18910. @note This method can be executed on any JSON value type.
  18911. @param[in] ptr JSON pointer to check its existence.
  18912. @return true if the JSON pointer can be resolved to a stored value, false
  18913. otherwise.
  18914. @post If `j.contains(ptr)` returns true, it is safe to call `j[ptr]`.
  18915. @throw parse_error.106 if an array index begins with '0'
  18916. @throw parse_error.109 if an array index was not a number
  18917. @complexity Logarithmic in the size of the JSON object.
  18918. @liveexample{The following code shows an example for `contains()`.,contains_json_pointer}
  18919. @sa see @ref contains(KeyT &&) const -- checks the existence of a key
  18920. @since version 3.7.0
  18921. */
  18922. bool contains(const json_pointer& ptr) const
  18923. {
  18924. return ptr.contains(this);
  18925. }
  18926. /// @}
  18927. ///////////////
  18928. // iterators //
  18929. ///////////////
  18930. /// @name iterators
  18931. /// @{
  18932. /*!
  18933. @brief returns an iterator to the first element
  18934. Returns an iterator to the first element.
  18935. @image html range-begin-end.svg "Illustration from cppreference.com"
  18936. @return iterator to the first element
  18937. @complexity Constant.
  18938. @requirement This function helps `basic_json` satisfying the
  18939. [Container](https://en.cppreference.com/w/cpp/named_req/Container)
  18940. requirements:
  18941. - The complexity is constant.
  18942. @liveexample{The following code shows an example for `begin()`.,begin}
  18943. @sa see @ref cbegin() -- returns a const iterator to the beginning
  18944. @sa see @ref end() -- returns an iterator to the end
  18945. @sa see @ref cend() -- returns a const iterator to the end
  18946. @since version 1.0.0
  18947. */
  18948. iterator begin() noexcept
  18949. {
  18950. iterator result(this);
  18951. result.set_begin();
  18952. return result;
  18953. }
  18954. /*!
  18955. @copydoc basic_json::cbegin()
  18956. */
  18957. const_iterator begin() const noexcept
  18958. {
  18959. return cbegin();
  18960. }
  18961. /*!
  18962. @brief returns a const iterator to the first element
  18963. Returns a const iterator to the first element.
  18964. @image html range-begin-end.svg "Illustration from cppreference.com"
  18965. @return const iterator to the first element
  18966. @complexity Constant.
  18967. @requirement This function helps `basic_json` satisfying the
  18968. [Container](https://en.cppreference.com/w/cpp/named_req/Container)
  18969. requirements:
  18970. - The complexity is constant.
  18971. - Has the semantics of `const_cast<const basic_json&>(*this).begin()`.
  18972. @liveexample{The following code shows an example for `cbegin()`.,cbegin}
  18973. @sa see @ref begin() -- returns an iterator to the beginning
  18974. @sa see @ref end() -- returns an iterator to the end
  18975. @sa see @ref cend() -- returns a const iterator to the end
  18976. @since version 1.0.0
  18977. */
  18978. const_iterator cbegin() const noexcept
  18979. {
  18980. const_iterator result(this);
  18981. result.set_begin();
  18982. return result;
  18983. }
  18984. /*!
  18985. @brief returns an iterator to one past the last element
  18986. Returns an iterator to one past the last element.
  18987. @image html range-begin-end.svg "Illustration from cppreference.com"
  18988. @return iterator one past the last element
  18989. @complexity Constant.
  18990. @requirement This function helps `basic_json` satisfying the
  18991. [Container](https://en.cppreference.com/w/cpp/named_req/Container)
  18992. requirements:
  18993. - The complexity is constant.
  18994. @liveexample{The following code shows an example for `end()`.,end}
  18995. @sa see @ref cend() -- returns a const iterator to the end
  18996. @sa see @ref begin() -- returns an iterator to the beginning
  18997. @sa see @ref cbegin() -- returns a const iterator to the beginning
  18998. @since version 1.0.0
  18999. */
  19000. iterator end() noexcept
  19001. {
  19002. iterator result(this);
  19003. result.set_end();
  19004. return result;
  19005. }
  19006. /*!
  19007. @copydoc basic_json::cend()
  19008. */
  19009. const_iterator end() const noexcept
  19010. {
  19011. return cend();
  19012. }
  19013. /*!
  19014. @brief returns a const iterator to one past the last element
  19015. Returns a const iterator to one past the last element.
  19016. @image html range-begin-end.svg "Illustration from cppreference.com"
  19017. @return const iterator one past the last element
  19018. @complexity Constant.
  19019. @requirement This function helps `basic_json` satisfying the
  19020. [Container](https://en.cppreference.com/w/cpp/named_req/Container)
  19021. requirements:
  19022. - The complexity is constant.
  19023. - Has the semantics of `const_cast<const basic_json&>(*this).end()`.
  19024. @liveexample{The following code shows an example for `cend()`.,cend}
  19025. @sa see @ref end() -- returns an iterator to the end
  19026. @sa see @ref begin() -- returns an iterator to the beginning
  19027. @sa see @ref cbegin() -- returns a const iterator to the beginning
  19028. @since version 1.0.0
  19029. */
  19030. const_iterator cend() const noexcept
  19031. {
  19032. const_iterator result(this);
  19033. result.set_end();
  19034. return result;
  19035. }
  19036. /*!
  19037. @brief returns an iterator to the reverse-beginning
  19038. Returns an iterator to the reverse-beginning; that is, the last element.
  19039. @image html range-rbegin-rend.svg "Illustration from cppreference.com"
  19040. @complexity Constant.
  19041. @requirement This function helps `basic_json` satisfying the
  19042. [ReversibleContainer](https://en.cppreference.com/w/cpp/named_req/ReversibleContainer)
  19043. requirements:
  19044. - The complexity is constant.
  19045. - Has the semantics of `reverse_iterator(end())`.
  19046. @liveexample{The following code shows an example for `rbegin()`.,rbegin}
  19047. @sa see @ref crbegin() -- returns a const reverse iterator to the beginning
  19048. @sa see @ref rend() -- returns a reverse iterator to the end
  19049. @sa see @ref crend() -- returns a const reverse iterator to the end
  19050. @since version 1.0.0
  19051. */
  19052. reverse_iterator rbegin() noexcept
  19053. {
  19054. return reverse_iterator(end());
  19055. }
  19056. /*!
  19057. @copydoc basic_json::crbegin()
  19058. */
  19059. const_reverse_iterator rbegin() const noexcept
  19060. {
  19061. return crbegin();
  19062. }
  19063. /*!
  19064. @brief returns an iterator to the reverse-end
  19065. Returns an iterator to the reverse-end; that is, one before the first
  19066. element.
  19067. @image html range-rbegin-rend.svg "Illustration from cppreference.com"
  19068. @complexity Constant.
  19069. @requirement This function helps `basic_json` satisfying the
  19070. [ReversibleContainer](https://en.cppreference.com/w/cpp/named_req/ReversibleContainer)
  19071. requirements:
  19072. - The complexity is constant.
  19073. - Has the semantics of `reverse_iterator(begin())`.
  19074. @liveexample{The following code shows an example for `rend()`.,rend}
  19075. @sa see @ref crend() -- returns a const reverse iterator to the end
  19076. @sa see @ref rbegin() -- returns a reverse iterator to the beginning
  19077. @sa see @ref crbegin() -- returns a const reverse iterator to the beginning
  19078. @since version 1.0.0
  19079. */
  19080. reverse_iterator rend() noexcept
  19081. {
  19082. return reverse_iterator(begin());
  19083. }
  19084. /*!
  19085. @copydoc basic_json::crend()
  19086. */
  19087. const_reverse_iterator rend() const noexcept
  19088. {
  19089. return crend();
  19090. }
  19091. /*!
  19092. @brief returns a const reverse iterator to the last element
  19093. Returns a const iterator to the reverse-beginning; that is, the last
  19094. element.
  19095. @image html range-rbegin-rend.svg "Illustration from cppreference.com"
  19096. @complexity Constant.
  19097. @requirement This function helps `basic_json` satisfying the
  19098. [ReversibleContainer](https://en.cppreference.com/w/cpp/named_req/ReversibleContainer)
  19099. requirements:
  19100. - The complexity is constant.
  19101. - Has the semantics of `const_cast<const basic_json&>(*this).rbegin()`.
  19102. @liveexample{The following code shows an example for `crbegin()`.,crbegin}
  19103. @sa see @ref rbegin() -- returns a reverse iterator to the beginning
  19104. @sa see @ref rend() -- returns a reverse iterator to the end
  19105. @sa see @ref crend() -- returns a const reverse iterator to the end
  19106. @since version 1.0.0
  19107. */
  19108. const_reverse_iterator crbegin() const noexcept
  19109. {
  19110. return const_reverse_iterator(cend());
  19111. }
  19112. /*!
  19113. @brief returns a const reverse iterator to one before the first
  19114. Returns a const reverse iterator to the reverse-end; that is, one before
  19115. the first element.
  19116. @image html range-rbegin-rend.svg "Illustration from cppreference.com"
  19117. @complexity Constant.
  19118. @requirement This function helps `basic_json` satisfying the
  19119. [ReversibleContainer](https://en.cppreference.com/w/cpp/named_req/ReversibleContainer)
  19120. requirements:
  19121. - The complexity is constant.
  19122. - Has the semantics of `const_cast<const basic_json&>(*this).rend()`.
  19123. @liveexample{The following code shows an example for `crend()`.,crend}
  19124. @sa see @ref rend() -- returns a reverse iterator to the end
  19125. @sa see @ref rbegin() -- returns a reverse iterator to the beginning
  19126. @sa see @ref crbegin() -- returns a const reverse iterator to the beginning
  19127. @since version 1.0.0
  19128. */
  19129. const_reverse_iterator crend() const noexcept
  19130. {
  19131. return const_reverse_iterator(cbegin());
  19132. }
  19133. public:
  19134. /*!
  19135. @brief wrapper to access iterator member functions in range-based for
  19136. This function allows to access @ref iterator::key() and @ref
  19137. iterator::value() during range-based for loops. In these loops, a
  19138. reference to the JSON values is returned, so there is no access to the
  19139. underlying iterator.
  19140. For loop without iterator_wrapper:
  19141. @code{cpp}
  19142. for (auto it = j_object.begin(); it != j_object.end(); ++it)
  19143. {
  19144. std::cout << "key: " << it.key() << ", value:" << it.value() << '\n';
  19145. }
  19146. @endcode
  19147. Range-based for loop without iterator proxy:
  19148. @code{cpp}
  19149. for (auto it : j_object)
  19150. {
  19151. // "it" is of type json::reference and has no key() member
  19152. std::cout << "value: " << it << '\n';
  19153. }
  19154. @endcode
  19155. Range-based for loop with iterator proxy:
  19156. @code{cpp}
  19157. for (auto it : json::iterator_wrapper(j_object))
  19158. {
  19159. std::cout << "key: " << it.key() << ", value:" << it.value() << '\n';
  19160. }
  19161. @endcode
  19162. @note When iterating over an array, `key()` will return the index of the
  19163. element as string (see example).
  19164. @param[in] ref reference to a JSON value
  19165. @return iteration proxy object wrapping @a ref with an interface to use in
  19166. range-based for loops
  19167. @liveexample{The following code shows how the wrapper is used,iterator_wrapper}
  19168. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  19169. changes in the JSON value.
  19170. @complexity Constant.
  19171. @note The name of this function is not yet final and may change in the
  19172. future.
  19173. @deprecated This stream operator is deprecated and will be removed in
  19174. future 4.0.0 of the library. Please use @ref items() instead;
  19175. that is, replace `json::iterator_wrapper(j)` with `j.items()`.
  19176. */
  19177. JSON_HEDLEY_DEPRECATED_FOR(3.1.0, items())
  19178. static iteration_proxy<iterator> iterator_wrapper(reference ref) noexcept
  19179. {
  19180. return ref.items();
  19181. }
  19182. /*!
  19183. @copydoc iterator_wrapper(reference)
  19184. */
  19185. JSON_HEDLEY_DEPRECATED_FOR(3.1.0, items())
  19186. static iteration_proxy<const_iterator> iterator_wrapper(const_reference ref) noexcept
  19187. {
  19188. return ref.items();
  19189. }
  19190. /*!
  19191. @brief helper to access iterator member functions in range-based for
  19192. This function allows to access @ref iterator::key() and @ref
  19193. iterator::value() during range-based for loops. In these loops, a
  19194. reference to the JSON values is returned, so there is no access to the
  19195. underlying iterator.
  19196. For loop without `items()` function:
  19197. @code{cpp}
  19198. for (auto it = j_object.begin(); it != j_object.end(); ++it)
  19199. {
  19200. std::cout << "key: " << it.key() << ", value:" << it.value() << '\n';
  19201. }
  19202. @endcode
  19203. Range-based for loop without `items()` function:
  19204. @code{cpp}
  19205. for (auto it : j_object)
  19206. {
  19207. // "it" is of type json::reference and has no key() member
  19208. std::cout << "value: " << it << '\n';
  19209. }
  19210. @endcode
  19211. Range-based for loop with `items()` function:
  19212. @code{cpp}
  19213. for (auto& el : j_object.items())
  19214. {
  19215. std::cout << "key: " << el.key() << ", value:" << el.value() << '\n';
  19216. }
  19217. @endcode
  19218. The `items()` function also allows to use
  19219. [structured bindings](https://en.cppreference.com/w/cpp/language/structured_binding)
  19220. (C++17):
  19221. @code{cpp}
  19222. for (auto& [key, val] : j_object.items())
  19223. {
  19224. std::cout << "key: " << key << ", value:" << val << '\n';
  19225. }
  19226. @endcode
  19227. @note When iterating over an array, `key()` will return the index of the
  19228. element as string (see example). For primitive types (e.g., numbers),
  19229. `key()` returns an empty string.
  19230. @warning Using `items()` on temporary objects is dangerous. Make sure the
  19231. object's lifetime exeeds the iteration. See
  19232. <https://github.com/nlohmann/json/issues/2040> for more
  19233. information.
  19234. @return iteration proxy object wrapping @a ref with an interface to use in
  19235. range-based for loops
  19236. @liveexample{The following code shows how the function is used.,items}
  19237. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  19238. changes in the JSON value.
  19239. @complexity Constant.
  19240. @since version 3.1.0, structured bindings support since 3.5.0.
  19241. */
  19242. iteration_proxy<iterator> items() noexcept
  19243. {
  19244. return iteration_proxy<iterator>(*this);
  19245. }
  19246. /*!
  19247. @copydoc items()
  19248. */
  19249. iteration_proxy<const_iterator> items() const noexcept
  19250. {
  19251. return iteration_proxy<const_iterator>(*this);
  19252. }
  19253. /// @}
  19254. //////////////
  19255. // capacity //
  19256. //////////////
  19257. /// @name capacity
  19258. /// @{
  19259. /*!
  19260. @brief checks whether the container is empty.
  19261. Checks if a JSON value has no elements (i.e. whether its @ref size is `0`).
  19262. @return The return value depends on the different types and is
  19263. defined as follows:
  19264. Value type | return value
  19265. ----------- | -------------
  19266. null | `true`
  19267. boolean | `false`
  19268. string | `false`
  19269. number | `false`
  19270. binary | `false`
  19271. object | result of function `object_t::empty()`
  19272. array | result of function `array_t::empty()`
  19273. @liveexample{The following code uses `empty()` to check if a JSON
  19274. object contains any elements.,empty}
  19275. @complexity Constant, as long as @ref array_t and @ref object_t satisfy
  19276. the Container concept; that is, their `empty()` functions have constant
  19277. complexity.
  19278. @iterators No changes.
  19279. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  19280. @note This function does not return whether a string stored as JSON value
  19281. is empty - it returns whether the JSON container itself is empty which is
  19282. false in the case of a string.
  19283. @requirement This function helps `basic_json` satisfying the
  19284. [Container](https://en.cppreference.com/w/cpp/named_req/Container)
  19285. requirements:
  19286. - The complexity is constant.
  19287. - Has the semantics of `begin() == end()`.
  19288. @sa see @ref size() -- returns the number of elements
  19289. @since version 1.0.0
  19290. */
  19291. bool empty() const noexcept
  19292. {
  19293. switch (m_type)
  19294. {
  19295. case value_t::null:
  19296. {
  19297. // null values are empty
  19298. return true;
  19299. }
  19300. case value_t::array:
  19301. {
  19302. // delegate call to array_t::empty()
  19303. return m_value.array->empty();
  19304. }
  19305. case value_t::object:
  19306. {
  19307. // delegate call to object_t::empty()
  19308. return m_value.object->empty();
  19309. }
  19310. case value_t::string:
  19311. case value_t::boolean:
  19312. case value_t::number_integer:
  19313. case value_t::number_unsigned:
  19314. case value_t::number_float:
  19315. case value_t::binary:
  19316. case value_t::discarded:
  19317. default:
  19318. {
  19319. // all other types are nonempty
  19320. return false;
  19321. }
  19322. }
  19323. }
  19324. /*!
  19325. @brief returns the number of elements
  19326. Returns the number of elements in a JSON value.
  19327. @return The return value depends on the different types and is
  19328. defined as follows:
  19329. Value type | return value
  19330. ----------- | -------------
  19331. null | `0`
  19332. boolean | `1`
  19333. string | `1`
  19334. number | `1`
  19335. binary | `1`
  19336. object | result of function object_t::size()
  19337. array | result of function array_t::size()
  19338. @liveexample{The following code calls `size()` on the different value
  19339. types.,size}
  19340. @complexity Constant, as long as @ref array_t and @ref object_t satisfy
  19341. the Container concept; that is, their size() functions have constant
  19342. complexity.
  19343. @iterators No changes.
  19344. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  19345. @note This function does not return the length of a string stored as JSON
  19346. value - it returns the number of elements in the JSON value which is 1 in
  19347. the case of a string.
  19348. @requirement This function helps `basic_json` satisfying the
  19349. [Container](https://en.cppreference.com/w/cpp/named_req/Container)
  19350. requirements:
  19351. - The complexity is constant.
  19352. - Has the semantics of `std::distance(begin(), end())`.
  19353. @sa see @ref empty() -- checks whether the container is empty
  19354. @sa see @ref max_size() -- returns the maximal number of elements
  19355. @since version 1.0.0
  19356. */
  19357. size_type size() const noexcept
  19358. {
  19359. switch (m_type)
  19360. {
  19361. case value_t::null:
  19362. {
  19363. // null values are empty
  19364. return 0;
  19365. }
  19366. case value_t::array:
  19367. {
  19368. // delegate call to array_t::size()
  19369. return m_value.array->size();
  19370. }
  19371. case value_t::object:
  19372. {
  19373. // delegate call to object_t::size()
  19374. return m_value.object->size();
  19375. }
  19376. case value_t::string:
  19377. case value_t::boolean:
  19378. case value_t::number_integer:
  19379. case value_t::number_unsigned:
  19380. case value_t::number_float:
  19381. case value_t::binary:
  19382. case value_t::discarded:
  19383. default:
  19384. {
  19385. // all other types have size 1
  19386. return 1;
  19387. }
  19388. }
  19389. }
  19390. /*!
  19391. @brief returns the maximum possible number of elements
  19392. Returns the maximum number of elements a JSON value is able to hold due to
  19393. system or library implementation limitations, i.e. `std::distance(begin(),
  19394. end())` for the JSON value.
  19395. @return The return value depends on the different types and is
  19396. defined as follows:
  19397. Value type | return value
  19398. ----------- | -------------
  19399. null | `0` (same as `size()`)
  19400. boolean | `1` (same as `size()`)
  19401. string | `1` (same as `size()`)
  19402. number | `1` (same as `size()`)
  19403. binary | `1` (same as `size()`)
  19404. object | result of function `object_t::max_size()`
  19405. array | result of function `array_t::max_size()`
  19406. @liveexample{The following code calls `max_size()` on the different value
  19407. types. Note the output is implementation specific.,max_size}
  19408. @complexity Constant, as long as @ref array_t and @ref object_t satisfy
  19409. the Container concept; that is, their `max_size()` functions have constant
  19410. complexity.
  19411. @iterators No changes.
  19412. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  19413. @requirement This function helps `basic_json` satisfying the
  19414. [Container](https://en.cppreference.com/w/cpp/named_req/Container)
  19415. requirements:
  19416. - The complexity is constant.
  19417. - Has the semantics of returning `b.size()` where `b` is the largest
  19418. possible JSON value.
  19419. @sa see @ref size() -- returns the number of elements
  19420. @since version 1.0.0
  19421. */
  19422. size_type max_size() const noexcept
  19423. {
  19424. switch (m_type)
  19425. {
  19426. case value_t::array:
  19427. {
  19428. // delegate call to array_t::max_size()
  19429. return m_value.array->max_size();
  19430. }
  19431. case value_t::object:
  19432. {
  19433. // delegate call to object_t::max_size()
  19434. return m_value.object->max_size();
  19435. }
  19436. case value_t::null:
  19437. case value_t::string:
  19438. case value_t::boolean:
  19439. case value_t::number_integer:
  19440. case value_t::number_unsigned:
  19441. case value_t::number_float:
  19442. case value_t::binary:
  19443. case value_t::discarded:
  19444. default:
  19445. {
  19446. // all other types have max_size() == size()
  19447. return size();
  19448. }
  19449. }
  19450. }
  19451. /// @}
  19452. ///////////////
  19453. // modifiers //
  19454. ///////////////
  19455. /// @name modifiers
  19456. /// @{
  19457. /*!
  19458. @brief clears the contents
  19459. Clears the content of a JSON value and resets it to the default value as
  19460. if @ref basic_json(value_t) would have been called with the current value
  19461. type from @ref type():
  19462. Value type | initial value
  19463. ----------- | -------------
  19464. null | `null`
  19465. boolean | `false`
  19466. string | `""`
  19467. number | `0`
  19468. binary | An empty byte vector
  19469. object | `{}`
  19470. array | `[]`
  19471. @post Has the same effect as calling
  19472. @code {.cpp}
  19473. *this = basic_json(type());
  19474. @endcode
  19475. @liveexample{The example below shows the effect of `clear()` to different
  19476. JSON types.,clear}
  19477. @complexity Linear in the size of the JSON value.
  19478. @iterators All iterators, pointers and references related to this container
  19479. are invalidated.
  19480. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  19481. @sa see @ref basic_json(value_t) -- constructor that creates an object with the
  19482. same value than calling `clear()`
  19483. @since version 1.0.0
  19484. */
  19485. void clear() noexcept
  19486. {
  19487. switch (m_type)
  19488. {
  19489. case value_t::number_integer:
  19490. {
  19491. m_value.number_integer = 0;
  19492. break;
  19493. }
  19494. case value_t::number_unsigned:
  19495. {
  19496. m_value.number_unsigned = 0;
  19497. break;
  19498. }
  19499. case value_t::number_float:
  19500. {
  19501. m_value.number_float = 0.0;
  19502. break;
  19503. }
  19504. case value_t::boolean:
  19505. {
  19506. m_value.boolean = false;
  19507. break;
  19508. }
  19509. case value_t::string:
  19510. {
  19511. m_value.string->clear();
  19512. break;
  19513. }
  19514. case value_t::binary:
  19515. {
  19516. m_value.binary->clear();
  19517. break;
  19518. }
  19519. case value_t::array:
  19520. {
  19521. m_value.array->clear();
  19522. break;
  19523. }
  19524. case value_t::object:
  19525. {
  19526. m_value.object->clear();
  19527. break;
  19528. }
  19529. case value_t::null:
  19530. case value_t::discarded:
  19531. default:
  19532. break;
  19533. }
  19534. }
  19535. /*!
  19536. @brief add an object to an array
  19537. Appends the given element @a val to the end of the JSON value. If the
  19538. function is called on a JSON null value, an empty array is created before
  19539. appending @a val.
  19540. @param[in] val the value to add to the JSON array
  19541. @throw type_error.308 when called on a type other than JSON array or
  19542. null; example: `"cannot use push_back() with number"`
  19543. @complexity Amortized constant.
  19544. @liveexample{The example shows how `push_back()` and `+=` can be used to
  19545. add elements to a JSON array. Note how the `null` value was silently
  19546. converted to a JSON array.,push_back}
  19547. @since version 1.0.0
  19548. */
  19549. void push_back(basic_json&& val)
  19550. {
  19551. // push_back only works for null objects or arrays
  19552. if (JSON_HEDLEY_UNLIKELY(!(is_null() || is_array())))
  19553. {
  19554. JSON_THROW(type_error::create(308, "cannot use push_back() with " + std::string(type_name()), *this));
  19555. }
  19556. // transform null object into an array
  19557. if (is_null())
  19558. {
  19559. m_type = value_t::array;
  19560. m_value = value_t::array;
  19561. assert_invariant();
  19562. }
  19563. // add element to array (move semantics)
  19564. const auto old_capacity = m_value.array->capacity();
  19565. m_value.array->push_back(std::move(val));
  19566. set_parent(m_value.array->back(), old_capacity);
  19567. // if val is moved from, basic_json move constructor marks it null so we do not call the destructor
  19568. }
  19569. /*!
  19570. @brief add an object to an array
  19571. @copydoc push_back(basic_json&&)
  19572. */
  19573. reference operator+=(basic_json&& val)
  19574. {
  19575. push_back(std::move(val));
  19576. return *this;
  19577. }
  19578. /*!
  19579. @brief add an object to an array
  19580. @copydoc push_back(basic_json&&)
  19581. */
  19582. void push_back(const basic_json& val)
  19583. {
  19584. // push_back only works for null objects or arrays
  19585. if (JSON_HEDLEY_UNLIKELY(!(is_null() || is_array())))
  19586. {
  19587. JSON_THROW(type_error::create(308, "cannot use push_back() with " + std::string(type_name()), *this));
  19588. }
  19589. // transform null object into an array
  19590. if (is_null())
  19591. {
  19592. m_type = value_t::array;
  19593. m_value = value_t::array;
  19594. assert_invariant();
  19595. }
  19596. // add element to array
  19597. const auto old_capacity = m_value.array->capacity();
  19598. m_value.array->push_back(val);
  19599. set_parent(m_value.array->back(), old_capacity);
  19600. }
  19601. /*!
  19602. @brief add an object to an array
  19603. @copydoc push_back(basic_json&&)
  19604. */
  19605. reference operator+=(const basic_json& val)
  19606. {
  19607. push_back(val);
  19608. return *this;
  19609. }
  19610. /*!
  19611. @brief add an object to an object
  19612. Inserts the given element @a val to the JSON object. If the function is
  19613. called on a JSON null value, an empty object is created before inserting
  19614. @a val.
  19615. @param[in] val the value to add to the JSON object
  19616. @throw type_error.308 when called on a type other than JSON object or
  19617. null; example: `"cannot use push_back() with number"`
  19618. @complexity Logarithmic in the size of the container, O(log(`size()`)).
  19619. @liveexample{The example shows how `push_back()` and `+=` can be used to
  19620. add elements to a JSON object. Note how the `null` value was silently
  19621. converted to a JSON object.,push_back__object_t__value}
  19622. @since version 1.0.0
  19623. */
  19624. void push_back(const typename object_t::value_type& val)
  19625. {
  19626. // push_back only works for null objects or objects
  19627. if (JSON_HEDLEY_UNLIKELY(!(is_null() || is_object())))
  19628. {
  19629. JSON_THROW(type_error::create(308, "cannot use push_back() with " + std::string(type_name()), *this));
  19630. }
  19631. // transform null object into an object
  19632. if (is_null())
  19633. {
  19634. m_type = value_t::object;
  19635. m_value = value_t::object;
  19636. assert_invariant();
  19637. }
  19638. // add element to object
  19639. auto res = m_value.object->insert(val);
  19640. set_parent(res.first->second);
  19641. }
  19642. /*!
  19643. @brief add an object to an object
  19644. @copydoc push_back(const typename object_t::value_type&)
  19645. */
  19646. reference operator+=(const typename object_t::value_type& val)
  19647. {
  19648. push_back(val);
  19649. return *this;
  19650. }
  19651. /*!
  19652. @brief add an object to an object
  19653. This function allows to use `push_back` with an initializer list. In case
  19654. 1. the current value is an object,
  19655. 2. the initializer list @a init contains only two elements, and
  19656. 3. the first element of @a init is a string,
  19657. @a init is converted into an object element and added using
  19658. @ref push_back(const typename object_t::value_type&). Otherwise, @a init
  19659. is converted to a JSON value and added using @ref push_back(basic_json&&).
  19660. @param[in] init an initializer list
  19661. @complexity Linear in the size of the initializer list @a init.
  19662. @note This function is required to resolve an ambiguous overload error,
  19663. because pairs like `{"key", "value"}` can be both interpreted as
  19664. `object_t::value_type` or `std::initializer_list<basic_json>`, see
  19665. https://github.com/nlohmann/json/issues/235 for more information.
  19666. @liveexample{The example shows how initializer lists are treated as
  19667. objects when possible.,push_back__initializer_list}
  19668. */
  19669. void push_back(initializer_list_t init)
  19670. {
  19671. if (is_object() && init.size() == 2 && (*init.begin())->is_string())
  19672. {
  19673. basic_json&& key = init.begin()->moved_or_copied();
  19674. push_back(typename object_t::value_type(
  19675. std::move(key.get_ref<string_t&>()), (init.begin() + 1)->moved_or_copied()));
  19676. }
  19677. else
  19678. {
  19679. push_back(basic_json(init));
  19680. }
  19681. }
  19682. /*!
  19683. @brief add an object to an object
  19684. @copydoc push_back(initializer_list_t)
  19685. */
  19686. reference operator+=(initializer_list_t init)
  19687. {
  19688. push_back(init);
  19689. return *this;
  19690. }
  19691. /*!
  19692. @brief add an object to an array
  19693. Creates a JSON value from the passed parameters @a args to the end of the
  19694. JSON value. If the function is called on a JSON null value, an empty array
  19695. is created before appending the value created from @a args.
  19696. @param[in] args arguments to forward to a constructor of @ref basic_json
  19697. @tparam Args compatible types to create a @ref basic_json object
  19698. @return reference to the inserted element
  19699. @throw type_error.311 when called on a type other than JSON array or
  19700. null; example: `"cannot use emplace_back() with number"`
  19701. @complexity Amortized constant.
  19702. @liveexample{The example shows how `push_back()` can be used to add
  19703. elements to a JSON array. Note how the `null` value was silently converted
  19704. to a JSON array.,emplace_back}
  19705. @since version 2.0.8, returns reference since 3.7.0
  19706. */
  19707. template<class... Args>
  19708. reference emplace_back(Args&& ... args)
  19709. {
  19710. // emplace_back only works for null objects or arrays
  19711. if (JSON_HEDLEY_UNLIKELY(!(is_null() || is_array())))
  19712. {
  19713. JSON_THROW(type_error::create(311, "cannot use emplace_back() with " + std::string(type_name()), *this));
  19714. }
  19715. // transform null object into an array
  19716. if (is_null())
  19717. {
  19718. m_type = value_t::array;
  19719. m_value = value_t::array;
  19720. assert_invariant();
  19721. }
  19722. // add element to array (perfect forwarding)
  19723. const auto old_capacity = m_value.array->capacity();
  19724. m_value.array->emplace_back(std::forward<Args>(args)...);
  19725. return set_parent(m_value.array->back(), old_capacity);
  19726. }
  19727. /*!
  19728. @brief add an object to an object if key does not exist
  19729. Inserts a new element into a JSON object constructed in-place with the
  19730. given @a args if there is no element with the key in the container. If the
  19731. function is called on a JSON null value, an empty object is created before
  19732. appending the value created from @a args.
  19733. @param[in] args arguments to forward to a constructor of @ref basic_json
  19734. @tparam Args compatible types to create a @ref basic_json object
  19735. @return a pair consisting of an iterator to the inserted element, or the
  19736. already-existing element if no insertion happened, and a bool
  19737. denoting whether the insertion took place.
  19738. @throw type_error.311 when called on a type other than JSON object or
  19739. null; example: `"cannot use emplace() with number"`
  19740. @complexity Logarithmic in the size of the container, O(log(`size()`)).
  19741. @liveexample{The example shows how `emplace()` can be used to add elements
  19742. to a JSON object. Note how the `null` value was silently converted to a
  19743. JSON object. Further note how no value is added if there was already one
  19744. value stored with the same key.,emplace}
  19745. @since version 2.0.8
  19746. */
  19747. template<class... Args>
  19748. std::pair<iterator, bool> emplace(Args&& ... args)
  19749. {
  19750. // emplace only works for null objects or arrays
  19751. if (JSON_HEDLEY_UNLIKELY(!(is_null() || is_object())))
  19752. {
  19753. JSON_THROW(type_error::create(311, "cannot use emplace() with " + std::string(type_name()), *this));
  19754. }
  19755. // transform null object into an object
  19756. if (is_null())
  19757. {
  19758. m_type = value_t::object;
  19759. m_value = value_t::object;
  19760. assert_invariant();
  19761. }
  19762. // add element to array (perfect forwarding)
  19763. auto res = m_value.object->emplace(std::forward<Args>(args)...);
  19764. set_parent(res.first->second);
  19765. // create result iterator and set iterator to the result of emplace
  19766. auto it = begin();
  19767. it.m_it.object_iterator = res.first;
  19768. // return pair of iterator and boolean
  19769. return {it, res.second};
  19770. }
  19771. /// Helper for insertion of an iterator
  19772. /// @note: This uses std::distance to support GCC 4.8,
  19773. /// see https://github.com/nlohmann/json/pull/1257
  19774. template<typename... Args>
  19775. iterator insert_iterator(const_iterator pos, Args&& ... args)
  19776. {
  19777. iterator result(this);
  19778. JSON_ASSERT(m_value.array != nullptr);
  19779. auto insert_pos = std::distance(m_value.array->begin(), pos.m_it.array_iterator);
  19780. m_value.array->insert(pos.m_it.array_iterator, std::forward<Args>(args)...);
  19781. result.m_it.array_iterator = m_value.array->begin() + insert_pos;
  19782. // This could have been written as:
  19783. // result.m_it.array_iterator = m_value.array->insert(pos.m_it.array_iterator, cnt, val);
  19784. // but the return value of insert is missing in GCC 4.8, so it is written this way instead.
  19785. set_parents();
  19786. return result;
  19787. }
  19788. /*!
  19789. @brief inserts element
  19790. Inserts element @a val before iterator @a pos.
  19791. @param[in] pos iterator before which the content will be inserted; may be
  19792. the end() iterator
  19793. @param[in] val element to insert
  19794. @return iterator pointing to the inserted @a val.
  19795. @throw type_error.309 if called on JSON values other than arrays;
  19796. example: `"cannot use insert() with string"`
  19797. @throw invalid_iterator.202 if @a pos is not an iterator of *this;
  19798. example: `"iterator does not fit current value"`
  19799. @complexity Constant plus linear in the distance between @a pos and end of
  19800. the container.
  19801. @liveexample{The example shows how `insert()` is used.,insert}
  19802. @since version 1.0.0
  19803. */
  19804. iterator insert(const_iterator pos, const basic_json& val)
  19805. {
  19806. // insert only works for arrays
  19807. if (JSON_HEDLEY_LIKELY(is_array()))
  19808. {
  19809. // check if iterator pos fits to this JSON value
  19810. if (JSON_HEDLEY_UNLIKELY(pos.m_object != this))
  19811. {
  19812. JSON_THROW(invalid_iterator::create(202, "iterator does not fit current value", *this));
  19813. }
  19814. // insert to array and return iterator
  19815. return insert_iterator(pos, val);
  19816. }
  19817. JSON_THROW(type_error::create(309, "cannot use insert() with " + std::string(type_name()), *this));
  19818. }
  19819. /*!
  19820. @brief inserts element
  19821. @copydoc insert(const_iterator, const basic_json&)
  19822. */
  19823. iterator insert(const_iterator pos, basic_json&& val)
  19824. {
  19825. return insert(pos, val);
  19826. }
  19827. /*!
  19828. @brief inserts elements
  19829. Inserts @a cnt copies of @a val before iterator @a pos.
  19830. @param[in] pos iterator before which the content will be inserted; may be
  19831. the end() iterator
  19832. @param[in] cnt number of copies of @a val to insert
  19833. @param[in] val element to insert
  19834. @return iterator pointing to the first element inserted, or @a pos if
  19835. `cnt==0`
  19836. @throw type_error.309 if called on JSON values other than arrays; example:
  19837. `"cannot use insert() with string"`
  19838. @throw invalid_iterator.202 if @a pos is not an iterator of *this;
  19839. example: `"iterator does not fit current value"`
  19840. @complexity Linear in @a cnt plus linear in the distance between @a pos
  19841. and end of the container.
  19842. @liveexample{The example shows how `insert()` is used.,insert__count}
  19843. @since version 1.0.0
  19844. */
  19845. iterator insert(const_iterator pos, size_type cnt, const basic_json& val)
  19846. {
  19847. // insert only works for arrays
  19848. if (JSON_HEDLEY_LIKELY(is_array()))
  19849. {
  19850. // check if iterator pos fits to this JSON value
  19851. if (JSON_HEDLEY_UNLIKELY(pos.m_object != this))
  19852. {
  19853. JSON_THROW(invalid_iterator::create(202, "iterator does not fit current value", *this));
  19854. }
  19855. // insert to array and return iterator
  19856. return insert_iterator(pos, cnt, val);
  19857. }
  19858. JSON_THROW(type_error::create(309, "cannot use insert() with " + std::string(type_name()), *this));
  19859. }
  19860. /*!
  19861. @brief inserts elements
  19862. Inserts elements from range `[first, last)` before iterator @a pos.
  19863. @param[in] pos iterator before which the content will be inserted; may be
  19864. the end() iterator
  19865. @param[in] first begin of the range of elements to insert
  19866. @param[in] last end of the range of elements to insert
  19867. @throw type_error.309 if called on JSON values other than arrays; example:
  19868. `"cannot use insert() with string"`
  19869. @throw invalid_iterator.202 if @a pos is not an iterator of *this;
  19870. example: `"iterator does not fit current value"`
  19871. @throw invalid_iterator.210 if @a first and @a last do not belong to the
  19872. same JSON value; example: `"iterators do not fit"`
  19873. @throw invalid_iterator.211 if @a first or @a last are iterators into
  19874. container for which insert is called; example: `"passed iterators may not
  19875. belong to container"`
  19876. @return iterator pointing to the first element inserted, or @a pos if
  19877. `first==last`
  19878. @complexity Linear in `std::distance(first, last)` plus linear in the
  19879. distance between @a pos and end of the container.
  19880. @liveexample{The example shows how `insert()` is used.,insert__range}
  19881. @since version 1.0.0
  19882. */
  19883. iterator insert(const_iterator pos, const_iterator first, const_iterator last)
  19884. {
  19885. // insert only works for arrays
  19886. if (JSON_HEDLEY_UNLIKELY(!is_array()))
  19887. {
  19888. JSON_THROW(type_error::create(309, "cannot use insert() with " + std::string(type_name()), *this));
  19889. }
  19890. // check if iterator pos fits to this JSON value
  19891. if (JSON_HEDLEY_UNLIKELY(pos.m_object != this))
  19892. {
  19893. JSON_THROW(invalid_iterator::create(202, "iterator does not fit current value", *this));
  19894. }
  19895. // check if range iterators belong to the same JSON object
  19896. if (JSON_HEDLEY_UNLIKELY(first.m_object != last.m_object))
  19897. {
  19898. JSON_THROW(invalid_iterator::create(210, "iterators do not fit", *this));
  19899. }
  19900. if (JSON_HEDLEY_UNLIKELY(first.m_object == this))
  19901. {
  19902. JSON_THROW(invalid_iterator::create(211, "passed iterators may not belong to container", *this));
  19903. }
  19904. // insert to array and return iterator
  19905. return insert_iterator(pos, first.m_it.array_iterator, last.m_it.array_iterator);
  19906. }
  19907. /*!
  19908. @brief inserts elements
  19909. Inserts elements from initializer list @a ilist before iterator @a pos.
  19910. @param[in] pos iterator before which the content will be inserted; may be
  19911. the end() iterator
  19912. @param[in] ilist initializer list to insert the values from
  19913. @throw type_error.309 if called on JSON values other than arrays; example:
  19914. `"cannot use insert() with string"`
  19915. @throw invalid_iterator.202 if @a pos is not an iterator of *this;
  19916. example: `"iterator does not fit current value"`
  19917. @return iterator pointing to the first element inserted, or @a pos if
  19918. `ilist` is empty
  19919. @complexity Linear in `ilist.size()` plus linear in the distance between
  19920. @a pos and end of the container.
  19921. @liveexample{The example shows how `insert()` is used.,insert__ilist}
  19922. @since version 1.0.0
  19923. */
  19924. iterator insert(const_iterator pos, initializer_list_t ilist)
  19925. {
  19926. // insert only works for arrays
  19927. if (JSON_HEDLEY_UNLIKELY(!is_array()))
  19928. {
  19929. JSON_THROW(type_error::create(309, "cannot use insert() with " + std::string(type_name()), *this));
  19930. }
  19931. // check if iterator pos fits to this JSON value
  19932. if (JSON_HEDLEY_UNLIKELY(pos.m_object != this))
  19933. {
  19934. JSON_THROW(invalid_iterator::create(202, "iterator does not fit current value", *this));
  19935. }
  19936. // insert to array and return iterator
  19937. return insert_iterator(pos, ilist.begin(), ilist.end());
  19938. }
  19939. /*!
  19940. @brief inserts elements
  19941. Inserts elements from range `[first, last)`.
  19942. @param[in] first begin of the range of elements to insert
  19943. @param[in] last end of the range of elements to insert
  19944. @throw type_error.309 if called on JSON values other than objects; example:
  19945. `"cannot use insert() with string"`
  19946. @throw invalid_iterator.202 if iterator @a first or @a last does does not
  19947. point to an object; example: `"iterators first and last must point to
  19948. objects"`
  19949. @throw invalid_iterator.210 if @a first and @a last do not belong to the
  19950. same JSON value; example: `"iterators do not fit"`
  19951. @complexity Logarithmic: `O(N*log(size() + N))`, where `N` is the number
  19952. of elements to insert.
  19953. @liveexample{The example shows how `insert()` is used.,insert__range_object}
  19954. @since version 3.0.0
  19955. */
  19956. void insert(const_iterator first, const_iterator last)
  19957. {
  19958. // insert only works for objects
  19959. if (JSON_HEDLEY_UNLIKELY(!is_object()))
  19960. {
  19961. JSON_THROW(type_error::create(309, "cannot use insert() with " + std::string(type_name()), *this));
  19962. }
  19963. // check if range iterators belong to the same JSON object
  19964. if (JSON_HEDLEY_UNLIKELY(first.m_object != last.m_object))
  19965. {
  19966. JSON_THROW(invalid_iterator::create(210, "iterators do not fit", *this));
  19967. }
  19968. // passed iterators must belong to objects
  19969. if (JSON_HEDLEY_UNLIKELY(!first.m_object->is_object()))
  19970. {
  19971. JSON_THROW(invalid_iterator::create(202, "iterators first and last must point to objects", *this));
  19972. }
  19973. m_value.object->insert(first.m_it.object_iterator, last.m_it.object_iterator);
  19974. }
  19975. /*!
  19976. @brief updates a JSON object from another object, overwriting existing keys
  19977. Inserts all values from JSON object @a j and overwrites existing keys.
  19978. @param[in] j JSON object to read values from
  19979. @throw type_error.312 if called on JSON values other than objects; example:
  19980. `"cannot use update() with string"`
  19981. @complexity O(N*log(size() + N)), where N is the number of elements to
  19982. insert.
  19983. @liveexample{The example shows how `update()` is used.,update}
  19984. @sa https://docs.python.org/3.6/library/stdtypes.html#dict.update
  19985. @since version 3.0.0
  19986. */
  19987. void update(const_reference j)
  19988. {
  19989. // implicitly convert null value to an empty object
  19990. if (is_null())
  19991. {
  19992. m_type = value_t::object;
  19993. m_value.object = create<object_t>();
  19994. assert_invariant();
  19995. }
  19996. if (JSON_HEDLEY_UNLIKELY(!is_object()))
  19997. {
  19998. JSON_THROW(type_error::create(312, "cannot use update() with " + std::string(type_name()), *this));
  19999. }
  20000. if (JSON_HEDLEY_UNLIKELY(!j.is_object()))
  20001. {
  20002. JSON_THROW(type_error::create(312, "cannot use update() with " + std::string(j.type_name()), *this));
  20003. }
  20004. for (auto it = j.cbegin(); it != j.cend(); ++it)
  20005. {
  20006. m_value.object->operator[](it.key()) = it.value();
  20007. #if JSON_DIAGNOSTICS
  20008. m_value.object->operator[](it.key()).m_parent = this;
  20009. #endif
  20010. }
  20011. }
  20012. /*!
  20013. @brief updates a JSON object from another object, overwriting existing keys
  20014. Inserts all values from from range `[first, last)` and overwrites existing
  20015. keys.
  20016. @param[in] first begin of the range of elements to insert
  20017. @param[in] last end of the range of elements to insert
  20018. @throw type_error.312 if called on JSON values other than objects; example:
  20019. `"cannot use update() with string"`
  20020. @throw invalid_iterator.202 if iterator @a first or @a last does does not
  20021. point to an object; example: `"iterators first and last must point to
  20022. objects"`
  20023. @throw invalid_iterator.210 if @a first and @a last do not belong to the
  20024. same JSON value; example: `"iterators do not fit"`
  20025. @complexity O(N*log(size() + N)), where N is the number of elements to
  20026. insert.
  20027. @liveexample{The example shows how `update()` is used__range.,update}
  20028. @sa https://docs.python.org/3.6/library/stdtypes.html#dict.update
  20029. @since version 3.0.0
  20030. */
  20031. void update(const_iterator first, const_iterator last)
  20032. {
  20033. // implicitly convert null value to an empty object
  20034. if (is_null())
  20035. {
  20036. m_type = value_t::object;
  20037. m_value.object = create<object_t>();
  20038. assert_invariant();
  20039. }
  20040. if (JSON_HEDLEY_UNLIKELY(!is_object()))
  20041. {
  20042. JSON_THROW(type_error::create(312, "cannot use update() with " + std::string(type_name()), *this));
  20043. }
  20044. // check if range iterators belong to the same JSON object
  20045. if (JSON_HEDLEY_UNLIKELY(first.m_object != last.m_object))
  20046. {
  20047. JSON_THROW(invalid_iterator::create(210, "iterators do not fit", *this));
  20048. }
  20049. // passed iterators must belong to objects
  20050. if (JSON_HEDLEY_UNLIKELY(!first.m_object->is_object()
  20051. || !last.m_object->is_object()))
  20052. {
  20053. JSON_THROW(invalid_iterator::create(202, "iterators first and last must point to objects", *this));
  20054. }
  20055. for (auto it = first; it != last; ++it)
  20056. {
  20057. m_value.object->operator[](it.key()) = it.value();
  20058. #if JSON_DIAGNOSTICS
  20059. m_value.object->operator[](it.key()).m_parent = this;
  20060. #endif
  20061. }
  20062. }
  20063. /*!
  20064. @brief exchanges the values
  20065. Exchanges the contents of the JSON value with those of @a other. Does not
  20066. invoke any move, copy, or swap operations on individual elements. All
  20067. iterators and references remain valid. The past-the-end iterator is
  20068. invalidated.
  20069. @param[in,out] other JSON value to exchange the contents with
  20070. @complexity Constant.
  20071. @liveexample{The example below shows how JSON values can be swapped with
  20072. `swap()`.,swap__reference}
  20073. @since version 1.0.0
  20074. */
  20075. void swap(reference other) noexcept (
  20076. std::is_nothrow_move_constructible<value_t>::value&&
  20077. std::is_nothrow_move_assignable<value_t>::value&&
  20078. std::is_nothrow_move_constructible<json_value>::value&&
  20079. std::is_nothrow_move_assignable<json_value>::value
  20080. )
  20081. {
  20082. std::swap(m_type, other.m_type);
  20083. std::swap(m_value, other.m_value);
  20084. set_parents();
  20085. other.set_parents();
  20086. assert_invariant();
  20087. }
  20088. /*!
  20089. @brief exchanges the values
  20090. Exchanges the contents of the JSON value from @a left with those of @a right. Does not
  20091. invoke any move, copy, or swap operations on individual elements. All
  20092. iterators and references remain valid. The past-the-end iterator is
  20093. invalidated. implemented as a friend function callable via ADL.
  20094. @param[in,out] left JSON value to exchange the contents with
  20095. @param[in,out] right JSON value to exchange the contents with
  20096. @complexity Constant.
  20097. @liveexample{The example below shows how JSON values can be swapped with
  20098. `swap()`.,swap__reference}
  20099. @since version 1.0.0
  20100. */
  20101. friend void swap(reference left, reference right) noexcept (
  20102. std::is_nothrow_move_constructible<value_t>::value&&
  20103. std::is_nothrow_move_assignable<value_t>::value&&
  20104. std::is_nothrow_move_constructible<json_value>::value&&
  20105. std::is_nothrow_move_assignable<json_value>::value
  20106. )
  20107. {
  20108. left.swap(right);
  20109. }
  20110. /*!
  20111. @brief exchanges the values
  20112. Exchanges the contents of a JSON array with those of @a other. Does not
  20113. invoke any move, copy, or swap operations on individual elements. All
  20114. iterators and references remain valid. The past-the-end iterator is
  20115. invalidated.
  20116. @param[in,out] other array to exchange the contents with
  20117. @throw type_error.310 when JSON value is not an array; example: `"cannot
  20118. use swap() with string"`
  20119. @complexity Constant.
  20120. @liveexample{The example below shows how arrays can be swapped with
  20121. `swap()`.,swap__array_t}
  20122. @since version 1.0.0
  20123. */
  20124. void swap(array_t& other) // NOLINT(bugprone-exception-escape)
  20125. {
  20126. // swap only works for arrays
  20127. if (JSON_HEDLEY_LIKELY(is_array()))
  20128. {
  20129. std::swap(*(m_value.array), other);
  20130. }
  20131. else
  20132. {
  20133. JSON_THROW(type_error::create(310, "cannot use swap() with " + std::string(type_name()), *this));
  20134. }
  20135. }
  20136. /*!
  20137. @brief exchanges the values
  20138. Exchanges the contents of a JSON object with those of @a other. Does not
  20139. invoke any move, copy, or swap operations on individual elements. All
  20140. iterators and references remain valid. The past-the-end iterator is
  20141. invalidated.
  20142. @param[in,out] other object to exchange the contents with
  20143. @throw type_error.310 when JSON value is not an object; example:
  20144. `"cannot use swap() with string"`
  20145. @complexity Constant.
  20146. @liveexample{The example below shows how objects can be swapped with
  20147. `swap()`.,swap__object_t}
  20148. @since version 1.0.0
  20149. */
  20150. void swap(object_t& other) // NOLINT(bugprone-exception-escape)
  20151. {
  20152. // swap only works for objects
  20153. if (JSON_HEDLEY_LIKELY(is_object()))
  20154. {
  20155. std::swap(*(m_value.object), other);
  20156. }
  20157. else
  20158. {
  20159. JSON_THROW(type_error::create(310, "cannot use swap() with " + std::string(type_name()), *this));
  20160. }
  20161. }
  20162. /*!
  20163. @brief exchanges the values
  20164. Exchanges the contents of a JSON string with those of @a other. Does not
  20165. invoke any move, copy, or swap operations on individual elements. All
  20166. iterators and references remain valid. The past-the-end iterator is
  20167. invalidated.
  20168. @param[in,out] other string to exchange the contents with
  20169. @throw type_error.310 when JSON value is not a string; example: `"cannot
  20170. use swap() with boolean"`
  20171. @complexity Constant.
  20172. @liveexample{The example below shows how strings can be swapped with
  20173. `swap()`.,swap__string_t}
  20174. @since version 1.0.0
  20175. */
  20176. void swap(string_t& other) // NOLINT(bugprone-exception-escape)
  20177. {
  20178. // swap only works for strings
  20179. if (JSON_HEDLEY_LIKELY(is_string()))
  20180. {
  20181. std::swap(*(m_value.string), other);
  20182. }
  20183. else
  20184. {
  20185. JSON_THROW(type_error::create(310, "cannot use swap() with " + std::string(type_name()), *this));
  20186. }
  20187. }
  20188. /*!
  20189. @brief exchanges the values
  20190. Exchanges the contents of a JSON string with those of @a other. Does not
  20191. invoke any move, copy, or swap operations on individual elements. All
  20192. iterators and references remain valid. The past-the-end iterator is
  20193. invalidated.
  20194. @param[in,out] other binary to exchange the contents with
  20195. @throw type_error.310 when JSON value is not a string; example: `"cannot
  20196. use swap() with boolean"`
  20197. @complexity Constant.
  20198. @liveexample{The example below shows how strings can be swapped with
  20199. `swap()`.,swap__binary_t}
  20200. @since version 3.8.0
  20201. */
  20202. void swap(binary_t& other) // NOLINT(bugprone-exception-escape)
  20203. {
  20204. // swap only works for strings
  20205. if (JSON_HEDLEY_LIKELY(is_binary()))
  20206. {
  20207. std::swap(*(m_value.binary), other);
  20208. }
  20209. else
  20210. {
  20211. JSON_THROW(type_error::create(310, "cannot use swap() with " + std::string(type_name()), *this));
  20212. }
  20213. }
  20214. /// @copydoc swap(binary_t&)
  20215. void swap(typename binary_t::container_type& other) // NOLINT(bugprone-exception-escape)
  20216. {
  20217. // swap only works for strings
  20218. if (JSON_HEDLEY_LIKELY(is_binary()))
  20219. {
  20220. std::swap(*(m_value.binary), other);
  20221. }
  20222. else
  20223. {
  20224. JSON_THROW(type_error::create(310, "cannot use swap() with " + std::string(type_name()), *this));
  20225. }
  20226. }
  20227. /// @}
  20228. public:
  20229. //////////////////////////////////////////
  20230. // lexicographical comparison operators //
  20231. //////////////////////////////////////////
  20232. /// @name lexicographical comparison operators
  20233. /// @{
  20234. /*!
  20235. @brief comparison: equal
  20236. Compares two JSON values for equality according to the following rules:
  20237. - Two JSON values are equal if (1) they are from the same type and (2)
  20238. their stored values are the same according to their respective
  20239. `operator==`.
  20240. - Integer and floating-point numbers are automatically converted before
  20241. comparison. Note that two NaN values are always treated as unequal.
  20242. - Two JSON null values are equal.
  20243. @note Floating-point inside JSON values numbers are compared with
  20244. `json::number_float_t::operator==` which is `double::operator==` by
  20245. default. To compare floating-point while respecting an epsilon, an alternative
  20246. [comparison function](https://github.com/mariokonrad/marnav/blob/master/include/marnav/math/floatingpoint.hpp#L34-#L39)
  20247. could be used, for instance
  20248. @code {.cpp}
  20249. template<typename T, typename = typename std::enable_if<std::is_floating_point<T>::value, T>::type>
  20250. inline bool is_same(T a, T b, T epsilon = std::numeric_limits<T>::epsilon()) noexcept
  20251. {
  20252. return std::abs(a - b) <= epsilon;
  20253. }
  20254. @endcode
  20255. Or you can self-defined operator equal function like this:
  20256. @code {.cpp}
  20257. bool my_equal(const_reference lhs, const_reference rhs) {
  20258. const auto lhs_type lhs.type();
  20259. const auto rhs_type rhs.type();
  20260. if (lhs_type == rhs_type) {
  20261. switch(lhs_type)
  20262. // self_defined case
  20263. case value_t::number_float:
  20264. return std::abs(lhs - rhs) <= std::numeric_limits<float>::epsilon();
  20265. // other cases remain the same with the original
  20266. ...
  20267. }
  20268. ...
  20269. }
  20270. @endcode
  20271. @note NaN values never compare equal to themselves or to other NaN values.
  20272. @param[in] lhs first JSON value to consider
  20273. @param[in] rhs second JSON value to consider
  20274. @return whether the values @a lhs and @a rhs are equal
  20275. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  20276. @complexity Linear.
  20277. @liveexample{The example demonstrates comparing several JSON
  20278. types.,operator__equal}
  20279. @since version 1.0.0
  20280. */
  20281. friend bool operator==(const_reference lhs, const_reference rhs) noexcept
  20282. {
  20283. #ifdef __GNUC__
  20284. #pragma GCC diagnostic push
  20285. #pragma GCC diagnostic ignored "-Wfloat-equal"
  20286. #endif
  20287. const auto lhs_type = lhs.type();
  20288. const auto rhs_type = rhs.type();
  20289. if (lhs_type == rhs_type)
  20290. {
  20291. switch (lhs_type)
  20292. {
  20293. case value_t::array:
  20294. return *lhs.m_value.array == *rhs.m_value.array;
  20295. case value_t::object:
  20296. return *lhs.m_value.object == *rhs.m_value.object;
  20297. case value_t::null:
  20298. return true;
  20299. case value_t::string:
  20300. return *lhs.m_value.string == *rhs.m_value.string;
  20301. case value_t::boolean:
  20302. return lhs.m_value.boolean == rhs.m_value.boolean;
  20303. case value_t::number_integer:
  20304. return lhs.m_value.number_integer == rhs.m_value.number_integer;
  20305. case value_t::number_unsigned:
  20306. return lhs.m_value.number_unsigned == rhs.m_value.number_unsigned;
  20307. case value_t::number_float:
  20308. return lhs.m_value.number_float == rhs.m_value.number_float;
  20309. case value_t::binary:
  20310. return *lhs.m_value.binary == *rhs.m_value.binary;
  20311. case value_t::discarded:
  20312. default:
  20313. return false;
  20314. }
  20315. }
  20316. else if (lhs_type == value_t::number_integer && rhs_type == value_t::number_float)
  20317. {
  20318. return static_cast<number_float_t>(lhs.m_value.number_integer) == rhs.m_value.number_float;
  20319. }
  20320. else if (lhs_type == value_t::number_float && rhs_type == value_t::number_integer)
  20321. {
  20322. return lhs.m_value.number_float == static_cast<number_float_t>(rhs.m_value.number_integer);
  20323. }
  20324. else if (lhs_type == value_t::number_unsigned && rhs_type == value_t::number_float)
  20325. {
  20326. return static_cast<number_float_t>(lhs.m_value.number_unsigned) == rhs.m_value.number_float;
  20327. }
  20328. else if (lhs_type == value_t::number_float && rhs_type == value_t::number_unsigned)
  20329. {
  20330. return lhs.m_value.number_float == static_cast<number_float_t>(rhs.m_value.number_unsigned);
  20331. }
  20332. else if (lhs_type == value_t::number_unsigned && rhs_type == value_t::number_integer)
  20333. {
  20334. return static_cast<number_integer_t>(lhs.m_value.number_unsigned) == rhs.m_value.number_integer;
  20335. }
  20336. else if (lhs_type == value_t::number_integer && rhs_type == value_t::number_unsigned)
  20337. {
  20338. return lhs.m_value.number_integer == static_cast<number_integer_t>(rhs.m_value.number_unsigned);
  20339. }
  20340. return false;
  20341. #ifdef __GNUC__
  20342. #pragma GCC diagnostic pop
  20343. #endif
  20344. }
  20345. /*!
  20346. @brief comparison: equal
  20347. @copydoc operator==(const_reference, const_reference)
  20348. */
  20349. template<typename ScalarType, typename std::enable_if<
  20350. std::is_scalar<ScalarType>::value, int>::type = 0>
  20351. friend bool operator==(const_reference lhs, ScalarType rhs) noexcept
  20352. {
  20353. return lhs == basic_json(rhs);
  20354. }
  20355. /*!
  20356. @brief comparison: equal
  20357. @copydoc operator==(const_reference, const_reference)
  20358. */
  20359. template<typename ScalarType, typename std::enable_if<
  20360. std::is_scalar<ScalarType>::value, int>::type = 0>
  20361. friend bool operator==(ScalarType lhs, const_reference rhs) noexcept
  20362. {
  20363. return basic_json(lhs) == rhs;
  20364. }
  20365. /*!
  20366. @brief comparison: not equal
  20367. Compares two JSON values for inequality by calculating `not (lhs == rhs)`.
  20368. @param[in] lhs first JSON value to consider
  20369. @param[in] rhs second JSON value to consider
  20370. @return whether the values @a lhs and @a rhs are not equal
  20371. @complexity Linear.
  20372. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  20373. @liveexample{The example demonstrates comparing several JSON
  20374. types.,operator__notequal}
  20375. @since version 1.0.0
  20376. */
  20377. friend bool operator!=(const_reference lhs, const_reference rhs) noexcept
  20378. {
  20379. return !(lhs == rhs);
  20380. }
  20381. /*!
  20382. @brief comparison: not equal
  20383. @copydoc operator!=(const_reference, const_reference)
  20384. */
  20385. template<typename ScalarType, typename std::enable_if<
  20386. std::is_scalar<ScalarType>::value, int>::type = 0>
  20387. friend bool operator!=(const_reference lhs, ScalarType rhs) noexcept
  20388. {
  20389. return lhs != basic_json(rhs);
  20390. }
  20391. /*!
  20392. @brief comparison: not equal
  20393. @copydoc operator!=(const_reference, const_reference)
  20394. */
  20395. template<typename ScalarType, typename std::enable_if<
  20396. std::is_scalar<ScalarType>::value, int>::type = 0>
  20397. friend bool operator!=(ScalarType lhs, const_reference rhs) noexcept
  20398. {
  20399. return basic_json(lhs) != rhs;
  20400. }
  20401. /*!
  20402. @brief comparison: less than
  20403. Compares whether one JSON value @a lhs is less than another JSON value @a
  20404. rhs according to the following rules:
  20405. - If @a lhs and @a rhs have the same type, the values are compared using
  20406. the default `<` operator.
  20407. - Integer and floating-point numbers are automatically converted before
  20408. comparison
  20409. - In case @a lhs and @a rhs have different types, the values are ignored
  20410. and the order of the types is considered, see
  20411. @ref operator<(const value_t, const value_t).
  20412. @param[in] lhs first JSON value to consider
  20413. @param[in] rhs second JSON value to consider
  20414. @return whether @a lhs is less than @a rhs
  20415. @complexity Linear.
  20416. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  20417. @liveexample{The example demonstrates comparing several JSON
  20418. types.,operator__less}
  20419. @since version 1.0.0
  20420. */
  20421. friend bool operator<(const_reference lhs, const_reference rhs) noexcept
  20422. {
  20423. const auto lhs_type = lhs.type();
  20424. const auto rhs_type = rhs.type();
  20425. if (lhs_type == rhs_type)
  20426. {
  20427. switch (lhs_type)
  20428. {
  20429. case value_t::array:
  20430. // note parentheses are necessary, see
  20431. // https://github.com/nlohmann/json/issues/1530
  20432. return (*lhs.m_value.array) < (*rhs.m_value.array);
  20433. case value_t::object:
  20434. return (*lhs.m_value.object) < (*rhs.m_value.object);
  20435. case value_t::null:
  20436. return false;
  20437. case value_t::string:
  20438. return (*lhs.m_value.string) < (*rhs.m_value.string);
  20439. case value_t::boolean:
  20440. return (lhs.m_value.boolean) < (rhs.m_value.boolean);
  20441. case value_t::number_integer:
  20442. return (lhs.m_value.number_integer) < (rhs.m_value.number_integer);
  20443. case value_t::number_unsigned:
  20444. return (lhs.m_value.number_unsigned) < (rhs.m_value.number_unsigned);
  20445. case value_t::number_float:
  20446. return (lhs.m_value.number_float) < (rhs.m_value.number_float);
  20447. case value_t::binary:
  20448. return (*lhs.m_value.binary) < (*rhs.m_value.binary);
  20449. case value_t::discarded:
  20450. default:
  20451. return false;
  20452. }
  20453. }
  20454. else if (lhs_type == value_t::number_integer && rhs_type == value_t::number_float)
  20455. {
  20456. return static_cast<number_float_t>(lhs.m_value.number_integer) < rhs.m_value.number_float;
  20457. }
  20458. else if (lhs_type == value_t::number_float && rhs_type == value_t::number_integer)
  20459. {
  20460. return lhs.m_value.number_float < static_cast<number_float_t>(rhs.m_value.number_integer);
  20461. }
  20462. else if (lhs_type == value_t::number_unsigned && rhs_type == value_t::number_float)
  20463. {
  20464. return static_cast<number_float_t>(lhs.m_value.number_unsigned) < rhs.m_value.number_float;
  20465. }
  20466. else if (lhs_type == value_t::number_float && rhs_type == value_t::number_unsigned)
  20467. {
  20468. return lhs.m_value.number_float < static_cast<number_float_t>(rhs.m_value.number_unsigned);
  20469. }
  20470. else if (lhs_type == value_t::number_integer && rhs_type == value_t::number_unsigned)
  20471. {
  20472. return lhs.m_value.number_integer < static_cast<number_integer_t>(rhs.m_value.number_unsigned);
  20473. }
  20474. else if (lhs_type == value_t::number_unsigned && rhs_type == value_t::number_integer)
  20475. {
  20476. return static_cast<number_integer_t>(lhs.m_value.number_unsigned) < rhs.m_value.number_integer;
  20477. }
  20478. // We only reach this line if we cannot compare values. In that case,
  20479. // we compare types. Note we have to call the operator explicitly,
  20480. // because MSVC has problems otherwise.
  20481. return operator<(lhs_type, rhs_type);
  20482. }
  20483. /*!
  20484. @brief comparison: less than
  20485. @copydoc operator<(const_reference, const_reference)
  20486. */
  20487. template<typename ScalarType, typename std::enable_if<
  20488. std::is_scalar<ScalarType>::value, int>::type = 0>
  20489. friend bool operator<(const_reference lhs, ScalarType rhs) noexcept
  20490. {
  20491. return lhs < basic_json(rhs);
  20492. }
  20493. /*!
  20494. @brief comparison: less than
  20495. @copydoc operator<(const_reference, const_reference)
  20496. */
  20497. template<typename ScalarType, typename std::enable_if<
  20498. std::is_scalar<ScalarType>::value, int>::type = 0>
  20499. friend bool operator<(ScalarType lhs, const_reference rhs) noexcept
  20500. {
  20501. return basic_json(lhs) < rhs;
  20502. }
  20503. /*!
  20504. @brief comparison: less than or equal
  20505. Compares whether one JSON value @a lhs is less than or equal to another
  20506. JSON value by calculating `not (rhs < lhs)`.
  20507. @param[in] lhs first JSON value to consider
  20508. @param[in] rhs second JSON value to consider
  20509. @return whether @a lhs is less than or equal to @a rhs
  20510. @complexity Linear.
  20511. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  20512. @liveexample{The example demonstrates comparing several JSON
  20513. types.,operator__greater}
  20514. @since version 1.0.0
  20515. */
  20516. friend bool operator<=(const_reference lhs, const_reference rhs) noexcept
  20517. {
  20518. return !(rhs < lhs);
  20519. }
  20520. /*!
  20521. @brief comparison: less than or equal
  20522. @copydoc operator<=(const_reference, const_reference)
  20523. */
  20524. template<typename ScalarType, typename std::enable_if<
  20525. std::is_scalar<ScalarType>::value, int>::type = 0>
  20526. friend bool operator<=(const_reference lhs, ScalarType rhs) noexcept
  20527. {
  20528. return lhs <= basic_json(rhs);
  20529. }
  20530. /*!
  20531. @brief comparison: less than or equal
  20532. @copydoc operator<=(const_reference, const_reference)
  20533. */
  20534. template<typename ScalarType, typename std::enable_if<
  20535. std::is_scalar<ScalarType>::value, int>::type = 0>
  20536. friend bool operator<=(ScalarType lhs, const_reference rhs) noexcept
  20537. {
  20538. return basic_json(lhs) <= rhs;
  20539. }
  20540. /*!
  20541. @brief comparison: greater than
  20542. Compares whether one JSON value @a lhs is greater than another
  20543. JSON value by calculating `not (lhs <= rhs)`.
  20544. @param[in] lhs first JSON value to consider
  20545. @param[in] rhs second JSON value to consider
  20546. @return whether @a lhs is greater than to @a rhs
  20547. @complexity Linear.
  20548. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  20549. @liveexample{The example demonstrates comparing several JSON
  20550. types.,operator__lessequal}
  20551. @since version 1.0.0
  20552. */
  20553. friend bool operator>(const_reference lhs, const_reference rhs) noexcept
  20554. {
  20555. return !(lhs <= rhs);
  20556. }
  20557. /*!
  20558. @brief comparison: greater than
  20559. @copydoc operator>(const_reference, const_reference)
  20560. */
  20561. template<typename ScalarType, typename std::enable_if<
  20562. std::is_scalar<ScalarType>::value, int>::type = 0>
  20563. friend bool operator>(const_reference lhs, ScalarType rhs) noexcept
  20564. {
  20565. return lhs > basic_json(rhs);
  20566. }
  20567. /*!
  20568. @brief comparison: greater than
  20569. @copydoc operator>(const_reference, const_reference)
  20570. */
  20571. template<typename ScalarType, typename std::enable_if<
  20572. std::is_scalar<ScalarType>::value, int>::type = 0>
  20573. friend bool operator>(ScalarType lhs, const_reference rhs) noexcept
  20574. {
  20575. return basic_json(lhs) > rhs;
  20576. }
  20577. /*!
  20578. @brief comparison: greater than or equal
  20579. Compares whether one JSON value @a lhs is greater than or equal to another
  20580. JSON value by calculating `not (lhs < rhs)`.
  20581. @param[in] lhs first JSON value to consider
  20582. @param[in] rhs second JSON value to consider
  20583. @return whether @a lhs is greater than or equal to @a rhs
  20584. @complexity Linear.
  20585. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  20586. @liveexample{The example demonstrates comparing several JSON
  20587. types.,operator__greaterequal}
  20588. @since version 1.0.0
  20589. */
  20590. friend bool operator>=(const_reference lhs, const_reference rhs) noexcept
  20591. {
  20592. return !(lhs < rhs);
  20593. }
  20594. /*!
  20595. @brief comparison: greater than or equal
  20596. @copydoc operator>=(const_reference, const_reference)
  20597. */
  20598. template<typename ScalarType, typename std::enable_if<
  20599. std::is_scalar<ScalarType>::value, int>::type = 0>
  20600. friend bool operator>=(const_reference lhs, ScalarType rhs) noexcept
  20601. {
  20602. return lhs >= basic_json(rhs);
  20603. }
  20604. /*!
  20605. @brief comparison: greater than or equal
  20606. @copydoc operator>=(const_reference, const_reference)
  20607. */
  20608. template<typename ScalarType, typename std::enable_if<
  20609. std::is_scalar<ScalarType>::value, int>::type = 0>
  20610. friend bool operator>=(ScalarType lhs, const_reference rhs) noexcept
  20611. {
  20612. return basic_json(lhs) >= rhs;
  20613. }
  20614. /// @}
  20615. ///////////////////
  20616. // serialization //
  20617. ///////////////////
  20618. /// @name serialization
  20619. /// @{
  20620. #ifndef JSON_NO_IO
  20621. /*!
  20622. @brief serialize to stream
  20623. Serialize the given JSON value @a j to the output stream @a o. The JSON
  20624. value will be serialized using the @ref dump member function.
  20625. - The indentation of the output can be controlled with the member variable
  20626. `width` of the output stream @a o. For instance, using the manipulator
  20627. `std::setw(4)` on @a o sets the indentation level to `4` and the
  20628. serialization result is the same as calling `dump(4)`.
  20629. - The indentation character can be controlled with the member variable
  20630. `fill` of the output stream @a o. For instance, the manipulator
  20631. `std::setfill('\\t')` sets indentation to use a tab character rather than
  20632. the default space character.
  20633. @param[in,out] o stream to serialize to
  20634. @param[in] j JSON value to serialize
  20635. @return the stream @a o
  20636. @throw type_error.316 if a string stored inside the JSON value is not
  20637. UTF-8 encoded
  20638. @complexity Linear.
  20639. @liveexample{The example below shows the serialization with different
  20640. parameters to `width` to adjust the indentation level.,operator_serialize}
  20641. @since version 1.0.0; indentation character added in version 3.0.0
  20642. */
  20643. friend std::ostream& operator<<(std::ostream& o, const basic_json& j)
  20644. {
  20645. // read width member and use it as indentation parameter if nonzero
  20646. const bool pretty_print = o.width() > 0;
  20647. const auto indentation = pretty_print ? o.width() : 0;
  20648. // reset width to 0 for subsequent calls to this stream
  20649. o.width(0);
  20650. // do the actual serialization
  20651. serializer s(detail::output_adapter<char>(o), o.fill());
  20652. s.dump(j, pretty_print, false, static_cast<unsigned int>(indentation));
  20653. return o;
  20654. }
  20655. /*!
  20656. @brief serialize to stream
  20657. @deprecated This stream operator is deprecated and will be removed in
  20658. future 4.0.0 of the library. Please use
  20659. @ref operator<<(std::ostream&, const basic_json&)
  20660. instead; that is, replace calls like `j >> o;` with `o << j;`.
  20661. @since version 1.0.0; deprecated since version 3.0.0
  20662. */
  20663. JSON_HEDLEY_DEPRECATED_FOR(3.0.0, operator<<(std::ostream&, const basic_json&))
  20664. friend std::ostream& operator>>(const basic_json& j, std::ostream& o)
  20665. {
  20666. return o << j;
  20667. }
  20668. #endif // JSON_NO_IO
  20669. /// @}
  20670. /////////////////////
  20671. // deserialization //
  20672. /////////////////////
  20673. /// @name deserialization
  20674. /// @{
  20675. /*!
  20676. @brief deserialize from a compatible input
  20677. @tparam InputType A compatible input, for instance
  20678. - an std::istream object
  20679. - a FILE pointer
  20680. - a C-style array of characters
  20681. - a pointer to a null-terminated string of single byte characters
  20682. - an object obj for which begin(obj) and end(obj) produces a valid pair of
  20683. iterators.
  20684. @param[in] i input to read from
  20685. @param[in] cb a parser callback function of type @ref parser_callback_t
  20686. which is used to control the deserialization by filtering unwanted values
  20687. (optional)
  20688. @param[in] allow_exceptions whether to throw exceptions in case of a
  20689. parse error (optional, true by default)
  20690. @param[in] ignore_comments whether comments should be ignored and treated
  20691. like whitespace (true) or yield a parse error (true); (optional, false by
  20692. default)
  20693. @return deserialized JSON value; in case of a parse error and
  20694. @a allow_exceptions set to `false`, the return value will be
  20695. value_t::discarded.
  20696. @throw parse_error.101 if a parse error occurs; example: `""unexpected end
  20697. of input; expected string literal""`
  20698. @throw parse_error.102 if to_unicode fails or surrogate error
  20699. @throw parse_error.103 if to_unicode fails
  20700. @complexity Linear in the length of the input. The parser is a predictive
  20701. LL(1) parser. The complexity can be higher if the parser callback function
  20702. @a cb or reading from the input @a i has a super-linear complexity.
  20703. @note A UTF-8 byte order mark is silently ignored.
  20704. @liveexample{The example below demonstrates the `parse()` function reading
  20705. from an array.,parse__array__parser_callback_t}
  20706. @liveexample{The example below demonstrates the `parse()` function with
  20707. and without callback function.,parse__string__parser_callback_t}
  20708. @liveexample{The example below demonstrates the `parse()` function with
  20709. and without callback function.,parse__istream__parser_callback_t}
  20710. @liveexample{The example below demonstrates the `parse()` function reading
  20711. from a contiguous container.,parse__contiguouscontainer__parser_callback_t}
  20712. @since version 2.0.3 (contiguous containers); version 3.9.0 allowed to
  20713. ignore comments.
  20714. */
  20715. template<typename InputType>
  20716. JSON_HEDLEY_WARN_UNUSED_RESULT
  20717. static basic_json parse(InputType&& i,
  20718. const parser_callback_t cb = nullptr,
  20719. const bool allow_exceptions = true,
  20720. const bool ignore_comments = false)
  20721. {
  20722. basic_json result;
  20723. parser(detail::input_adapter(std::forward<InputType>(i)), cb, allow_exceptions, ignore_comments).parse(true, result);
  20724. return result;
  20725. }
  20726. /*!
  20727. @brief deserialize from a pair of character iterators
  20728. The value_type of the iterator must be a integral type with size of 1, 2 or
  20729. 4 bytes, which will be interpreted respectively as UTF-8, UTF-16 and UTF-32.
  20730. @param[in] first iterator to start of character range
  20731. @param[in] last iterator to end of character range
  20732. @param[in] cb a parser callback function of type @ref parser_callback_t
  20733. which is used to control the deserialization by filtering unwanted values
  20734. (optional)
  20735. @param[in] allow_exceptions whether to throw exceptions in case of a
  20736. parse error (optional, true by default)
  20737. @param[in] ignore_comments whether comments should be ignored and treated
  20738. like whitespace (true) or yield a parse error (true); (optional, false by
  20739. default)
  20740. @return deserialized JSON value; in case of a parse error and
  20741. @a allow_exceptions set to `false`, the return value will be
  20742. value_t::discarded.
  20743. @throw parse_error.101 if a parse error occurs; example: `""unexpected end
  20744. of input; expected string literal""`
  20745. @throw parse_error.102 if to_unicode fails or surrogate error
  20746. @throw parse_error.103 if to_unicode fails
  20747. */
  20748. template<typename IteratorType>
  20749. JSON_HEDLEY_WARN_UNUSED_RESULT
  20750. static basic_json parse(IteratorType first,
  20751. IteratorType last,
  20752. const parser_callback_t cb = nullptr,
  20753. const bool allow_exceptions = true,
  20754. const bool ignore_comments = false)
  20755. {
  20756. basic_json result;
  20757. parser(detail::input_adapter(std::move(first), std::move(last)), cb, allow_exceptions, ignore_comments).parse(true, result);
  20758. return result;
  20759. }
  20760. JSON_HEDLEY_WARN_UNUSED_RESULT
  20761. JSON_HEDLEY_DEPRECATED_FOR(3.8.0, parse(ptr, ptr + len))
  20762. static basic_json parse(detail::span_input_adapter&& i,
  20763. const parser_callback_t cb = nullptr,
  20764. const bool allow_exceptions = true,
  20765. const bool ignore_comments = false)
  20766. {
  20767. basic_json result;
  20768. parser(i.get(), cb, allow_exceptions, ignore_comments).parse(true, result);
  20769. return result;
  20770. }
  20771. /*!
  20772. @brief check if the input is valid JSON
  20773. Unlike the @ref parse(InputType&&, const parser_callback_t,const bool)
  20774. function, this function neither throws an exception in case of invalid JSON
  20775. input (i.e., a parse error) nor creates diagnostic information.
  20776. @tparam InputType A compatible input, for instance
  20777. - an std::istream object
  20778. - a FILE pointer
  20779. - a C-style array of characters
  20780. - a pointer to a null-terminated string of single byte characters
  20781. - an object obj for which begin(obj) and end(obj) produces a valid pair of
  20782. iterators.
  20783. @param[in] i input to read from
  20784. @param[in] ignore_comments whether comments should be ignored and treated
  20785. like whitespace (true) or yield a parse error (true); (optional, false by
  20786. default)
  20787. @return Whether the input read from @a i is valid JSON.
  20788. @complexity Linear in the length of the input. The parser is a predictive
  20789. LL(1) parser.
  20790. @note A UTF-8 byte order mark is silently ignored.
  20791. @liveexample{The example below demonstrates the `accept()` function reading
  20792. from a string.,accept__string}
  20793. */
  20794. template<typename InputType>
  20795. static bool accept(InputType&& i,
  20796. const bool ignore_comments = false)
  20797. {
  20798. return parser(detail::input_adapter(std::forward<InputType>(i)), nullptr, false, ignore_comments).accept(true);
  20799. }
  20800. template<typename IteratorType>
  20801. static bool accept(IteratorType first, IteratorType last,
  20802. const bool ignore_comments = false)
  20803. {
  20804. return parser(detail::input_adapter(std::move(first), std::move(last)), nullptr, false, ignore_comments).accept(true);
  20805. }
  20806. JSON_HEDLEY_WARN_UNUSED_RESULT
  20807. JSON_HEDLEY_DEPRECATED_FOR(3.8.0, accept(ptr, ptr + len))
  20808. static bool accept(detail::span_input_adapter&& i,
  20809. const bool ignore_comments = false)
  20810. {
  20811. return parser(i.get(), nullptr, false, ignore_comments).accept(true);
  20812. }
  20813. /*!
  20814. @brief generate SAX events
  20815. The SAX event lister must follow the interface of @ref json_sax.
  20816. This function reads from a compatible input. Examples are:
  20817. - an std::istream object
  20818. - a FILE pointer
  20819. - a C-style array of characters
  20820. - a pointer to a null-terminated string of single byte characters
  20821. - an object obj for which begin(obj) and end(obj) produces a valid pair of
  20822. iterators.
  20823. @param[in] i input to read from
  20824. @param[in,out] sax SAX event listener
  20825. @param[in] format the format to parse (JSON, CBOR, MessagePack, or UBJSON)
  20826. @param[in] strict whether the input has to be consumed completely
  20827. @param[in] ignore_comments whether comments should be ignored and treated
  20828. like whitespace (true) or yield a parse error (true); (optional, false by
  20829. default); only applies to the JSON file format.
  20830. @return return value of the last processed SAX event
  20831. @throw parse_error.101 if a parse error occurs; example: `""unexpected end
  20832. of input; expected string literal""`
  20833. @throw parse_error.102 if to_unicode fails or surrogate error
  20834. @throw parse_error.103 if to_unicode fails
  20835. @complexity Linear in the length of the input. The parser is a predictive
  20836. LL(1) parser. The complexity can be higher if the SAX consumer @a sax has
  20837. a super-linear complexity.
  20838. @note A UTF-8 byte order mark is silently ignored.
  20839. @liveexample{The example below demonstrates the `sax_parse()` function
  20840. reading from string and processing the events with a user-defined SAX
  20841. event consumer.,sax_parse}
  20842. @since version 3.2.0
  20843. */
  20844. template <typename InputType, typename SAX>
  20845. JSON_HEDLEY_NON_NULL(2)
  20846. static bool sax_parse(InputType&& i, SAX* sax,
  20847. input_format_t format = input_format_t::json,
  20848. const bool strict = true,
  20849. const bool ignore_comments = false)
  20850. {
  20851. auto ia = detail::input_adapter(std::forward<InputType>(i));
  20852. return format == input_format_t::json
  20853. ? parser(std::move(ia), nullptr, true, ignore_comments).sax_parse(sax, strict)
  20854. : detail::binary_reader<basic_json, decltype(ia), SAX>(std::move(ia)).sax_parse(format, sax, strict);
  20855. }
  20856. template<class IteratorType, class SAX>
  20857. JSON_HEDLEY_NON_NULL(3)
  20858. static bool sax_parse(IteratorType first, IteratorType last, SAX* sax,
  20859. input_format_t format = input_format_t::json,
  20860. const bool strict = true,
  20861. const bool ignore_comments = false)
  20862. {
  20863. auto ia = detail::input_adapter(std::move(first), std::move(last));
  20864. return format == input_format_t::json
  20865. ? parser(std::move(ia), nullptr, true, ignore_comments).sax_parse(sax, strict)
  20866. : detail::binary_reader<basic_json, decltype(ia), SAX>(std::move(ia)).sax_parse(format, sax, strict);
  20867. }
  20868. template <typename SAX>
  20869. JSON_HEDLEY_DEPRECATED_FOR(3.8.0, sax_parse(ptr, ptr + len, ...))
  20870. JSON_HEDLEY_NON_NULL(2)
  20871. static bool sax_parse(detail::span_input_adapter&& i, SAX* sax,
  20872. input_format_t format = input_format_t::json,
  20873. const bool strict = true,
  20874. const bool ignore_comments = false)
  20875. {
  20876. auto ia = i.get();
  20877. return format == input_format_t::json
  20878. // NOLINTNEXTLINE(hicpp-move-const-arg,performance-move-const-arg)
  20879. ? parser(std::move(ia), nullptr, true, ignore_comments).sax_parse(sax, strict)
  20880. // NOLINTNEXTLINE(hicpp-move-const-arg,performance-move-const-arg)
  20881. : detail::binary_reader<basic_json, decltype(ia), SAX>(std::move(ia)).sax_parse(format, sax, strict);
  20882. }
  20883. #ifndef JSON_NO_IO
  20884. /*!
  20885. @brief deserialize from stream
  20886. @deprecated This stream operator is deprecated and will be removed in
  20887. version 4.0.0 of the library. Please use
  20888. @ref operator>>(std::istream&, basic_json&)
  20889. instead; that is, replace calls like `j << i;` with `i >> j;`.
  20890. @since version 1.0.0; deprecated since version 3.0.0
  20891. */
  20892. JSON_HEDLEY_DEPRECATED_FOR(3.0.0, operator>>(std::istream&, basic_json&))
  20893. friend std::istream& operator<<(basic_json& j, std::istream& i)
  20894. {
  20895. return operator>>(i, j);
  20896. }
  20897. /*!
  20898. @brief deserialize from stream
  20899. Deserializes an input stream to a JSON value.
  20900. @param[in,out] i input stream to read a serialized JSON value from
  20901. @param[in,out] j JSON value to write the deserialized input to
  20902. @throw parse_error.101 in case of an unexpected token
  20903. @throw parse_error.102 if to_unicode fails or surrogate error
  20904. @throw parse_error.103 if to_unicode fails
  20905. @complexity Linear in the length of the input. The parser is a predictive
  20906. LL(1) parser.
  20907. @note A UTF-8 byte order mark is silently ignored.
  20908. @liveexample{The example below shows how a JSON value is constructed by
  20909. reading a serialization from a stream.,operator_deserialize}
  20910. @sa parse(std::istream&, const parser_callback_t) for a variant with a
  20911. parser callback function to filter values while parsing
  20912. @since version 1.0.0
  20913. */
  20914. friend std::istream& operator>>(std::istream& i, basic_json& j)
  20915. {
  20916. parser(detail::input_adapter(i)).parse(false, j);
  20917. return i;
  20918. }
  20919. #endif // JSON_NO_IO
  20920. /// @}
  20921. ///////////////////////////
  20922. // convenience functions //
  20923. ///////////////////////////
  20924. /*!
  20925. @brief return the type as string
  20926. Returns the type name as string to be used in error messages - usually to
  20927. indicate that a function was called on a wrong JSON type.
  20928. @return a string representation of a the @a m_type member:
  20929. Value type | return value
  20930. ----------- | -------------
  20931. null | `"null"`
  20932. boolean | `"boolean"`
  20933. string | `"string"`
  20934. number | `"number"` (for all number types)
  20935. object | `"object"`
  20936. array | `"array"`
  20937. binary | `"binary"`
  20938. discarded | `"discarded"`
  20939. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  20940. @complexity Constant.
  20941. @liveexample{The following code exemplifies `type_name()` for all JSON
  20942. types.,type_name}
  20943. @sa see @ref type() -- return the type of the JSON value
  20944. @sa see @ref operator value_t() -- return the type of the JSON value (implicit)
  20945. @since version 1.0.0, public since 2.1.0, `const char*` and `noexcept`
  20946. since 3.0.0
  20947. */
  20948. JSON_HEDLEY_RETURNS_NON_NULL
  20949. const char* type_name() const noexcept
  20950. {
  20951. {
  20952. switch (m_type)
  20953. {
  20954. case value_t::null:
  20955. return "null";
  20956. case value_t::object:
  20957. return "object";
  20958. case value_t::array:
  20959. return "array";
  20960. case value_t::string:
  20961. return "string";
  20962. case value_t::boolean:
  20963. return "boolean";
  20964. case value_t::binary:
  20965. return "binary";
  20966. case value_t::discarded:
  20967. return "discarded";
  20968. case value_t::number_integer:
  20969. case value_t::number_unsigned:
  20970. case value_t::number_float:
  20971. default:
  20972. return "number";
  20973. }
  20974. }
  20975. }
  20976. JSON_PRIVATE_UNLESS_TESTED:
  20977. //////////////////////
  20978. // member variables //
  20979. //////////////////////
  20980. /// the type of the current element
  20981. value_t m_type = value_t::null;
  20982. /// the value of the current element
  20983. json_value m_value = {};
  20984. #if JSON_DIAGNOSTICS
  20985. /// a pointer to a parent value (for debugging purposes)
  20986. basic_json* m_parent = nullptr;
  20987. #endif
  20988. //////////////////////////////////////////
  20989. // binary serialization/deserialization //
  20990. //////////////////////////////////////////
  20991. /// @name binary serialization/deserialization support
  20992. /// @{
  20993. public:
  20994. /*!
  20995. @brief create a CBOR serialization of a given JSON value
  20996. Serializes a given JSON value @a j to a byte vector using the CBOR (Concise
  20997. Binary Object Representation) serialization format. CBOR is a binary
  20998. serialization format which aims to be more compact than JSON itself, yet
  20999. more efficient to parse.
  21000. The library uses the following mapping from JSON values types to
  21001. CBOR types according to the CBOR specification (RFC 7049):
  21002. JSON value type | value/range | CBOR type | first byte
  21003. --------------- | ------------------------------------------ | ---------------------------------- | ---------------
  21004. null | `null` | Null | 0xF6
  21005. boolean | `true` | True | 0xF5
  21006. boolean | `false` | False | 0xF4
  21007. number_integer | -9223372036854775808..-2147483649 | Negative integer (8 bytes follow) | 0x3B
  21008. number_integer | -2147483648..-32769 | Negative integer (4 bytes follow) | 0x3A
  21009. number_integer | -32768..-129 | Negative integer (2 bytes follow) | 0x39
  21010. number_integer | -128..-25 | Negative integer (1 byte follow) | 0x38
  21011. number_integer | -24..-1 | Negative integer | 0x20..0x37
  21012. number_integer | 0..23 | Integer | 0x00..0x17
  21013. number_integer | 24..255 | Unsigned integer (1 byte follow) | 0x18
  21014. number_integer | 256..65535 | Unsigned integer (2 bytes follow) | 0x19
  21015. number_integer | 65536..4294967295 | Unsigned integer (4 bytes follow) | 0x1A
  21016. number_integer | 4294967296..18446744073709551615 | Unsigned integer (8 bytes follow) | 0x1B
  21017. number_unsigned | 0..23 | Integer | 0x00..0x17
  21018. number_unsigned | 24..255 | Unsigned integer (1 byte follow) | 0x18
  21019. number_unsigned | 256..65535 | Unsigned integer (2 bytes follow) | 0x19
  21020. number_unsigned | 65536..4294967295 | Unsigned integer (4 bytes follow) | 0x1A
  21021. number_unsigned | 4294967296..18446744073709551615 | Unsigned integer (8 bytes follow) | 0x1B
  21022. number_float | *any value representable by a float* | Single-Precision Float | 0xFA
  21023. number_float | *any value NOT representable by a float* | Double-Precision Float | 0xFB
  21024. string | *length*: 0..23 | UTF-8 string | 0x60..0x77
  21025. string | *length*: 23..255 | UTF-8 string (1 byte follow) | 0x78
  21026. string | *length*: 256..65535 | UTF-8 string (2 bytes follow) | 0x79
  21027. string | *length*: 65536..4294967295 | UTF-8 string (4 bytes follow) | 0x7A
  21028. string | *length*: 4294967296..18446744073709551615 | UTF-8 string (8 bytes follow) | 0x7B
  21029. array | *size*: 0..23 | array | 0x80..0x97
  21030. array | *size*: 23..255 | array (1 byte follow) | 0x98
  21031. array | *size*: 256..65535 | array (2 bytes follow) | 0x99
  21032. array | *size*: 65536..4294967295 | array (4 bytes follow) | 0x9A
  21033. array | *size*: 4294967296..18446744073709551615 | array (8 bytes follow) | 0x9B
  21034. object | *size*: 0..23 | map | 0xA0..0xB7
  21035. object | *size*: 23..255 | map (1 byte follow) | 0xB8
  21036. object | *size*: 256..65535 | map (2 bytes follow) | 0xB9
  21037. object | *size*: 65536..4294967295 | map (4 bytes follow) | 0xBA
  21038. object | *size*: 4294967296..18446744073709551615 | map (8 bytes follow) | 0xBB
  21039. binary | *size*: 0..23 | byte string | 0x40..0x57
  21040. binary | *size*: 23..255 | byte string (1 byte follow) | 0x58
  21041. binary | *size*: 256..65535 | byte string (2 bytes follow) | 0x59
  21042. binary | *size*: 65536..4294967295 | byte string (4 bytes follow) | 0x5A
  21043. binary | *size*: 4294967296..18446744073709551615 | byte string (8 bytes follow) | 0x5B
  21044. Binary values with subtype are mapped to tagged values (0xD8..0xDB)
  21045. depending on the subtype, followed by a byte string, see "binary" cells
  21046. in the table above.
  21047. @note The mapping is **complete** in the sense that any JSON value type
  21048. can be converted to a CBOR value.
  21049. @note If NaN or Infinity are stored inside a JSON number, they are
  21050. serialized properly. This behavior differs from the @ref dump()
  21051. function which serializes NaN or Infinity to `null`.
  21052. @note The following CBOR types are not used in the conversion:
  21053. - UTF-8 strings terminated by "break" (0x7F)
  21054. - arrays terminated by "break" (0x9F)
  21055. - maps terminated by "break" (0xBF)
  21056. - byte strings terminated by "break" (0x5F)
  21057. - date/time (0xC0..0xC1)
  21058. - bignum (0xC2..0xC3)
  21059. - decimal fraction (0xC4)
  21060. - bigfloat (0xC5)
  21061. - expected conversions (0xD5..0xD7)
  21062. - simple values (0xE0..0xF3, 0xF8)
  21063. - undefined (0xF7)
  21064. - half-precision floats (0xF9)
  21065. - break (0xFF)
  21066. @param[in] j JSON value to serialize
  21067. @return CBOR serialization as byte vector
  21068. @complexity Linear in the size of the JSON value @a j.
  21069. @liveexample{The example shows the serialization of a JSON value to a byte
  21070. vector in CBOR format.,to_cbor}
  21071. @sa http://cbor.io
  21072. @sa see @ref from_cbor(InputType&&, const bool, const bool, const cbor_tag_handler_t) for the
  21073. analogous deserialization
  21074. @sa see @ref to_msgpack(const basic_json&) for the related MessagePack format
  21075. @sa see @ref to_ubjson(const basic_json&, const bool, const bool) for the
  21076. related UBJSON format
  21077. @since version 2.0.9; compact representation of floating-point numbers
  21078. since version 3.8.0
  21079. */
  21080. static std::vector<std::uint8_t> to_cbor(const basic_json& j)
  21081. {
  21082. std::vector<std::uint8_t> result;
  21083. to_cbor(j, result);
  21084. return result;
  21085. }
  21086. static void to_cbor(const basic_json& j, detail::output_adapter<std::uint8_t> o)
  21087. {
  21088. binary_writer<std::uint8_t>(o).write_cbor(j);
  21089. }
  21090. static void to_cbor(const basic_json& j, detail::output_adapter<char> o)
  21091. {
  21092. binary_writer<char>(o).write_cbor(j);
  21093. }
  21094. /*!
  21095. @brief create a MessagePack serialization of a given JSON value
  21096. Serializes a given JSON value @a j to a byte vector using the MessagePack
  21097. serialization format. MessagePack is a binary serialization format which
  21098. aims to be more compact than JSON itself, yet more efficient to parse.
  21099. The library uses the following mapping from JSON values types to
  21100. MessagePack types according to the MessagePack specification:
  21101. JSON value type | value/range | MessagePack type | first byte
  21102. --------------- | --------------------------------- | ---------------- | ----------
  21103. null | `null` | nil | 0xC0
  21104. boolean | `true` | true | 0xC3
  21105. boolean | `false` | false | 0xC2
  21106. number_integer | -9223372036854775808..-2147483649 | int64 | 0xD3
  21107. number_integer | -2147483648..-32769 | int32 | 0xD2
  21108. number_integer | -32768..-129 | int16 | 0xD1
  21109. number_integer | -128..-33 | int8 | 0xD0
  21110. number_integer | -32..-1 | negative fixint | 0xE0..0xFF
  21111. number_integer | 0..127 | positive fixint | 0x00..0x7F
  21112. number_integer | 128..255 | uint 8 | 0xCC
  21113. number_integer | 256..65535 | uint 16 | 0xCD
  21114. number_integer | 65536..4294967295 | uint 32 | 0xCE
  21115. number_integer | 4294967296..18446744073709551615 | uint 64 | 0xCF
  21116. number_unsigned | 0..127 | positive fixint | 0x00..0x7F
  21117. number_unsigned | 128..255 | uint 8 | 0xCC
  21118. number_unsigned | 256..65535 | uint 16 | 0xCD
  21119. number_unsigned | 65536..4294967295 | uint 32 | 0xCE
  21120. number_unsigned | 4294967296..18446744073709551615 | uint 64 | 0xCF
  21121. number_float | *any value representable by a float* | float 32 | 0xCA
  21122. number_float | *any value NOT representable by a float* | float 64 | 0xCB
  21123. string | *length*: 0..31 | fixstr | 0xA0..0xBF
  21124. string | *length*: 32..255 | str 8 | 0xD9
  21125. string | *length*: 256..65535 | str 16 | 0xDA
  21126. string | *length*: 65536..4294967295 | str 32 | 0xDB
  21127. array | *size*: 0..15 | fixarray | 0x90..0x9F
  21128. array | *size*: 16..65535 | array 16 | 0xDC
  21129. array | *size*: 65536..4294967295 | array 32 | 0xDD
  21130. object | *size*: 0..15 | fix map | 0x80..0x8F
  21131. object | *size*: 16..65535 | map 16 | 0xDE
  21132. object | *size*: 65536..4294967295 | map 32 | 0xDF
  21133. binary | *size*: 0..255 | bin 8 | 0xC4
  21134. binary | *size*: 256..65535 | bin 16 | 0xC5
  21135. binary | *size*: 65536..4294967295 | bin 32 | 0xC6
  21136. @note The mapping is **complete** in the sense that any JSON value type
  21137. can be converted to a MessagePack value.
  21138. @note The following values can **not** be converted to a MessagePack value:
  21139. - strings with more than 4294967295 bytes
  21140. - byte strings with more than 4294967295 bytes
  21141. - arrays with more than 4294967295 elements
  21142. - objects with more than 4294967295 elements
  21143. @note Any MessagePack output created @ref to_msgpack can be successfully
  21144. parsed by @ref from_msgpack.
  21145. @note If NaN or Infinity are stored inside a JSON number, they are
  21146. serialized properly. This behavior differs from the @ref dump()
  21147. function which serializes NaN or Infinity to `null`.
  21148. @param[in] j JSON value to serialize
  21149. @return MessagePack serialization as byte vector
  21150. @complexity Linear in the size of the JSON value @a j.
  21151. @liveexample{The example shows the serialization of a JSON value to a byte
  21152. vector in MessagePack format.,to_msgpack}
  21153. @sa http://msgpack.org
  21154. @sa see @ref from_msgpack for the analogous deserialization
  21155. @sa see @ref to_cbor(const basic_json& for the related CBOR format
  21156. @sa see @ref to_ubjson(const basic_json&, const bool, const bool) for the
  21157. related UBJSON format
  21158. @since version 2.0.9
  21159. */
  21160. static std::vector<std::uint8_t> to_msgpack(const basic_json& j)
  21161. {
  21162. std::vector<std::uint8_t> result;
  21163. to_msgpack(j, result);
  21164. return result;
  21165. }
  21166. static void to_msgpack(const basic_json& j, detail::output_adapter<std::uint8_t> o)
  21167. {
  21168. binary_writer<std::uint8_t>(o).write_msgpack(j);
  21169. }
  21170. static void to_msgpack(const basic_json& j, detail::output_adapter<char> o)
  21171. {
  21172. binary_writer<char>(o).write_msgpack(j);
  21173. }
  21174. /*!
  21175. @brief create a UBJSON serialization of a given JSON value
  21176. Serializes a given JSON value @a j to a byte vector using the UBJSON
  21177. (Universal Binary JSON) serialization format. UBJSON aims to be more compact
  21178. than JSON itself, yet more efficient to parse.
  21179. The library uses the following mapping from JSON values types to
  21180. UBJSON types according to the UBJSON specification:
  21181. JSON value type | value/range | UBJSON type | marker
  21182. --------------- | --------------------------------- | ----------- | ------
  21183. null | `null` | null | `Z`
  21184. boolean | `true` | true | `T`
  21185. boolean | `false` | false | `F`
  21186. number_integer | -9223372036854775808..-2147483649 | int64 | `L`
  21187. number_integer | -2147483648..-32769 | int32 | `l`
  21188. number_integer | -32768..-129 | int16 | `I`
  21189. number_integer | -128..127 | int8 | `i`
  21190. number_integer | 128..255 | uint8 | `U`
  21191. number_integer | 256..32767 | int16 | `I`
  21192. number_integer | 32768..2147483647 | int32 | `l`
  21193. number_integer | 2147483648..9223372036854775807 | int64 | `L`
  21194. number_unsigned | 0..127 | int8 | `i`
  21195. number_unsigned | 128..255 | uint8 | `U`
  21196. number_unsigned | 256..32767 | int16 | `I`
  21197. number_unsigned | 32768..2147483647 | int32 | `l`
  21198. number_unsigned | 2147483648..9223372036854775807 | int64 | `L`
  21199. number_unsigned | 2147483649..18446744073709551615 | high-precision | `H`
  21200. number_float | *any value* | float64 | `D`
  21201. string | *with shortest length indicator* | string | `S`
  21202. array | *see notes on optimized format* | array | `[`
  21203. object | *see notes on optimized format* | map | `{`
  21204. @note The mapping is **complete** in the sense that any JSON value type
  21205. can be converted to a UBJSON value.
  21206. @note The following values can **not** be converted to a UBJSON value:
  21207. - strings with more than 9223372036854775807 bytes (theoretical)
  21208. @note The following markers are not used in the conversion:
  21209. - `Z`: no-op values are not created.
  21210. - `C`: single-byte strings are serialized with `S` markers.
  21211. @note Any UBJSON output created @ref to_ubjson can be successfully parsed
  21212. by @ref from_ubjson.
  21213. @note If NaN or Infinity are stored inside a JSON number, they are
  21214. serialized properly. This behavior differs from the @ref dump()
  21215. function which serializes NaN or Infinity to `null`.
  21216. @note The optimized formats for containers are supported: Parameter
  21217. @a use_size adds size information to the beginning of a container and
  21218. removes the closing marker. Parameter @a use_type further checks
  21219. whether all elements of a container have the same type and adds the
  21220. type marker to the beginning of the container. The @a use_type
  21221. parameter must only be used together with @a use_size = true. Note
  21222. that @a use_size = true alone may result in larger representations -
  21223. the benefit of this parameter is that the receiving side is
  21224. immediately informed on the number of elements of the container.
  21225. @note If the JSON data contains the binary type, the value stored is a list
  21226. of integers, as suggested by the UBJSON documentation. In particular,
  21227. this means that serialization and the deserialization of a JSON
  21228. containing binary values into UBJSON and back will result in a
  21229. different JSON object.
  21230. @param[in] j JSON value to serialize
  21231. @param[in] use_size whether to add size annotations to container types
  21232. @param[in] use_type whether to add type annotations to container types
  21233. (must be combined with @a use_size = true)
  21234. @return UBJSON serialization as byte vector
  21235. @complexity Linear in the size of the JSON value @a j.
  21236. @liveexample{The example shows the serialization of a JSON value to a byte
  21237. vector in UBJSON format.,to_ubjson}
  21238. @sa http://ubjson.org
  21239. @sa see @ref from_ubjson(InputType&&, const bool, const bool) for the
  21240. analogous deserialization
  21241. @sa see @ref to_cbor(const basic_json& for the related CBOR format
  21242. @sa see @ref to_msgpack(const basic_json&) for the related MessagePack format
  21243. @since version 3.1.0
  21244. */
  21245. static std::vector<std::uint8_t> to_ubjson(const basic_json& j,
  21246. const bool use_size = false,
  21247. const bool use_type = false)
  21248. {
  21249. std::vector<std::uint8_t> result;
  21250. to_ubjson(j, result, use_size, use_type);
  21251. return result;
  21252. }
  21253. static void to_ubjson(const basic_json& j, detail::output_adapter<std::uint8_t> o,
  21254. const bool use_size = false, const bool use_type = false)
  21255. {
  21256. binary_writer<std::uint8_t>(o).write_ubjson(j, use_size, use_type);
  21257. }
  21258. static void to_ubjson(const basic_json& j, detail::output_adapter<char> o,
  21259. const bool use_size = false, const bool use_type = false)
  21260. {
  21261. binary_writer<char>(o).write_ubjson(j, use_size, use_type);
  21262. }
  21263. /*!
  21264. @brief Serializes the given JSON object `j` to BSON and returns a vector
  21265. containing the corresponding BSON-representation.
  21266. BSON (Binary JSON) is a binary format in which zero or more ordered key/value pairs are
  21267. stored as a single entity (a so-called document).
  21268. The library uses the following mapping from JSON values types to BSON types:
  21269. JSON value type | value/range | BSON type | marker
  21270. --------------- | --------------------------------- | ----------- | ------
  21271. null | `null` | null | 0x0A
  21272. boolean | `true`, `false` | boolean | 0x08
  21273. number_integer | -9223372036854775808..-2147483649 | int64 | 0x12
  21274. number_integer | -2147483648..2147483647 | int32 | 0x10
  21275. number_integer | 2147483648..9223372036854775807 | int64 | 0x12
  21276. number_unsigned | 0..2147483647 | int32 | 0x10
  21277. number_unsigned | 2147483648..9223372036854775807 | int64 | 0x12
  21278. number_unsigned | 9223372036854775808..18446744073709551615| -- | --
  21279. number_float | *any value* | double | 0x01
  21280. string | *any value* | string | 0x02
  21281. array | *any value* | document | 0x04
  21282. object | *any value* | document | 0x03
  21283. binary | *any value* | binary | 0x05
  21284. @warning The mapping is **incomplete**, since only JSON-objects (and things
  21285. contained therein) can be serialized to BSON.
  21286. Also, integers larger than 9223372036854775807 cannot be serialized to BSON,
  21287. and the keys may not contain U+0000, since they are serialized a
  21288. zero-terminated c-strings.
  21289. @throw out_of_range.407 if `j.is_number_unsigned() && j.get<std::uint64_t>() > 9223372036854775807`
  21290. @throw out_of_range.409 if a key in `j` contains a NULL (U+0000)
  21291. @throw type_error.317 if `!j.is_object()`
  21292. @pre The input `j` is required to be an object: `j.is_object() == true`.
  21293. @note Any BSON output created via @ref to_bson can be successfully parsed
  21294. by @ref from_bson.
  21295. @param[in] j JSON value to serialize
  21296. @return BSON serialization as byte vector
  21297. @complexity Linear in the size of the JSON value @a j.
  21298. @liveexample{The example shows the serialization of a JSON value to a byte
  21299. vector in BSON format.,to_bson}
  21300. @sa http://bsonspec.org/spec.html
  21301. @sa see @ref from_bson(detail::input_adapter&&, const bool strict) for the
  21302. analogous deserialization
  21303. @sa see @ref to_ubjson(const basic_json&, const bool, const bool) for the
  21304. related UBJSON format
  21305. @sa see @ref to_cbor(const basic_json&) for the related CBOR format
  21306. @sa see @ref to_msgpack(const basic_json&) for the related MessagePack format
  21307. */
  21308. static std::vector<std::uint8_t> to_bson(const basic_json& j)
  21309. {
  21310. std::vector<std::uint8_t> result;
  21311. to_bson(j, result);
  21312. return result;
  21313. }
  21314. /*!
  21315. @brief Serializes the given JSON object `j` to BSON and forwards the
  21316. corresponding BSON-representation to the given output_adapter `o`.
  21317. @param j The JSON object to convert to BSON.
  21318. @param o The output adapter that receives the binary BSON representation.
  21319. @pre The input `j` shall be an object: `j.is_object() == true`
  21320. @sa see @ref to_bson(const basic_json&)
  21321. */
  21322. static void to_bson(const basic_json& j, detail::output_adapter<std::uint8_t> o)
  21323. {
  21324. binary_writer<std::uint8_t>(o).write_bson(j);
  21325. }
  21326. /*!
  21327. @copydoc to_bson(const basic_json&, detail::output_adapter<std::uint8_t>)
  21328. */
  21329. static void to_bson(const basic_json& j, detail::output_adapter<char> o)
  21330. {
  21331. binary_writer<char>(o).write_bson(j);
  21332. }
  21333. /*!
  21334. @brief create a JSON value from an input in CBOR format
  21335. Deserializes a given input @a i to a JSON value using the CBOR (Concise
  21336. Binary Object Representation) serialization format.
  21337. The library maps CBOR types to JSON value types as follows:
  21338. CBOR type | JSON value type | first byte
  21339. ---------------------- | --------------- | ----------
  21340. Integer | number_unsigned | 0x00..0x17
  21341. Unsigned integer | number_unsigned | 0x18
  21342. Unsigned integer | number_unsigned | 0x19
  21343. Unsigned integer | number_unsigned | 0x1A
  21344. Unsigned integer | number_unsigned | 0x1B
  21345. Negative integer | number_integer | 0x20..0x37
  21346. Negative integer | number_integer | 0x38
  21347. Negative integer | number_integer | 0x39
  21348. Negative integer | number_integer | 0x3A
  21349. Negative integer | number_integer | 0x3B
  21350. Byte string | binary | 0x40..0x57
  21351. Byte string | binary | 0x58
  21352. Byte string | binary | 0x59
  21353. Byte string | binary | 0x5A
  21354. Byte string | binary | 0x5B
  21355. UTF-8 string | string | 0x60..0x77
  21356. UTF-8 string | string | 0x78
  21357. UTF-8 string | string | 0x79
  21358. UTF-8 string | string | 0x7A
  21359. UTF-8 string | string | 0x7B
  21360. UTF-8 string | string | 0x7F
  21361. array | array | 0x80..0x97
  21362. array | array | 0x98
  21363. array | array | 0x99
  21364. array | array | 0x9A
  21365. array | array | 0x9B
  21366. array | array | 0x9F
  21367. map | object | 0xA0..0xB7
  21368. map | object | 0xB8
  21369. map | object | 0xB9
  21370. map | object | 0xBA
  21371. map | object | 0xBB
  21372. map | object | 0xBF
  21373. False | `false` | 0xF4
  21374. True | `true` | 0xF5
  21375. Null | `null` | 0xF6
  21376. Half-Precision Float | number_float | 0xF9
  21377. Single-Precision Float | number_float | 0xFA
  21378. Double-Precision Float | number_float | 0xFB
  21379. @warning The mapping is **incomplete** in the sense that not all CBOR
  21380. types can be converted to a JSON value. The following CBOR types
  21381. are not supported and will yield parse errors (parse_error.112):
  21382. - date/time (0xC0..0xC1)
  21383. - bignum (0xC2..0xC3)
  21384. - decimal fraction (0xC4)
  21385. - bigfloat (0xC5)
  21386. - expected conversions (0xD5..0xD7)
  21387. - simple values (0xE0..0xF3, 0xF8)
  21388. - undefined (0xF7)
  21389. @warning CBOR allows map keys of any type, whereas JSON only allows
  21390. strings as keys in object values. Therefore, CBOR maps with keys
  21391. other than UTF-8 strings are rejected (parse_error.113).
  21392. @note Any CBOR output created @ref to_cbor can be successfully parsed by
  21393. @ref from_cbor.
  21394. @param[in] i an input in CBOR format convertible to an input adapter
  21395. @param[in] strict whether to expect the input to be consumed until EOF
  21396. (true by default)
  21397. @param[in] allow_exceptions whether to throw exceptions in case of a
  21398. parse error (optional, true by default)
  21399. @param[in] tag_handler how to treat CBOR tags (optional, error by default)
  21400. @return deserialized JSON value; in case of a parse error and
  21401. @a allow_exceptions set to `false`, the return value will be
  21402. value_t::discarded.
  21403. @throw parse_error.110 if the given input ends prematurely or the end of
  21404. file was not reached when @a strict was set to true
  21405. @throw parse_error.112 if unsupported features from CBOR were
  21406. used in the given input @a v or if the input is not valid CBOR
  21407. @throw parse_error.113 if a string was expected as map key, but not found
  21408. @complexity Linear in the size of the input @a i.
  21409. @liveexample{The example shows the deserialization of a byte vector in CBOR
  21410. format to a JSON value.,from_cbor}
  21411. @sa http://cbor.io
  21412. @sa see @ref to_cbor(const basic_json&) for the analogous serialization
  21413. @sa see @ref from_msgpack(InputType&&, const bool, const bool) for the
  21414. related MessagePack format
  21415. @sa see @ref from_ubjson(InputType&&, const bool, const bool) for the
  21416. related UBJSON format
  21417. @since version 2.0.9; parameter @a start_index since 2.1.1; changed to
  21418. consume input adapters, removed start_index parameter, and added
  21419. @a strict parameter since 3.0.0; added @a allow_exceptions parameter
  21420. since 3.2.0; added @a tag_handler parameter since 3.9.0.
  21421. */
  21422. template<typename InputType>
  21423. JSON_HEDLEY_WARN_UNUSED_RESULT
  21424. static basic_json from_cbor(InputType&& i,
  21425. const bool strict = true,
  21426. const bool allow_exceptions = true,
  21427. const cbor_tag_handler_t tag_handler = cbor_tag_handler_t::error)
  21428. {
  21429. basic_json result;
  21430. detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
  21431. auto ia = detail::input_adapter(std::forward<InputType>(i));
  21432. const bool res = binary_reader<decltype(ia)>(std::move(ia)).sax_parse(input_format_t::cbor, &sdp, strict, tag_handler);
  21433. return res ? result : basic_json(value_t::discarded);
  21434. }
  21435. /*!
  21436. @copydoc from_cbor(InputType&&, const bool, const bool, const cbor_tag_handler_t)
  21437. */
  21438. template<typename IteratorType>
  21439. JSON_HEDLEY_WARN_UNUSED_RESULT
  21440. static basic_json from_cbor(IteratorType first, IteratorType last,
  21441. const bool strict = true,
  21442. const bool allow_exceptions = true,
  21443. const cbor_tag_handler_t tag_handler = cbor_tag_handler_t::error)
  21444. {
  21445. basic_json result;
  21446. detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
  21447. auto ia = detail::input_adapter(std::move(first), std::move(last));
  21448. const bool res = binary_reader<decltype(ia)>(std::move(ia)).sax_parse(input_format_t::cbor, &sdp, strict, tag_handler);
  21449. return res ? result : basic_json(value_t::discarded);
  21450. }
  21451. template<typename T>
  21452. JSON_HEDLEY_WARN_UNUSED_RESULT
  21453. JSON_HEDLEY_DEPRECATED_FOR(3.8.0, from_cbor(ptr, ptr + len))
  21454. static basic_json from_cbor(const T* ptr, std::size_t len,
  21455. const bool strict = true,
  21456. const bool allow_exceptions = true,
  21457. const cbor_tag_handler_t tag_handler = cbor_tag_handler_t::error)
  21458. {
  21459. return from_cbor(ptr, ptr + len, strict, allow_exceptions, tag_handler);
  21460. }
  21461. JSON_HEDLEY_WARN_UNUSED_RESULT
  21462. JSON_HEDLEY_DEPRECATED_FOR(3.8.0, from_cbor(ptr, ptr + len))
  21463. static basic_json from_cbor(detail::span_input_adapter&& i,
  21464. const bool strict = true,
  21465. const bool allow_exceptions = true,
  21466. const cbor_tag_handler_t tag_handler = cbor_tag_handler_t::error)
  21467. {
  21468. basic_json result;
  21469. detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
  21470. auto ia = i.get();
  21471. // NOLINTNEXTLINE(hicpp-move-const-arg,performance-move-const-arg)
  21472. const bool res = binary_reader<decltype(ia)>(std::move(ia)).sax_parse(input_format_t::cbor, &sdp, strict, tag_handler);
  21473. return res ? result : basic_json(value_t::discarded);
  21474. }
  21475. /*!
  21476. @brief create a JSON value from an input in MessagePack format
  21477. Deserializes a given input @a i to a JSON value using the MessagePack
  21478. serialization format.
  21479. The library maps MessagePack types to JSON value types as follows:
  21480. MessagePack type | JSON value type | first byte
  21481. ---------------- | --------------- | ----------
  21482. positive fixint | number_unsigned | 0x00..0x7F
  21483. fixmap | object | 0x80..0x8F
  21484. fixarray | array | 0x90..0x9F
  21485. fixstr | string | 0xA0..0xBF
  21486. nil | `null` | 0xC0
  21487. false | `false` | 0xC2
  21488. true | `true` | 0xC3
  21489. float 32 | number_float | 0xCA
  21490. float 64 | number_float | 0xCB
  21491. uint 8 | number_unsigned | 0xCC
  21492. uint 16 | number_unsigned | 0xCD
  21493. uint 32 | number_unsigned | 0xCE
  21494. uint 64 | number_unsigned | 0xCF
  21495. int 8 | number_integer | 0xD0
  21496. int 16 | number_integer | 0xD1
  21497. int 32 | number_integer | 0xD2
  21498. int 64 | number_integer | 0xD3
  21499. str 8 | string | 0xD9
  21500. str 16 | string | 0xDA
  21501. str 32 | string | 0xDB
  21502. array 16 | array | 0xDC
  21503. array 32 | array | 0xDD
  21504. map 16 | object | 0xDE
  21505. map 32 | object | 0xDF
  21506. bin 8 | binary | 0xC4
  21507. bin 16 | binary | 0xC5
  21508. bin 32 | binary | 0xC6
  21509. ext 8 | binary | 0xC7
  21510. ext 16 | binary | 0xC8
  21511. ext 32 | binary | 0xC9
  21512. fixext 1 | binary | 0xD4
  21513. fixext 2 | binary | 0xD5
  21514. fixext 4 | binary | 0xD6
  21515. fixext 8 | binary | 0xD7
  21516. fixext 16 | binary | 0xD8
  21517. negative fixint | number_integer | 0xE0-0xFF
  21518. @note Any MessagePack output created @ref to_msgpack can be successfully
  21519. parsed by @ref from_msgpack.
  21520. @param[in] i an input in MessagePack format convertible to an input
  21521. adapter
  21522. @param[in] strict whether to expect the input to be consumed until EOF
  21523. (true by default)
  21524. @param[in] allow_exceptions whether to throw exceptions in case of a
  21525. parse error (optional, true by default)
  21526. @return deserialized JSON value; in case of a parse error and
  21527. @a allow_exceptions set to `false`, the return value will be
  21528. value_t::discarded.
  21529. @throw parse_error.110 if the given input ends prematurely or the end of
  21530. file was not reached when @a strict was set to true
  21531. @throw parse_error.112 if unsupported features from MessagePack were
  21532. used in the given input @a i or if the input is not valid MessagePack
  21533. @throw parse_error.113 if a string was expected as map key, but not found
  21534. @complexity Linear in the size of the input @a i.
  21535. @liveexample{The example shows the deserialization of a byte vector in
  21536. MessagePack format to a JSON value.,from_msgpack}
  21537. @sa http://msgpack.org
  21538. @sa see @ref to_msgpack(const basic_json&) for the analogous serialization
  21539. @sa see @ref from_cbor(InputType&&, const bool, const bool, const cbor_tag_handler_t) for the
  21540. related CBOR format
  21541. @sa see @ref from_ubjson(InputType&&, const bool, const bool) for
  21542. the related UBJSON format
  21543. @sa see @ref from_bson(InputType&&, const bool, const bool) for
  21544. the related BSON format
  21545. @since version 2.0.9; parameter @a start_index since 2.1.1; changed to
  21546. consume input adapters, removed start_index parameter, and added
  21547. @a strict parameter since 3.0.0; added @a allow_exceptions parameter
  21548. since 3.2.0
  21549. */
  21550. template<typename InputType>
  21551. JSON_HEDLEY_WARN_UNUSED_RESULT
  21552. static basic_json from_msgpack(InputType&& i,
  21553. const bool strict = true,
  21554. const bool allow_exceptions = true)
  21555. {
  21556. basic_json result;
  21557. detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
  21558. auto ia = detail::input_adapter(std::forward<InputType>(i));
  21559. const bool res = binary_reader<decltype(ia)>(std::move(ia)).sax_parse(input_format_t::msgpack, &sdp, strict);
  21560. return res ? result : basic_json(value_t::discarded);
  21561. }
  21562. /*!
  21563. @copydoc from_msgpack(InputType&&, const bool, const bool)
  21564. */
  21565. template<typename IteratorType>
  21566. JSON_HEDLEY_WARN_UNUSED_RESULT
  21567. static basic_json from_msgpack(IteratorType first, IteratorType last,
  21568. const bool strict = true,
  21569. const bool allow_exceptions = true)
  21570. {
  21571. basic_json result;
  21572. detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
  21573. auto ia = detail::input_adapter(std::move(first), std::move(last));
  21574. const bool res = binary_reader<decltype(ia)>(std::move(ia)).sax_parse(input_format_t::msgpack, &sdp, strict);
  21575. return res ? result : basic_json(value_t::discarded);
  21576. }
  21577. template<typename T>
  21578. JSON_HEDLEY_WARN_UNUSED_RESULT
  21579. JSON_HEDLEY_DEPRECATED_FOR(3.8.0, from_msgpack(ptr, ptr + len))
  21580. static basic_json from_msgpack(const T* ptr, std::size_t len,
  21581. const bool strict = true,
  21582. const bool allow_exceptions = true)
  21583. {
  21584. return from_msgpack(ptr, ptr + len, strict, allow_exceptions);
  21585. }
  21586. JSON_HEDLEY_WARN_UNUSED_RESULT
  21587. JSON_HEDLEY_DEPRECATED_FOR(3.8.0, from_msgpack(ptr, ptr + len))
  21588. static basic_json from_msgpack(detail::span_input_adapter&& i,
  21589. const bool strict = true,
  21590. const bool allow_exceptions = true)
  21591. {
  21592. basic_json result;
  21593. detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
  21594. auto ia = i.get();
  21595. // NOLINTNEXTLINE(hicpp-move-const-arg,performance-move-const-arg)
  21596. const bool res = binary_reader<decltype(ia)>(std::move(ia)).sax_parse(input_format_t::msgpack, &sdp, strict);
  21597. return res ? result : basic_json(value_t::discarded);
  21598. }
  21599. /*!
  21600. @brief create a JSON value from an input in UBJSON format
  21601. Deserializes a given input @a i to a JSON value using the UBJSON (Universal
  21602. Binary JSON) serialization format.
  21603. The library maps UBJSON types to JSON value types as follows:
  21604. UBJSON type | JSON value type | marker
  21605. ----------- | --------------------------------------- | ------
  21606. no-op | *no value, next value is read* | `N`
  21607. null | `null` | `Z`
  21608. false | `false` | `F`
  21609. true | `true` | `T`
  21610. float32 | number_float | `d`
  21611. float64 | number_float | `D`
  21612. uint8 | number_unsigned | `U`
  21613. int8 | number_integer | `i`
  21614. int16 | number_integer | `I`
  21615. int32 | number_integer | `l`
  21616. int64 | number_integer | `L`
  21617. high-precision number | number_integer, number_unsigned, or number_float - depends on number string | 'H'
  21618. string | string | `S`
  21619. char | string | `C`
  21620. array | array (optimized values are supported) | `[`
  21621. object | object (optimized values are supported) | `{`
  21622. @note The mapping is **complete** in the sense that any UBJSON value can
  21623. be converted to a JSON value.
  21624. @param[in] i an input in UBJSON format convertible to an input adapter
  21625. @param[in] strict whether to expect the input to be consumed until EOF
  21626. (true by default)
  21627. @param[in] allow_exceptions whether to throw exceptions in case of a
  21628. parse error (optional, true by default)
  21629. @return deserialized JSON value; in case of a parse error and
  21630. @a allow_exceptions set to `false`, the return value will be
  21631. value_t::discarded.
  21632. @throw parse_error.110 if the given input ends prematurely or the end of
  21633. file was not reached when @a strict was set to true
  21634. @throw parse_error.112 if a parse error occurs
  21635. @throw parse_error.113 if a string could not be parsed successfully
  21636. @complexity Linear in the size of the input @a i.
  21637. @liveexample{The example shows the deserialization of a byte vector in
  21638. UBJSON format to a JSON value.,from_ubjson}
  21639. @sa http://ubjson.org
  21640. @sa see @ref to_ubjson(const basic_json&, const bool, const bool) for the
  21641. analogous serialization
  21642. @sa see @ref from_cbor(InputType&&, const bool, const bool, const cbor_tag_handler_t) for the
  21643. related CBOR format
  21644. @sa see @ref from_msgpack(InputType&&, const bool, const bool) for
  21645. the related MessagePack format
  21646. @sa see @ref from_bson(InputType&&, const bool, const bool) for
  21647. the related BSON format
  21648. @since version 3.1.0; added @a allow_exceptions parameter since 3.2.0
  21649. */
  21650. template<typename InputType>
  21651. JSON_HEDLEY_WARN_UNUSED_RESULT
  21652. static basic_json from_ubjson(InputType&& i,
  21653. const bool strict = true,
  21654. const bool allow_exceptions = true)
  21655. {
  21656. basic_json result;
  21657. detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
  21658. auto ia = detail::input_adapter(std::forward<InputType>(i));
  21659. const bool res = binary_reader<decltype(ia)>(std::move(ia)).sax_parse(input_format_t::ubjson, &sdp, strict);
  21660. return res ? result : basic_json(value_t::discarded);
  21661. }
  21662. /*!
  21663. @copydoc from_ubjson(InputType&&, const bool, const bool)
  21664. */
  21665. template<typename IteratorType>
  21666. JSON_HEDLEY_WARN_UNUSED_RESULT
  21667. static basic_json from_ubjson(IteratorType first, IteratorType last,
  21668. const bool strict = true,
  21669. const bool allow_exceptions = true)
  21670. {
  21671. basic_json result;
  21672. detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
  21673. auto ia = detail::input_adapter(std::move(first), std::move(last));
  21674. const bool res = binary_reader<decltype(ia)>(std::move(ia)).sax_parse(input_format_t::ubjson, &sdp, strict);
  21675. return res ? result : basic_json(value_t::discarded);
  21676. }
  21677. template<typename T>
  21678. JSON_HEDLEY_WARN_UNUSED_RESULT
  21679. JSON_HEDLEY_DEPRECATED_FOR(3.8.0, from_ubjson(ptr, ptr + len))
  21680. static basic_json from_ubjson(const T* ptr, std::size_t len,
  21681. const bool strict = true,
  21682. const bool allow_exceptions = true)
  21683. {
  21684. return from_ubjson(ptr, ptr + len, strict, allow_exceptions);
  21685. }
  21686. JSON_HEDLEY_WARN_UNUSED_RESULT
  21687. JSON_HEDLEY_DEPRECATED_FOR(3.8.0, from_ubjson(ptr, ptr + len))
  21688. static basic_json from_ubjson(detail::span_input_adapter&& i,
  21689. const bool strict = true,
  21690. const bool allow_exceptions = true)
  21691. {
  21692. basic_json result;
  21693. detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
  21694. auto ia = i.get();
  21695. // NOLINTNEXTLINE(hicpp-move-const-arg,performance-move-const-arg)
  21696. const bool res = binary_reader<decltype(ia)>(std::move(ia)).sax_parse(input_format_t::ubjson, &sdp, strict);
  21697. return res ? result : basic_json(value_t::discarded);
  21698. }
  21699. /*!
  21700. @brief Create a JSON value from an input in BSON format
  21701. Deserializes a given input @a i to a JSON value using the BSON (Binary JSON)
  21702. serialization format.
  21703. The library maps BSON record types to JSON value types as follows:
  21704. BSON type | BSON marker byte | JSON value type
  21705. --------------- | ---------------- | ---------------------------
  21706. double | 0x01 | number_float
  21707. string | 0x02 | string
  21708. document | 0x03 | object
  21709. array | 0x04 | array
  21710. binary | 0x05 | binary
  21711. undefined | 0x06 | still unsupported
  21712. ObjectId | 0x07 | still unsupported
  21713. boolean | 0x08 | boolean
  21714. UTC Date-Time | 0x09 | still unsupported
  21715. null | 0x0A | null
  21716. Regular Expr. | 0x0B | still unsupported
  21717. DB Pointer | 0x0C | still unsupported
  21718. JavaScript Code | 0x0D | still unsupported
  21719. Symbol | 0x0E | still unsupported
  21720. JavaScript Code | 0x0F | still unsupported
  21721. int32 | 0x10 | number_integer
  21722. Timestamp | 0x11 | still unsupported
  21723. 128-bit decimal float | 0x13 | still unsupported
  21724. Max Key | 0x7F | still unsupported
  21725. Min Key | 0xFF | still unsupported
  21726. @warning The mapping is **incomplete**. The unsupported mappings
  21727. are indicated in the table above.
  21728. @param[in] i an input in BSON format convertible to an input adapter
  21729. @param[in] strict whether to expect the input to be consumed until EOF
  21730. (true by default)
  21731. @param[in] allow_exceptions whether to throw exceptions in case of a
  21732. parse error (optional, true by default)
  21733. @return deserialized JSON value; in case of a parse error and
  21734. @a allow_exceptions set to `false`, the return value will be
  21735. value_t::discarded.
  21736. @throw parse_error.114 if an unsupported BSON record type is encountered
  21737. @complexity Linear in the size of the input @a i.
  21738. @liveexample{The example shows the deserialization of a byte vector in
  21739. BSON format to a JSON value.,from_bson}
  21740. @sa http://bsonspec.org/spec.html
  21741. @sa see @ref to_bson(const basic_json&) for the analogous serialization
  21742. @sa see @ref from_cbor(InputType&&, const bool, const bool, const cbor_tag_handler_t) for the
  21743. related CBOR format
  21744. @sa see @ref from_msgpack(InputType&&, const bool, const bool) for
  21745. the related MessagePack format
  21746. @sa see @ref from_ubjson(InputType&&, const bool, const bool) for the
  21747. related UBJSON format
  21748. */
  21749. template<typename InputType>
  21750. JSON_HEDLEY_WARN_UNUSED_RESULT
  21751. static basic_json from_bson(InputType&& i,
  21752. const bool strict = true,
  21753. const bool allow_exceptions = true)
  21754. {
  21755. basic_json result;
  21756. detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
  21757. auto ia = detail::input_adapter(std::forward<InputType>(i));
  21758. const bool res = binary_reader<decltype(ia)>(std::move(ia)).sax_parse(input_format_t::bson, &sdp, strict);
  21759. return res ? result : basic_json(value_t::discarded);
  21760. }
  21761. /*!
  21762. @copydoc from_bson(InputType&&, const bool, const bool)
  21763. */
  21764. template<typename IteratorType>
  21765. JSON_HEDLEY_WARN_UNUSED_RESULT
  21766. static basic_json from_bson(IteratorType first, IteratorType last,
  21767. const bool strict = true,
  21768. const bool allow_exceptions = true)
  21769. {
  21770. basic_json result;
  21771. detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
  21772. auto ia = detail::input_adapter(std::move(first), std::move(last));
  21773. const bool res = binary_reader<decltype(ia)>(std::move(ia)).sax_parse(input_format_t::bson, &sdp, strict);
  21774. return res ? result : basic_json(value_t::discarded);
  21775. }
  21776. template<typename T>
  21777. JSON_HEDLEY_WARN_UNUSED_RESULT
  21778. JSON_HEDLEY_DEPRECATED_FOR(3.8.0, from_bson(ptr, ptr + len))
  21779. static basic_json from_bson(const T* ptr, std::size_t len,
  21780. const bool strict = true,
  21781. const bool allow_exceptions = true)
  21782. {
  21783. return from_bson(ptr, ptr + len, strict, allow_exceptions);
  21784. }
  21785. JSON_HEDLEY_WARN_UNUSED_RESULT
  21786. JSON_HEDLEY_DEPRECATED_FOR(3.8.0, from_bson(ptr, ptr + len))
  21787. static basic_json from_bson(detail::span_input_adapter&& i,
  21788. const bool strict = true,
  21789. const bool allow_exceptions = true)
  21790. {
  21791. basic_json result;
  21792. detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
  21793. auto ia = i.get();
  21794. // NOLINTNEXTLINE(hicpp-move-const-arg,performance-move-const-arg)
  21795. const bool res = binary_reader<decltype(ia)>(std::move(ia)).sax_parse(input_format_t::bson, &sdp, strict);
  21796. return res ? result : basic_json(value_t::discarded);
  21797. }
  21798. /// @}
  21799. //////////////////////////
  21800. // JSON Pointer support //
  21801. //////////////////////////
  21802. /// @name JSON Pointer functions
  21803. /// @{
  21804. /*!
  21805. @brief access specified element via JSON Pointer
  21806. Uses a JSON pointer to retrieve a reference to the respective JSON value.
  21807. No bound checking is performed. Similar to @ref operator[](const typename
  21808. object_t::key_type&), `null` values are created in arrays and objects if
  21809. necessary.
  21810. In particular:
  21811. - If the JSON pointer points to an object key that does not exist, it
  21812. is created an filled with a `null` value before a reference to it
  21813. is returned.
  21814. - If the JSON pointer points to an array index that does not exist, it
  21815. is created an filled with a `null` value before a reference to it
  21816. is returned. All indices between the current maximum and the given
  21817. index are also filled with `null`.
  21818. - The special value `-` is treated as a synonym for the index past the
  21819. end.
  21820. @param[in] ptr a JSON pointer
  21821. @return reference to the element pointed to by @a ptr
  21822. @complexity Constant.
  21823. @throw parse_error.106 if an array index begins with '0'
  21824. @throw parse_error.109 if an array index was not a number
  21825. @throw out_of_range.404 if the JSON pointer can not be resolved
  21826. @liveexample{The behavior is shown in the example.,operatorjson_pointer}
  21827. @since version 2.0.0
  21828. */
  21829. reference operator[](const json_pointer& ptr)
  21830. {
  21831. return ptr.get_unchecked(this);
  21832. }
  21833. /*!
  21834. @brief access specified element via JSON Pointer
  21835. Uses a JSON pointer to retrieve a reference to the respective JSON value.
  21836. No bound checking is performed. The function does not change the JSON
  21837. value; no `null` values are created. In particular, the special value
  21838. `-` yields an exception.
  21839. @param[in] ptr JSON pointer to the desired element
  21840. @return const reference to the element pointed to by @a ptr
  21841. @complexity Constant.
  21842. @throw parse_error.106 if an array index begins with '0'
  21843. @throw parse_error.109 if an array index was not a number
  21844. @throw out_of_range.402 if the array index '-' is used
  21845. @throw out_of_range.404 if the JSON pointer can not be resolved
  21846. @liveexample{The behavior is shown in the example.,operatorjson_pointer_const}
  21847. @since version 2.0.0
  21848. */
  21849. const_reference operator[](const json_pointer& ptr) const
  21850. {
  21851. return ptr.get_unchecked(this);
  21852. }
  21853. /*!
  21854. @brief access specified element via JSON Pointer
  21855. Returns a reference to the element at with specified JSON pointer @a ptr,
  21856. with bounds checking.
  21857. @param[in] ptr JSON pointer to the desired element
  21858. @return reference to the element pointed to by @a ptr
  21859. @throw parse_error.106 if an array index in the passed JSON pointer @a ptr
  21860. begins with '0'. See example below.
  21861. @throw parse_error.109 if an array index in the passed JSON pointer @a ptr
  21862. is not a number. See example below.
  21863. @throw out_of_range.401 if an array index in the passed JSON pointer @a ptr
  21864. is out of range. See example below.
  21865. @throw out_of_range.402 if the array index '-' is used in the passed JSON
  21866. pointer @a ptr. As `at` provides checked access (and no elements are
  21867. implicitly inserted), the index '-' is always invalid. See example below.
  21868. @throw out_of_range.403 if the JSON pointer describes a key of an object
  21869. which cannot be found. See example below.
  21870. @throw out_of_range.404 if the JSON pointer @a ptr can not be resolved.
  21871. See example below.
  21872. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  21873. changes in the JSON value.
  21874. @complexity Constant.
  21875. @since version 2.0.0
  21876. @liveexample{The behavior is shown in the example.,at_json_pointer}
  21877. */
  21878. reference at(const json_pointer& ptr)
  21879. {
  21880. return ptr.get_checked(this);
  21881. }
  21882. /*!
  21883. @brief access specified element via JSON Pointer
  21884. Returns a const reference to the element at with specified JSON pointer @a
  21885. ptr, with bounds checking.
  21886. @param[in] ptr JSON pointer to the desired element
  21887. @return reference to the element pointed to by @a ptr
  21888. @throw parse_error.106 if an array index in the passed JSON pointer @a ptr
  21889. begins with '0'. See example below.
  21890. @throw parse_error.109 if an array index in the passed JSON pointer @a ptr
  21891. is not a number. See example below.
  21892. @throw out_of_range.401 if an array index in the passed JSON pointer @a ptr
  21893. is out of range. See example below.
  21894. @throw out_of_range.402 if the array index '-' is used in the passed JSON
  21895. pointer @a ptr. As `at` provides checked access (and no elements are
  21896. implicitly inserted), the index '-' is always invalid. See example below.
  21897. @throw out_of_range.403 if the JSON pointer describes a key of an object
  21898. which cannot be found. See example below.
  21899. @throw out_of_range.404 if the JSON pointer @a ptr can not be resolved.
  21900. See example below.
  21901. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  21902. changes in the JSON value.
  21903. @complexity Constant.
  21904. @since version 2.0.0
  21905. @liveexample{The behavior is shown in the example.,at_json_pointer_const}
  21906. */
  21907. const_reference at(const json_pointer& ptr) const
  21908. {
  21909. return ptr.get_checked(this);
  21910. }
  21911. /*!
  21912. @brief return flattened JSON value
  21913. The function creates a JSON object whose keys are JSON pointers (see [RFC
  21914. 6901](https://tools.ietf.org/html/rfc6901)) and whose values are all
  21915. primitive. The original JSON value can be restored using the @ref
  21916. unflatten() function.
  21917. @return an object that maps JSON pointers to primitive values
  21918. @note Empty objects and arrays are flattened to `null` and will not be
  21919. reconstructed correctly by the @ref unflatten() function.
  21920. @complexity Linear in the size the JSON value.
  21921. @liveexample{The following code shows how a JSON object is flattened to an
  21922. object whose keys consist of JSON pointers.,flatten}
  21923. @sa see @ref unflatten() for the reverse function
  21924. @since version 2.0.0
  21925. */
  21926. basic_json flatten() const
  21927. {
  21928. basic_json result(value_t::object);
  21929. json_pointer::flatten("", *this, result);
  21930. return result;
  21931. }
  21932. /*!
  21933. @brief unflatten a previously flattened JSON value
  21934. The function restores the arbitrary nesting of a JSON value that has been
  21935. flattened before using the @ref flatten() function. The JSON value must
  21936. meet certain constraints:
  21937. 1. The value must be an object.
  21938. 2. The keys must be JSON pointers (see
  21939. [RFC 6901](https://tools.ietf.org/html/rfc6901))
  21940. 3. The mapped values must be primitive JSON types.
  21941. @return the original JSON from a flattened version
  21942. @note Empty objects and arrays are flattened by @ref flatten() to `null`
  21943. values and can not unflattened to their original type. Apart from
  21944. this example, for a JSON value `j`, the following is always true:
  21945. `j == j.flatten().unflatten()`.
  21946. @complexity Linear in the size the JSON value.
  21947. @throw type_error.314 if value is not an object
  21948. @throw type_error.315 if object values are not primitive
  21949. @liveexample{The following code shows how a flattened JSON object is
  21950. unflattened into the original nested JSON object.,unflatten}
  21951. @sa see @ref flatten() for the reverse function
  21952. @since version 2.0.0
  21953. */
  21954. basic_json unflatten() const
  21955. {
  21956. return json_pointer::unflatten(*this);
  21957. }
  21958. /// @}
  21959. //////////////////////////
  21960. // JSON Patch functions //
  21961. //////////////////////////
  21962. /// @name JSON Patch functions
  21963. /// @{
  21964. /*!
  21965. @brief applies a JSON patch
  21966. [JSON Patch](http://jsonpatch.com) defines a JSON document structure for
  21967. expressing a sequence of operations to apply to a JSON) document. With
  21968. this function, a JSON Patch is applied to the current JSON value by
  21969. executing all operations from the patch.
  21970. @param[in] json_patch JSON patch document
  21971. @return patched document
  21972. @note The application of a patch is atomic: Either all operations succeed
  21973. and the patched document is returned or an exception is thrown. In
  21974. any case, the original value is not changed: the patch is applied
  21975. to a copy of the value.
  21976. @throw parse_error.104 if the JSON patch does not consist of an array of
  21977. objects
  21978. @throw parse_error.105 if the JSON patch is malformed (e.g., mandatory
  21979. attributes are missing); example: `"operation add must have member path"`
  21980. @throw out_of_range.401 if an array index is out of range.
  21981. @throw out_of_range.403 if a JSON pointer inside the patch could not be
  21982. resolved successfully in the current JSON value; example: `"key baz not
  21983. found"`
  21984. @throw out_of_range.405 if JSON pointer has no parent ("add", "remove",
  21985. "move")
  21986. @throw other_error.501 if "test" operation was unsuccessful
  21987. @complexity Linear in the size of the JSON value and the length of the
  21988. JSON patch. As usually only a fraction of the JSON value is affected by
  21989. the patch, the complexity can usually be neglected.
  21990. @liveexample{The following code shows how a JSON patch is applied to a
  21991. value.,patch}
  21992. @sa see @ref diff -- create a JSON patch by comparing two JSON values
  21993. @sa [RFC 6902 (JSON Patch)](https://tools.ietf.org/html/rfc6902)
  21994. @sa [RFC 6901 (JSON Pointer)](https://tools.ietf.org/html/rfc6901)
  21995. @since version 2.0.0
  21996. */
  21997. basic_json patch(const basic_json& json_patch) const
  21998. {
  21999. // make a working copy to apply the patch to
  22000. basic_json result = *this;
  22001. // the valid JSON Patch operations
  22002. enum class patch_operations {add, remove, replace, move, copy, test, invalid};
  22003. const auto get_op = [](const std::string & op)
  22004. {
  22005. if (op == "add")
  22006. {
  22007. return patch_operations::add;
  22008. }
  22009. if (op == "remove")
  22010. {
  22011. return patch_operations::remove;
  22012. }
  22013. if (op == "replace")
  22014. {
  22015. return patch_operations::replace;
  22016. }
  22017. if (op == "move")
  22018. {
  22019. return patch_operations::move;
  22020. }
  22021. if (op == "copy")
  22022. {
  22023. return patch_operations::copy;
  22024. }
  22025. if (op == "test")
  22026. {
  22027. return patch_operations::test;
  22028. }
  22029. return patch_operations::invalid;
  22030. };
  22031. // wrapper for "add" operation; add value at ptr
  22032. const auto operation_add = [&result](json_pointer & ptr, basic_json val)
  22033. {
  22034. // adding to the root of the target document means replacing it
  22035. if (ptr.empty())
  22036. {
  22037. result = val;
  22038. return;
  22039. }
  22040. // make sure the top element of the pointer exists
  22041. json_pointer top_pointer = ptr.top();
  22042. if (top_pointer != ptr)
  22043. {
  22044. result.at(top_pointer);
  22045. }
  22046. // get reference to parent of JSON pointer ptr
  22047. const auto last_path = ptr.back();
  22048. ptr.pop_back();
  22049. basic_json& parent = result[ptr];
  22050. switch (parent.m_type)
  22051. {
  22052. case value_t::null:
  22053. case value_t::object:
  22054. {
  22055. // use operator[] to add value
  22056. parent[last_path] = val;
  22057. break;
  22058. }
  22059. case value_t::array:
  22060. {
  22061. if (last_path == "-")
  22062. {
  22063. // special case: append to back
  22064. parent.push_back(val);
  22065. }
  22066. else
  22067. {
  22068. const auto idx = json_pointer::array_index(last_path);
  22069. if (JSON_HEDLEY_UNLIKELY(idx > parent.size()))
  22070. {
  22071. // avoid undefined behavior
  22072. JSON_THROW(out_of_range::create(401, "array index " + std::to_string(idx) + " is out of range", parent));
  22073. }
  22074. // default case: insert add offset
  22075. parent.insert(parent.begin() + static_cast<difference_type>(idx), val);
  22076. }
  22077. break;
  22078. }
  22079. // if there exists a parent it cannot be primitive
  22080. case value_t::string: // LCOV_EXCL_LINE
  22081. case value_t::boolean: // LCOV_EXCL_LINE
  22082. case value_t::number_integer: // LCOV_EXCL_LINE
  22083. case value_t::number_unsigned: // LCOV_EXCL_LINE
  22084. case value_t::number_float: // LCOV_EXCL_LINE
  22085. case value_t::binary: // LCOV_EXCL_LINE
  22086. case value_t::discarded: // LCOV_EXCL_LINE
  22087. default: // LCOV_EXCL_LINE
  22088. JSON_ASSERT(false); // NOLINT(cert-dcl03-c,hicpp-static-assert,misc-static-assert) LCOV_EXCL_LINE
  22089. }
  22090. };
  22091. // wrapper for "remove" operation; remove value at ptr
  22092. const auto operation_remove = [this, &result](json_pointer & ptr)
  22093. {
  22094. // get reference to parent of JSON pointer ptr
  22095. const auto last_path = ptr.back();
  22096. ptr.pop_back();
  22097. basic_json& parent = result.at(ptr);
  22098. // remove child
  22099. if (parent.is_object())
  22100. {
  22101. // perform range check
  22102. auto it = parent.find(last_path);
  22103. if (JSON_HEDLEY_LIKELY(it != parent.end()))
  22104. {
  22105. parent.erase(it);
  22106. }
  22107. else
  22108. {
  22109. JSON_THROW(out_of_range::create(403, "key '" + last_path + "' not found", *this));
  22110. }
  22111. }
  22112. else if (parent.is_array())
  22113. {
  22114. // note erase performs range check
  22115. parent.erase(json_pointer::array_index(last_path));
  22116. }
  22117. };
  22118. // type check: top level value must be an array
  22119. if (JSON_HEDLEY_UNLIKELY(!json_patch.is_array()))
  22120. {
  22121. JSON_THROW(parse_error::create(104, 0, "JSON patch must be an array of objects", json_patch));
  22122. }
  22123. // iterate and apply the operations
  22124. for (const auto& val : json_patch)
  22125. {
  22126. // wrapper to get a value for an operation
  22127. const auto get_value = [&val](const std::string & op,
  22128. const std::string & member,
  22129. bool string_type) -> basic_json &
  22130. {
  22131. // find value
  22132. auto it = val.m_value.object->find(member);
  22133. // context-sensitive error message
  22134. const auto error_msg = (op == "op") ? "operation" : "operation '" + op + "'";
  22135. // check if desired value is present
  22136. if (JSON_HEDLEY_UNLIKELY(it == val.m_value.object->end()))
  22137. {
  22138. // NOLINTNEXTLINE(performance-inefficient-string-concatenation)
  22139. JSON_THROW(parse_error::create(105, 0, error_msg + " must have member '" + member + "'", val));
  22140. }
  22141. // check if result is of type string
  22142. if (JSON_HEDLEY_UNLIKELY(string_type && !it->second.is_string()))
  22143. {
  22144. // NOLINTNEXTLINE(performance-inefficient-string-concatenation)
  22145. JSON_THROW(parse_error::create(105, 0, error_msg + " must have string member '" + member + "'", val));
  22146. }
  22147. // no error: return value
  22148. return it->second;
  22149. };
  22150. // type check: every element of the array must be an object
  22151. if (JSON_HEDLEY_UNLIKELY(!val.is_object()))
  22152. {
  22153. JSON_THROW(parse_error::create(104, 0, "JSON patch must be an array of objects", val));
  22154. }
  22155. // collect mandatory members
  22156. const auto op = get_value("op", "op", true).template get<std::string>();
  22157. const auto path = get_value(op, "path", true).template get<std::string>();
  22158. json_pointer ptr(path);
  22159. switch (get_op(op))
  22160. {
  22161. case patch_operations::add:
  22162. {
  22163. operation_add(ptr, get_value("add", "value", false));
  22164. break;
  22165. }
  22166. case patch_operations::remove:
  22167. {
  22168. operation_remove(ptr);
  22169. break;
  22170. }
  22171. case patch_operations::replace:
  22172. {
  22173. // the "path" location must exist - use at()
  22174. result.at(ptr) = get_value("replace", "value", false);
  22175. break;
  22176. }
  22177. case patch_operations::move:
  22178. {
  22179. const auto from_path = get_value("move", "from", true).template get<std::string>();
  22180. json_pointer from_ptr(from_path);
  22181. // the "from" location must exist - use at()
  22182. basic_json v = result.at(from_ptr);
  22183. // The move operation is functionally identical to a
  22184. // "remove" operation on the "from" location, followed
  22185. // immediately by an "add" operation at the target
  22186. // location with the value that was just removed.
  22187. operation_remove(from_ptr);
  22188. operation_add(ptr, v);
  22189. break;
  22190. }
  22191. case patch_operations::copy:
  22192. {
  22193. const auto from_path = get_value("copy", "from", true).template get<std::string>();
  22194. const json_pointer from_ptr(from_path);
  22195. // the "from" location must exist - use at()
  22196. basic_json v = result.at(from_ptr);
  22197. // The copy is functionally identical to an "add"
  22198. // operation at the target location using the value
  22199. // specified in the "from" member.
  22200. operation_add(ptr, v);
  22201. break;
  22202. }
  22203. case patch_operations::test:
  22204. {
  22205. bool success = false;
  22206. JSON_TRY
  22207. {
  22208. // check if "value" matches the one at "path"
  22209. // the "path" location must exist - use at()
  22210. success = (result.at(ptr) == get_value("test", "value", false));
  22211. }
  22212. JSON_INTERNAL_CATCH (out_of_range&)
  22213. {
  22214. // ignore out of range errors: success remains false
  22215. }
  22216. // throw an exception if test fails
  22217. if (JSON_HEDLEY_UNLIKELY(!success))
  22218. {
  22219. JSON_THROW(other_error::create(501, "unsuccessful: " + val.dump(), val));
  22220. }
  22221. break;
  22222. }
  22223. case patch_operations::invalid:
  22224. default:
  22225. {
  22226. // op must be "add", "remove", "replace", "move", "copy", or
  22227. // "test"
  22228. JSON_THROW(parse_error::create(105, 0, "operation value '" + op + "' is invalid", val));
  22229. }
  22230. }
  22231. }
  22232. return result;
  22233. }
  22234. /*!
  22235. @brief creates a diff as a JSON patch
  22236. Creates a [JSON Patch](http://jsonpatch.com) so that value @a source can
  22237. be changed into the value @a target by calling @ref patch function.
  22238. @invariant For two JSON values @a source and @a target, the following code
  22239. yields always `true`:
  22240. @code {.cpp}
  22241. source.patch(diff(source, target)) == target;
  22242. @endcode
  22243. @note Currently, only `remove`, `add`, and `replace` operations are
  22244. generated.
  22245. @param[in] source JSON value to compare from
  22246. @param[in] target JSON value to compare against
  22247. @param[in] path helper value to create JSON pointers
  22248. @return a JSON patch to convert the @a source to @a target
  22249. @complexity Linear in the lengths of @a source and @a target.
  22250. @liveexample{The following code shows how a JSON patch is created as a
  22251. diff for two JSON values.,diff}
  22252. @sa see @ref patch -- apply a JSON patch
  22253. @sa see @ref merge_patch -- apply a JSON Merge Patch
  22254. @sa [RFC 6902 (JSON Patch)](https://tools.ietf.org/html/rfc6902)
  22255. @since version 2.0.0
  22256. */
  22257. JSON_HEDLEY_WARN_UNUSED_RESULT
  22258. static basic_json diff(const basic_json& source, const basic_json& target,
  22259. const std::string& path = "")
  22260. {
  22261. // the patch
  22262. basic_json result(value_t::array);
  22263. // if the values are the same, return empty patch
  22264. if (source == target)
  22265. {
  22266. return result;
  22267. }
  22268. if (source.type() != target.type())
  22269. {
  22270. // different types: replace value
  22271. result.push_back(
  22272. {
  22273. {"op", "replace"}, {"path", path}, {"value", target}
  22274. });
  22275. return result;
  22276. }
  22277. switch (source.type())
  22278. {
  22279. case value_t::array:
  22280. {
  22281. // first pass: traverse common elements
  22282. std::size_t i = 0;
  22283. while (i < source.size() && i < target.size())
  22284. {
  22285. // recursive call to compare array values at index i
  22286. auto temp_diff = diff(source[i], target[i], path + "/" + std::to_string(i));
  22287. result.insert(result.end(), temp_diff.begin(), temp_diff.end());
  22288. ++i;
  22289. }
  22290. // i now reached the end of at least one array
  22291. // in a second pass, traverse the remaining elements
  22292. // remove my remaining elements
  22293. const auto end_index = static_cast<difference_type>(result.size());
  22294. while (i < source.size())
  22295. {
  22296. // add operations in reverse order to avoid invalid
  22297. // indices
  22298. result.insert(result.begin() + end_index, object(
  22299. {
  22300. {"op", "remove"},
  22301. {"path", path + "/" + std::to_string(i)}
  22302. }));
  22303. ++i;
  22304. }
  22305. // add other remaining elements
  22306. while (i < target.size())
  22307. {
  22308. result.push_back(
  22309. {
  22310. {"op", "add"},
  22311. {"path", path + "/-"},
  22312. {"value", target[i]}
  22313. });
  22314. ++i;
  22315. }
  22316. break;
  22317. }
  22318. case value_t::object:
  22319. {
  22320. // first pass: traverse this object's elements
  22321. for (auto it = source.cbegin(); it != source.cend(); ++it)
  22322. {
  22323. // escape the key name to be used in a JSON patch
  22324. const auto path_key = path + "/" + detail::escape(it.key());
  22325. if (target.find(it.key()) != target.end())
  22326. {
  22327. // recursive call to compare object values at key it
  22328. auto temp_diff = diff(it.value(), target[it.key()], path_key);
  22329. result.insert(result.end(), temp_diff.begin(), temp_diff.end());
  22330. }
  22331. else
  22332. {
  22333. // found a key that is not in o -> remove it
  22334. result.push_back(object(
  22335. {
  22336. {"op", "remove"}, {"path", path_key}
  22337. }));
  22338. }
  22339. }
  22340. // second pass: traverse other object's elements
  22341. for (auto it = target.cbegin(); it != target.cend(); ++it)
  22342. {
  22343. if (source.find(it.key()) == source.end())
  22344. {
  22345. // found a key that is not in this -> add it
  22346. const auto path_key = path + "/" + detail::escape(it.key());
  22347. result.push_back(
  22348. {
  22349. {"op", "add"}, {"path", path_key},
  22350. {"value", it.value()}
  22351. });
  22352. }
  22353. }
  22354. break;
  22355. }
  22356. case value_t::null:
  22357. case value_t::string:
  22358. case value_t::boolean:
  22359. case value_t::number_integer:
  22360. case value_t::number_unsigned:
  22361. case value_t::number_float:
  22362. case value_t::binary:
  22363. case value_t::discarded:
  22364. default:
  22365. {
  22366. // both primitive type: replace value
  22367. result.push_back(
  22368. {
  22369. {"op", "replace"}, {"path", path}, {"value", target}
  22370. });
  22371. break;
  22372. }
  22373. }
  22374. return result;
  22375. }
  22376. /// @}
  22377. ////////////////////////////////
  22378. // JSON Merge Patch functions //
  22379. ////////////////////////////////
  22380. /// @name JSON Merge Patch functions
  22381. /// @{
  22382. /*!
  22383. @brief applies a JSON Merge Patch
  22384. The merge patch format is primarily intended for use with the HTTP PATCH
  22385. method as a means of describing a set of modifications to a target
  22386. resource's content. This function applies a merge patch to the current
  22387. JSON value.
  22388. The function implements the following algorithm from Section 2 of
  22389. [RFC 7396 (JSON Merge Patch)](https://tools.ietf.org/html/rfc7396):
  22390. ```
  22391. define MergePatch(Target, Patch):
  22392. if Patch is an Object:
  22393. if Target is not an Object:
  22394. Target = {} // Ignore the contents and set it to an empty Object
  22395. for each Name/Value pair in Patch:
  22396. if Value is null:
  22397. if Name exists in Target:
  22398. remove the Name/Value pair from Target
  22399. else:
  22400. Target[Name] = MergePatch(Target[Name], Value)
  22401. return Target
  22402. else:
  22403. return Patch
  22404. ```
  22405. Thereby, `Target` is the current object; that is, the patch is applied to
  22406. the current value.
  22407. @param[in] apply_patch the patch to apply
  22408. @complexity Linear in the lengths of @a patch.
  22409. @liveexample{The following code shows how a JSON Merge Patch is applied to
  22410. a JSON document.,merge_patch}
  22411. @sa see @ref patch -- apply a JSON patch
  22412. @sa [RFC 7396 (JSON Merge Patch)](https://tools.ietf.org/html/rfc7396)
  22413. @since version 3.0.0
  22414. */
  22415. void merge_patch(const basic_json& apply_patch)
  22416. {
  22417. if (apply_patch.is_object())
  22418. {
  22419. if (!is_object())
  22420. {
  22421. *this = object();
  22422. }
  22423. for (auto it = apply_patch.begin(); it != apply_patch.end(); ++it)
  22424. {
  22425. if (it.value().is_null())
  22426. {
  22427. erase(it.key());
  22428. }
  22429. else
  22430. {
  22431. operator[](it.key()).merge_patch(it.value());
  22432. }
  22433. }
  22434. }
  22435. else
  22436. {
  22437. *this = apply_patch;
  22438. }
  22439. }
  22440. /// @}
  22441. };
  22442. /*!
  22443. @brief user-defined to_string function for JSON values
  22444. This function implements a user-defined to_string for JSON objects.
  22445. @param[in] j a JSON object
  22446. @return a std::string object
  22447. */
  22448. NLOHMANN_BASIC_JSON_TPL_DECLARATION
  22449. std::string to_string(const NLOHMANN_BASIC_JSON_TPL& j)
  22450. {
  22451. return j.dump();
  22452. }
  22453. } // namespace nlohmann
  22454. ///////////////////////
  22455. // nonmember support //
  22456. ///////////////////////
  22457. // specialization of std::swap, and std::hash
  22458. namespace std
  22459. {
  22460. /// hash value for JSON objects
  22461. template<>
  22462. struct hash<nlohmann::json>
  22463. {
  22464. /*!
  22465. @brief return a hash value for a JSON object
  22466. @since version 1.0.0
  22467. */
  22468. std::size_t operator()(const nlohmann::json& j) const
  22469. {
  22470. return nlohmann::detail::hash(j);
  22471. }
  22472. };
  22473. /// specialization for std::less<value_t>
  22474. /// @note: do not remove the space after '<',
  22475. /// see https://github.com/nlohmann/json/pull/679
  22476. template<>
  22477. struct less<::nlohmann::detail::value_t>
  22478. {
  22479. /*!
  22480. @brief compare two value_t enum values
  22481. @since version 3.0.0
  22482. */
  22483. bool operator()(nlohmann::detail::value_t lhs,
  22484. nlohmann::detail::value_t rhs) const noexcept
  22485. {
  22486. return nlohmann::detail::operator<(lhs, rhs);
  22487. }
  22488. };
  22489. // C++20 prohibit function specialization in the std namespace.
  22490. #ifndef JSON_HAS_CPP_20
  22491. /*!
  22492. @brief exchanges the values of two JSON objects
  22493. @since version 1.0.0
  22494. */
  22495. template<>
  22496. inline void swap<nlohmann::json>(nlohmann::json& j1, nlohmann::json& j2) noexcept( // NOLINT(readability-inconsistent-declaration-parameter-name)
  22497. is_nothrow_move_constructible<nlohmann::json>::value&& // NOLINT(misc-redundant-expression)
  22498. is_nothrow_move_assignable<nlohmann::json>::value
  22499. )
  22500. {
  22501. j1.swap(j2);
  22502. }
  22503. #endif
  22504. } // namespace std
  22505. /*!
  22506. @brief user-defined string literal for JSON values
  22507. This operator implements a user-defined string literal for JSON objects. It
  22508. can be used by adding `"_json"` to a string literal and returns a JSON object
  22509. if no parse error occurred.
  22510. @param[in] s a string representation of a JSON object
  22511. @param[in] n the length of string @a s
  22512. @return a JSON object
  22513. @since version 1.0.0
  22514. */
  22515. JSON_HEDLEY_NON_NULL(1)
  22516. inline nlohmann::json operator "" _json(const char* s, std::size_t n)
  22517. {
  22518. return nlohmann::json::parse(s, s + n);
  22519. }
  22520. /*!
  22521. @brief user-defined string literal for JSON pointer
  22522. This operator implements a user-defined string literal for JSON Pointers. It
  22523. can be used by adding `"_json_pointer"` to a string literal and returns a JSON pointer
  22524. object if no parse error occurred.
  22525. @param[in] s a string representation of a JSON Pointer
  22526. @param[in] n the length of string @a s
  22527. @return a JSON pointer object
  22528. @since version 2.0.0
  22529. */
  22530. JSON_HEDLEY_NON_NULL(1)
  22531. inline nlohmann::json::json_pointer operator "" _json_pointer(const char* s, std::size_t n)
  22532. {
  22533. return nlohmann::json::json_pointer(std::string(s, n));
  22534. }
  22535. // #include <nlohmann/detail/macro_unscope.hpp>
  22536. // restore clang diagnostic settings
  22537. #if defined(__clang__)
  22538. #pragma clang diagnostic pop
  22539. #endif
  22540. // clean up
  22541. #undef JSON_ASSERT
  22542. #undef JSON_INTERNAL_CATCH
  22543. #undef JSON_CATCH
  22544. #undef JSON_THROW
  22545. #undef JSON_TRY
  22546. #undef JSON_PRIVATE_UNLESS_TESTED
  22547. #undef JSON_HAS_CPP_11
  22548. #undef JSON_HAS_CPP_14
  22549. #undef JSON_HAS_CPP_17
  22550. #undef JSON_HAS_CPP_20
  22551. #undef NLOHMANN_BASIC_JSON_TPL_DECLARATION
  22552. #undef NLOHMANN_BASIC_JSON_TPL
  22553. #undef JSON_EXPLICIT
  22554. #undef NLOHMANN_CAN_CALL_STD_FUNC_IMPL
  22555. // #include <nlohmann/thirdparty/hedley/hedley_undef.hpp>
  22556. #undef JSON_HEDLEY_ALWAYS_INLINE
  22557. #undef JSON_HEDLEY_ARM_VERSION
  22558. #undef JSON_HEDLEY_ARM_VERSION_CHECK
  22559. #undef JSON_HEDLEY_ARRAY_PARAM
  22560. #undef JSON_HEDLEY_ASSUME
  22561. #undef JSON_HEDLEY_BEGIN_C_DECLS
  22562. #undef JSON_HEDLEY_CLANG_HAS_ATTRIBUTE
  22563. #undef JSON_HEDLEY_CLANG_HAS_BUILTIN
  22564. #undef JSON_HEDLEY_CLANG_HAS_CPP_ATTRIBUTE
  22565. #undef JSON_HEDLEY_CLANG_HAS_DECLSPEC_DECLSPEC_ATTRIBUTE
  22566. #undef JSON_HEDLEY_CLANG_HAS_EXTENSION
  22567. #undef JSON_HEDLEY_CLANG_HAS_FEATURE
  22568. #undef JSON_HEDLEY_CLANG_HAS_WARNING
  22569. #undef JSON_HEDLEY_COMPCERT_VERSION
  22570. #undef JSON_HEDLEY_COMPCERT_VERSION_CHECK
  22571. #undef JSON_HEDLEY_CONCAT
  22572. #undef JSON_HEDLEY_CONCAT3
  22573. #undef JSON_HEDLEY_CONCAT3_EX
  22574. #undef JSON_HEDLEY_CONCAT_EX
  22575. #undef JSON_HEDLEY_CONST
  22576. #undef JSON_HEDLEY_CONSTEXPR
  22577. #undef JSON_HEDLEY_CONST_CAST
  22578. #undef JSON_HEDLEY_CPP_CAST
  22579. #undef JSON_HEDLEY_CRAY_VERSION
  22580. #undef JSON_HEDLEY_CRAY_VERSION_CHECK
  22581. #undef JSON_HEDLEY_C_DECL
  22582. #undef JSON_HEDLEY_DEPRECATED
  22583. #undef JSON_HEDLEY_DEPRECATED_FOR
  22584. #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL
  22585. #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_
  22586. #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED
  22587. #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES
  22588. #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS
  22589. #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNUSED_FUNCTION
  22590. #undef JSON_HEDLEY_DIAGNOSTIC_POP
  22591. #undef JSON_HEDLEY_DIAGNOSTIC_PUSH
  22592. #undef JSON_HEDLEY_DMC_VERSION
  22593. #undef JSON_HEDLEY_DMC_VERSION_CHECK
  22594. #undef JSON_HEDLEY_EMPTY_BASES
  22595. #undef JSON_HEDLEY_EMSCRIPTEN_VERSION
  22596. #undef JSON_HEDLEY_EMSCRIPTEN_VERSION_CHECK
  22597. #undef JSON_HEDLEY_END_C_DECLS
  22598. #undef JSON_HEDLEY_FLAGS
  22599. #undef JSON_HEDLEY_FLAGS_CAST
  22600. #undef JSON_HEDLEY_GCC_HAS_ATTRIBUTE
  22601. #undef JSON_HEDLEY_GCC_HAS_BUILTIN
  22602. #undef JSON_HEDLEY_GCC_HAS_CPP_ATTRIBUTE
  22603. #undef JSON_HEDLEY_GCC_HAS_DECLSPEC_ATTRIBUTE
  22604. #undef JSON_HEDLEY_GCC_HAS_EXTENSION
  22605. #undef JSON_HEDLEY_GCC_HAS_FEATURE
  22606. #undef JSON_HEDLEY_GCC_HAS_WARNING
  22607. #undef JSON_HEDLEY_GCC_NOT_CLANG_VERSION_CHECK
  22608. #undef JSON_HEDLEY_GCC_VERSION
  22609. #undef JSON_HEDLEY_GCC_VERSION_CHECK
  22610. #undef JSON_HEDLEY_GNUC_HAS_ATTRIBUTE
  22611. #undef JSON_HEDLEY_GNUC_HAS_BUILTIN
  22612. #undef JSON_HEDLEY_GNUC_HAS_CPP_ATTRIBUTE
  22613. #undef JSON_HEDLEY_GNUC_HAS_DECLSPEC_ATTRIBUTE
  22614. #undef JSON_HEDLEY_GNUC_HAS_EXTENSION
  22615. #undef JSON_HEDLEY_GNUC_HAS_FEATURE
  22616. #undef JSON_HEDLEY_GNUC_HAS_WARNING
  22617. #undef JSON_HEDLEY_GNUC_VERSION
  22618. #undef JSON_HEDLEY_GNUC_VERSION_CHECK
  22619. #undef JSON_HEDLEY_HAS_ATTRIBUTE
  22620. #undef JSON_HEDLEY_HAS_BUILTIN
  22621. #undef JSON_HEDLEY_HAS_CPP_ATTRIBUTE
  22622. #undef JSON_HEDLEY_HAS_CPP_ATTRIBUTE_NS
  22623. #undef JSON_HEDLEY_HAS_DECLSPEC_ATTRIBUTE
  22624. #undef JSON_HEDLEY_HAS_EXTENSION
  22625. #undef JSON_HEDLEY_HAS_FEATURE
  22626. #undef JSON_HEDLEY_HAS_WARNING
  22627. #undef JSON_HEDLEY_IAR_VERSION
  22628. #undef JSON_HEDLEY_IAR_VERSION_CHECK
  22629. #undef JSON_HEDLEY_IBM_VERSION
  22630. #undef JSON_HEDLEY_IBM_VERSION_CHECK
  22631. #undef JSON_HEDLEY_IMPORT
  22632. #undef JSON_HEDLEY_INLINE
  22633. #undef JSON_HEDLEY_INTEL_CL_VERSION
  22634. #undef JSON_HEDLEY_INTEL_CL_VERSION_CHECK
  22635. #undef JSON_HEDLEY_INTEL_VERSION
  22636. #undef JSON_HEDLEY_INTEL_VERSION_CHECK
  22637. #undef JSON_HEDLEY_IS_CONSTANT
  22638. #undef JSON_HEDLEY_IS_CONSTEXPR_
  22639. #undef JSON_HEDLEY_LIKELY
  22640. #undef JSON_HEDLEY_MALLOC
  22641. #undef JSON_HEDLEY_MCST_LCC_VERSION
  22642. #undef JSON_HEDLEY_MCST_LCC_VERSION_CHECK
  22643. #undef JSON_HEDLEY_MESSAGE
  22644. #undef JSON_HEDLEY_MSVC_VERSION
  22645. #undef JSON_HEDLEY_MSVC_VERSION_CHECK
  22646. #undef JSON_HEDLEY_NEVER_INLINE
  22647. #undef JSON_HEDLEY_NON_NULL
  22648. #undef JSON_HEDLEY_NO_ESCAPE
  22649. #undef JSON_HEDLEY_NO_RETURN
  22650. #undef JSON_HEDLEY_NO_THROW
  22651. #undef JSON_HEDLEY_NULL
  22652. #undef JSON_HEDLEY_PELLES_VERSION
  22653. #undef JSON_HEDLEY_PELLES_VERSION_CHECK
  22654. #undef JSON_HEDLEY_PGI_VERSION
  22655. #undef JSON_HEDLEY_PGI_VERSION_CHECK
  22656. #undef JSON_HEDLEY_PREDICT
  22657. #undef JSON_HEDLEY_PRINTF_FORMAT
  22658. #undef JSON_HEDLEY_PRIVATE
  22659. #undef JSON_HEDLEY_PUBLIC
  22660. #undef JSON_HEDLEY_PURE
  22661. #undef JSON_HEDLEY_REINTERPRET_CAST
  22662. #undef JSON_HEDLEY_REQUIRE
  22663. #undef JSON_HEDLEY_REQUIRE_CONSTEXPR
  22664. #undef JSON_HEDLEY_REQUIRE_MSG
  22665. #undef JSON_HEDLEY_RESTRICT
  22666. #undef JSON_HEDLEY_RETURNS_NON_NULL
  22667. #undef JSON_HEDLEY_SENTINEL
  22668. #undef JSON_HEDLEY_STATIC_ASSERT
  22669. #undef JSON_HEDLEY_STATIC_CAST
  22670. #undef JSON_HEDLEY_STRINGIFY
  22671. #undef JSON_HEDLEY_STRINGIFY_EX
  22672. #undef JSON_HEDLEY_SUNPRO_VERSION
  22673. #undef JSON_HEDLEY_SUNPRO_VERSION_CHECK
  22674. #undef JSON_HEDLEY_TINYC_VERSION
  22675. #undef JSON_HEDLEY_TINYC_VERSION_CHECK
  22676. #undef JSON_HEDLEY_TI_ARMCL_VERSION
  22677. #undef JSON_HEDLEY_TI_ARMCL_VERSION_CHECK
  22678. #undef JSON_HEDLEY_TI_CL2000_VERSION
  22679. #undef JSON_HEDLEY_TI_CL2000_VERSION_CHECK
  22680. #undef JSON_HEDLEY_TI_CL430_VERSION
  22681. #undef JSON_HEDLEY_TI_CL430_VERSION_CHECK
  22682. #undef JSON_HEDLEY_TI_CL6X_VERSION
  22683. #undef JSON_HEDLEY_TI_CL6X_VERSION_CHECK
  22684. #undef JSON_HEDLEY_TI_CL7X_VERSION
  22685. #undef JSON_HEDLEY_TI_CL7X_VERSION_CHECK
  22686. #undef JSON_HEDLEY_TI_CLPRU_VERSION
  22687. #undef JSON_HEDLEY_TI_CLPRU_VERSION_CHECK
  22688. #undef JSON_HEDLEY_TI_VERSION
  22689. #undef JSON_HEDLEY_TI_VERSION_CHECK
  22690. #undef JSON_HEDLEY_UNAVAILABLE
  22691. #undef JSON_HEDLEY_UNLIKELY
  22692. #undef JSON_HEDLEY_UNPREDICTABLE
  22693. #undef JSON_HEDLEY_UNREACHABLE
  22694. #undef JSON_HEDLEY_UNREACHABLE_RETURN
  22695. #undef JSON_HEDLEY_VERSION
  22696. #undef JSON_HEDLEY_VERSION_DECODE_MAJOR
  22697. #undef JSON_HEDLEY_VERSION_DECODE_MINOR
  22698. #undef JSON_HEDLEY_VERSION_DECODE_REVISION
  22699. #undef JSON_HEDLEY_VERSION_ENCODE
  22700. #undef JSON_HEDLEY_WARNING
  22701. #undef JSON_HEDLEY_WARN_UNUSED_RESULT
  22702. #undef JSON_HEDLEY_WARN_UNUSED_RESULT_MSG
  22703. #undef JSON_HEDLEY_FALL_THROUGH
  22704. #endif // INCLUDE_NLOHMANN_JSON_HPP_