json.hpp 905 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448
  1. /*
  2. __ _____ _____ _____
  3. __| | __| | | | JSON for Modern C++
  4. | | |__ | | | | | | version 3.9.1
  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 9
  29. #define NLOHMANN_JSON_VERSION_PATCH 1
  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. #include <iosfwd> // istream, ostream
  35. #include <iterator> // random_access_iterator_tag
  36. #include <memory> // unique_ptr
  37. #include <numeric> // accumulate
  38. #include <string> // string, stoi, to_string
  39. #include <utility> // declval, forward, move, pair, swap
  40. #include <vector> // vector
  41. // #include <nlohmann/adl_serializer.hpp>
  42. #include <utility>
  43. // #include <nlohmann/detail/conversions/from_json.hpp>
  44. #include <algorithm> // transform
  45. #include <array> // array
  46. #include <forward_list> // forward_list
  47. #include <iterator> // inserter, front_inserter, end
  48. #include <map> // map
  49. #include <string> // string
  50. #include <tuple> // tuple, make_tuple
  51. #include <type_traits> // is_arithmetic, is_same, is_enum, underlying_type, is_convertible
  52. #include <unordered_map> // unordered_map
  53. #include <utility> // pair, declval
  54. #include <valarray> // valarray
  55. // #include <nlohmann/detail/exceptions.hpp>
  56. #include <exception> // exception
  57. #include <stdexcept> // runtime_error
  58. #include <string> // to_string
  59. // #include <nlohmann/detail/input/position_t.hpp>
  60. #include <cstddef> // size_t
  61. namespace nlohmann
  62. {
  63. namespace detail
  64. {
  65. /// struct to capture the start position of the current token
  66. struct position_t
  67. {
  68. /// the total number of characters read
  69. std::size_t chars_read_total = 0;
  70. /// the number of characters read in the current line
  71. std::size_t chars_read_current_line = 0;
  72. /// the number of lines read
  73. std::size_t lines_read = 0;
  74. /// conversion to size_t to preserve SAX interface
  75. constexpr operator size_t() const
  76. {
  77. return chars_read_total;
  78. }
  79. };
  80. } // namespace detail
  81. } // namespace nlohmann
  82. // #include <nlohmann/detail/macro_scope.hpp>
  83. #include <utility> // pair
  84. // #include <nlohmann/thirdparty/hedley/hedley.hpp>
  85. /* Hedley - https://nemequ.github.io/hedley
  86. * Created by Evan Nemerson <evan@nemerson.com>
  87. *
  88. * To the extent possible under law, the author(s) have dedicated all
  89. * copyright and related and neighboring rights to this software to
  90. * the public domain worldwide. This software is distributed without
  91. * any warranty.
  92. *
  93. * For details, see <http://creativecommons.org/publicdomain/zero/1.0/>.
  94. * SPDX-License-Identifier: CC0-1.0
  95. */
  96. #if !defined(JSON_HEDLEY_VERSION) || (JSON_HEDLEY_VERSION < 13)
  97. #if defined(JSON_HEDLEY_VERSION)
  98. #undef JSON_HEDLEY_VERSION
  99. #endif
  100. #define JSON_HEDLEY_VERSION 13
  101. #if defined(JSON_HEDLEY_STRINGIFY_EX)
  102. #undef JSON_HEDLEY_STRINGIFY_EX
  103. #endif
  104. #define JSON_HEDLEY_STRINGIFY_EX(x) #x
  105. #if defined(JSON_HEDLEY_STRINGIFY)
  106. #undef JSON_HEDLEY_STRINGIFY
  107. #endif
  108. #define JSON_HEDLEY_STRINGIFY(x) JSON_HEDLEY_STRINGIFY_EX(x)
  109. #if defined(JSON_HEDLEY_CONCAT_EX)
  110. #undef JSON_HEDLEY_CONCAT_EX
  111. #endif
  112. #define JSON_HEDLEY_CONCAT_EX(a,b) a##b
  113. #if defined(JSON_HEDLEY_CONCAT)
  114. #undef JSON_HEDLEY_CONCAT
  115. #endif
  116. #define JSON_HEDLEY_CONCAT(a,b) JSON_HEDLEY_CONCAT_EX(a,b)
  117. #if defined(JSON_HEDLEY_CONCAT3_EX)
  118. #undef JSON_HEDLEY_CONCAT3_EX
  119. #endif
  120. #define JSON_HEDLEY_CONCAT3_EX(a,b,c) a##b##c
  121. #if defined(JSON_HEDLEY_CONCAT3)
  122. #undef JSON_HEDLEY_CONCAT3
  123. #endif
  124. #define JSON_HEDLEY_CONCAT3(a,b,c) JSON_HEDLEY_CONCAT3_EX(a,b,c)
  125. #if defined(JSON_HEDLEY_VERSION_ENCODE)
  126. #undef JSON_HEDLEY_VERSION_ENCODE
  127. #endif
  128. #define JSON_HEDLEY_VERSION_ENCODE(major,minor,revision) (((major) * 1000000) + ((minor) * 1000) + (revision))
  129. #if defined(JSON_HEDLEY_VERSION_DECODE_MAJOR)
  130. #undef JSON_HEDLEY_VERSION_DECODE_MAJOR
  131. #endif
  132. #define JSON_HEDLEY_VERSION_DECODE_MAJOR(version) ((version) / 1000000)
  133. #if defined(JSON_HEDLEY_VERSION_DECODE_MINOR)
  134. #undef JSON_HEDLEY_VERSION_DECODE_MINOR
  135. #endif
  136. #define JSON_HEDLEY_VERSION_DECODE_MINOR(version) (((version) % 1000000) / 1000)
  137. #if defined(JSON_HEDLEY_VERSION_DECODE_REVISION)
  138. #undef JSON_HEDLEY_VERSION_DECODE_REVISION
  139. #endif
  140. #define JSON_HEDLEY_VERSION_DECODE_REVISION(version) ((version) % 1000)
  141. #if defined(JSON_HEDLEY_GNUC_VERSION)
  142. #undef JSON_HEDLEY_GNUC_VERSION
  143. #endif
  144. #if defined(__GNUC__) && defined(__GNUC_PATCHLEVEL__)
  145. #define JSON_HEDLEY_GNUC_VERSION JSON_HEDLEY_VERSION_ENCODE(__GNUC__, __GNUC_MINOR__, __GNUC_PATCHLEVEL__)
  146. #elif defined(__GNUC__)
  147. #define JSON_HEDLEY_GNUC_VERSION JSON_HEDLEY_VERSION_ENCODE(__GNUC__, __GNUC_MINOR__, 0)
  148. #endif
  149. #if defined(JSON_HEDLEY_GNUC_VERSION_CHECK)
  150. #undef JSON_HEDLEY_GNUC_VERSION_CHECK
  151. #endif
  152. #if defined(JSON_HEDLEY_GNUC_VERSION)
  153. #define JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_GNUC_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
  154. #else
  155. #define JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch) (0)
  156. #endif
  157. #if defined(JSON_HEDLEY_MSVC_VERSION)
  158. #undef JSON_HEDLEY_MSVC_VERSION
  159. #endif
  160. #if defined(_MSC_FULL_VER) && (_MSC_FULL_VER >= 140000000)
  161. #define JSON_HEDLEY_MSVC_VERSION JSON_HEDLEY_VERSION_ENCODE(_MSC_FULL_VER / 10000000, (_MSC_FULL_VER % 10000000) / 100000, (_MSC_FULL_VER % 100000) / 100)
  162. #elif defined(_MSC_FULL_VER)
  163. #define JSON_HEDLEY_MSVC_VERSION JSON_HEDLEY_VERSION_ENCODE(_MSC_FULL_VER / 1000000, (_MSC_FULL_VER % 1000000) / 10000, (_MSC_FULL_VER % 10000) / 10)
  164. #elif defined(_MSC_VER)
  165. #define JSON_HEDLEY_MSVC_VERSION JSON_HEDLEY_VERSION_ENCODE(_MSC_VER / 100, _MSC_VER % 100, 0)
  166. #endif
  167. #if defined(JSON_HEDLEY_MSVC_VERSION_CHECK)
  168. #undef JSON_HEDLEY_MSVC_VERSION_CHECK
  169. #endif
  170. #if !defined(_MSC_VER)
  171. #define JSON_HEDLEY_MSVC_VERSION_CHECK(major,minor,patch) (0)
  172. #elif defined(_MSC_VER) && (_MSC_VER >= 1400)
  173. #define JSON_HEDLEY_MSVC_VERSION_CHECK(major,minor,patch) (_MSC_FULL_VER >= ((major * 10000000) + (minor * 100000) + (patch)))
  174. #elif defined(_MSC_VER) && (_MSC_VER >= 1200)
  175. #define JSON_HEDLEY_MSVC_VERSION_CHECK(major,minor,patch) (_MSC_FULL_VER >= ((major * 1000000) + (minor * 10000) + (patch)))
  176. #else
  177. #define JSON_HEDLEY_MSVC_VERSION_CHECK(major,minor,patch) (_MSC_VER >= ((major * 100) + (minor)))
  178. #endif
  179. #if defined(JSON_HEDLEY_INTEL_VERSION)
  180. #undef JSON_HEDLEY_INTEL_VERSION
  181. #endif
  182. #if defined(__INTEL_COMPILER) && defined(__INTEL_COMPILER_UPDATE)
  183. #define JSON_HEDLEY_INTEL_VERSION JSON_HEDLEY_VERSION_ENCODE(__INTEL_COMPILER / 100, __INTEL_COMPILER % 100, __INTEL_COMPILER_UPDATE)
  184. #elif defined(__INTEL_COMPILER)
  185. #define JSON_HEDLEY_INTEL_VERSION JSON_HEDLEY_VERSION_ENCODE(__INTEL_COMPILER / 100, __INTEL_COMPILER % 100, 0)
  186. #endif
  187. #if defined(JSON_HEDLEY_INTEL_VERSION_CHECK)
  188. #undef JSON_HEDLEY_INTEL_VERSION_CHECK
  189. #endif
  190. #if defined(JSON_HEDLEY_INTEL_VERSION)
  191. #define JSON_HEDLEY_INTEL_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_INTEL_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
  192. #else
  193. #define JSON_HEDLEY_INTEL_VERSION_CHECK(major,minor,patch) (0)
  194. #endif
  195. #if defined(JSON_HEDLEY_PGI_VERSION)
  196. #undef JSON_HEDLEY_PGI_VERSION
  197. #endif
  198. #if defined(__PGI) && defined(__PGIC__) && defined(__PGIC_MINOR__) && defined(__PGIC_PATCHLEVEL__)
  199. #define JSON_HEDLEY_PGI_VERSION JSON_HEDLEY_VERSION_ENCODE(__PGIC__, __PGIC_MINOR__, __PGIC_PATCHLEVEL__)
  200. #endif
  201. #if defined(JSON_HEDLEY_PGI_VERSION_CHECK)
  202. #undef JSON_HEDLEY_PGI_VERSION_CHECK
  203. #endif
  204. #if defined(JSON_HEDLEY_PGI_VERSION)
  205. #define JSON_HEDLEY_PGI_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_PGI_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
  206. #else
  207. #define JSON_HEDLEY_PGI_VERSION_CHECK(major,minor,patch) (0)
  208. #endif
  209. #if defined(JSON_HEDLEY_SUNPRO_VERSION)
  210. #undef JSON_HEDLEY_SUNPRO_VERSION
  211. #endif
  212. #if defined(__SUNPRO_C) && (__SUNPRO_C > 0x1000)
  213. #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)
  214. #elif defined(__SUNPRO_C)
  215. #define JSON_HEDLEY_SUNPRO_VERSION JSON_HEDLEY_VERSION_ENCODE((__SUNPRO_C >> 8) & 0xf, (__SUNPRO_C >> 4) & 0xf, (__SUNPRO_C) & 0xf)
  216. #elif defined(__SUNPRO_CC) && (__SUNPRO_CC > 0x1000)
  217. #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)
  218. #elif defined(__SUNPRO_CC)
  219. #define JSON_HEDLEY_SUNPRO_VERSION JSON_HEDLEY_VERSION_ENCODE((__SUNPRO_CC >> 8) & 0xf, (__SUNPRO_CC >> 4) & 0xf, (__SUNPRO_CC) & 0xf)
  220. #endif
  221. #if defined(JSON_HEDLEY_SUNPRO_VERSION_CHECK)
  222. #undef JSON_HEDLEY_SUNPRO_VERSION_CHECK
  223. #endif
  224. #if defined(JSON_HEDLEY_SUNPRO_VERSION)
  225. #define JSON_HEDLEY_SUNPRO_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_SUNPRO_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
  226. #else
  227. #define JSON_HEDLEY_SUNPRO_VERSION_CHECK(major,minor,patch) (0)
  228. #endif
  229. #if defined(JSON_HEDLEY_EMSCRIPTEN_VERSION)
  230. #undef JSON_HEDLEY_EMSCRIPTEN_VERSION
  231. #endif
  232. #if defined(__EMSCRIPTEN__)
  233. #define JSON_HEDLEY_EMSCRIPTEN_VERSION JSON_HEDLEY_VERSION_ENCODE(__EMSCRIPTEN_major__, __EMSCRIPTEN_minor__, __EMSCRIPTEN_tiny__)
  234. #endif
  235. #if defined(JSON_HEDLEY_EMSCRIPTEN_VERSION_CHECK)
  236. #undef JSON_HEDLEY_EMSCRIPTEN_VERSION_CHECK
  237. #endif
  238. #if defined(JSON_HEDLEY_EMSCRIPTEN_VERSION)
  239. #define JSON_HEDLEY_EMSCRIPTEN_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_EMSCRIPTEN_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
  240. #else
  241. #define JSON_HEDLEY_EMSCRIPTEN_VERSION_CHECK(major,minor,patch) (0)
  242. #endif
  243. #if defined(JSON_HEDLEY_ARM_VERSION)
  244. #undef JSON_HEDLEY_ARM_VERSION
  245. #endif
  246. #if defined(__CC_ARM) && defined(__ARMCOMPILER_VERSION)
  247. #define JSON_HEDLEY_ARM_VERSION JSON_HEDLEY_VERSION_ENCODE(__ARMCOMPILER_VERSION / 1000000, (__ARMCOMPILER_VERSION % 1000000) / 10000, (__ARMCOMPILER_VERSION % 10000) / 100)
  248. #elif defined(__CC_ARM) && defined(__ARMCC_VERSION)
  249. #define JSON_HEDLEY_ARM_VERSION JSON_HEDLEY_VERSION_ENCODE(__ARMCC_VERSION / 1000000, (__ARMCC_VERSION % 1000000) / 10000, (__ARMCC_VERSION % 10000) / 100)
  250. #endif
  251. #if defined(JSON_HEDLEY_ARM_VERSION_CHECK)
  252. #undef JSON_HEDLEY_ARM_VERSION_CHECK
  253. #endif
  254. #if defined(JSON_HEDLEY_ARM_VERSION)
  255. #define JSON_HEDLEY_ARM_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_ARM_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
  256. #else
  257. #define JSON_HEDLEY_ARM_VERSION_CHECK(major,minor,patch) (0)
  258. #endif
  259. #if defined(JSON_HEDLEY_IBM_VERSION)
  260. #undef JSON_HEDLEY_IBM_VERSION
  261. #endif
  262. #if defined(__ibmxl__)
  263. #define JSON_HEDLEY_IBM_VERSION JSON_HEDLEY_VERSION_ENCODE(__ibmxl_version__, __ibmxl_release__, __ibmxl_modification__)
  264. #elif defined(__xlC__) && defined(__xlC_ver__)
  265. #define JSON_HEDLEY_IBM_VERSION JSON_HEDLEY_VERSION_ENCODE(__xlC__ >> 8, __xlC__ & 0xff, (__xlC_ver__ >> 8) & 0xff)
  266. #elif defined(__xlC__)
  267. #define JSON_HEDLEY_IBM_VERSION JSON_HEDLEY_VERSION_ENCODE(__xlC__ >> 8, __xlC__ & 0xff, 0)
  268. #endif
  269. #if defined(JSON_HEDLEY_IBM_VERSION_CHECK)
  270. #undef JSON_HEDLEY_IBM_VERSION_CHECK
  271. #endif
  272. #if defined(JSON_HEDLEY_IBM_VERSION)
  273. #define JSON_HEDLEY_IBM_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_IBM_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
  274. #else
  275. #define JSON_HEDLEY_IBM_VERSION_CHECK(major,minor,patch) (0)
  276. #endif
  277. #if defined(JSON_HEDLEY_TI_VERSION)
  278. #undef JSON_HEDLEY_TI_VERSION
  279. #endif
  280. #if \
  281. defined(__TI_COMPILER_VERSION__) && \
  282. ( \
  283. defined(__TMS470__) || defined(__TI_ARM__) || \
  284. defined(__MSP430__) || \
  285. defined(__TMS320C2000__) \
  286. )
  287. #if (__TI_COMPILER_VERSION__ >= 16000000)
  288. #define JSON_HEDLEY_TI_VERSION JSON_HEDLEY_VERSION_ENCODE(__TI_COMPILER_VERSION__ / 1000000, (__TI_COMPILER_VERSION__ % 1000000) / 1000, (__TI_COMPILER_VERSION__ % 1000))
  289. #endif
  290. #endif
  291. #if defined(JSON_HEDLEY_TI_VERSION_CHECK)
  292. #undef JSON_HEDLEY_TI_VERSION_CHECK
  293. #endif
  294. #if defined(JSON_HEDLEY_TI_VERSION)
  295. #define JSON_HEDLEY_TI_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_TI_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
  296. #else
  297. #define JSON_HEDLEY_TI_VERSION_CHECK(major,minor,patch) (0)
  298. #endif
  299. #if defined(JSON_HEDLEY_TI_CL2000_VERSION)
  300. #undef JSON_HEDLEY_TI_CL2000_VERSION
  301. #endif
  302. #if defined(__TI_COMPILER_VERSION__) && defined(__TMS320C2000__)
  303. #define JSON_HEDLEY_TI_CL2000_VERSION JSON_HEDLEY_VERSION_ENCODE(__TI_COMPILER_VERSION__ / 1000000, (__TI_COMPILER_VERSION__ % 1000000) / 1000, (__TI_COMPILER_VERSION__ % 1000))
  304. #endif
  305. #if defined(JSON_HEDLEY_TI_CL2000_VERSION_CHECK)
  306. #undef JSON_HEDLEY_TI_CL2000_VERSION_CHECK
  307. #endif
  308. #if defined(JSON_HEDLEY_TI_CL2000_VERSION)
  309. #define JSON_HEDLEY_TI_CL2000_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_TI_CL2000_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
  310. #else
  311. #define JSON_HEDLEY_TI_CL2000_VERSION_CHECK(major,minor,patch) (0)
  312. #endif
  313. #if defined(JSON_HEDLEY_TI_CL430_VERSION)
  314. #undef JSON_HEDLEY_TI_CL430_VERSION
  315. #endif
  316. #if defined(__TI_COMPILER_VERSION__) && defined(__MSP430__)
  317. #define JSON_HEDLEY_TI_CL430_VERSION JSON_HEDLEY_VERSION_ENCODE(__TI_COMPILER_VERSION__ / 1000000, (__TI_COMPILER_VERSION__ % 1000000) / 1000, (__TI_COMPILER_VERSION__ % 1000))
  318. #endif
  319. #if defined(JSON_HEDLEY_TI_CL430_VERSION_CHECK)
  320. #undef JSON_HEDLEY_TI_CL430_VERSION_CHECK
  321. #endif
  322. #if defined(JSON_HEDLEY_TI_CL430_VERSION)
  323. #define JSON_HEDLEY_TI_CL430_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_TI_CL430_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
  324. #else
  325. #define JSON_HEDLEY_TI_CL430_VERSION_CHECK(major,minor,patch) (0)
  326. #endif
  327. #if defined(JSON_HEDLEY_TI_ARMCL_VERSION)
  328. #undef JSON_HEDLEY_TI_ARMCL_VERSION
  329. #endif
  330. #if defined(__TI_COMPILER_VERSION__) && (defined(__TMS470__) || defined(__TI_ARM__))
  331. #define JSON_HEDLEY_TI_ARMCL_VERSION JSON_HEDLEY_VERSION_ENCODE(__TI_COMPILER_VERSION__ / 1000000, (__TI_COMPILER_VERSION__ % 1000000) / 1000, (__TI_COMPILER_VERSION__ % 1000))
  332. #endif
  333. #if defined(JSON_HEDLEY_TI_ARMCL_VERSION_CHECK)
  334. #undef JSON_HEDLEY_TI_ARMCL_VERSION_CHECK
  335. #endif
  336. #if defined(JSON_HEDLEY_TI_ARMCL_VERSION)
  337. #define JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_TI_ARMCL_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
  338. #else
  339. #define JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(major,minor,patch) (0)
  340. #endif
  341. #if defined(JSON_HEDLEY_TI_CL6X_VERSION)
  342. #undef JSON_HEDLEY_TI_CL6X_VERSION
  343. #endif
  344. #if defined(__TI_COMPILER_VERSION__) && defined(__TMS320C6X__)
  345. #define JSON_HEDLEY_TI_CL6X_VERSION JSON_HEDLEY_VERSION_ENCODE(__TI_COMPILER_VERSION__ / 1000000, (__TI_COMPILER_VERSION__ % 1000000) / 1000, (__TI_COMPILER_VERSION__ % 1000))
  346. #endif
  347. #if defined(JSON_HEDLEY_TI_CL6X_VERSION_CHECK)
  348. #undef JSON_HEDLEY_TI_CL6X_VERSION_CHECK
  349. #endif
  350. #if defined(JSON_HEDLEY_TI_CL6X_VERSION)
  351. #define JSON_HEDLEY_TI_CL6X_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_TI_CL6X_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
  352. #else
  353. #define JSON_HEDLEY_TI_CL6X_VERSION_CHECK(major,minor,patch) (0)
  354. #endif
  355. #if defined(JSON_HEDLEY_TI_CL7X_VERSION)
  356. #undef JSON_HEDLEY_TI_CL7X_VERSION
  357. #endif
  358. #if defined(__TI_COMPILER_VERSION__) && defined(__C7000__)
  359. #define JSON_HEDLEY_TI_CL7X_VERSION JSON_HEDLEY_VERSION_ENCODE(__TI_COMPILER_VERSION__ / 1000000, (__TI_COMPILER_VERSION__ % 1000000) / 1000, (__TI_COMPILER_VERSION__ % 1000))
  360. #endif
  361. #if defined(JSON_HEDLEY_TI_CL7X_VERSION_CHECK)
  362. #undef JSON_HEDLEY_TI_CL7X_VERSION_CHECK
  363. #endif
  364. #if defined(JSON_HEDLEY_TI_CL7X_VERSION)
  365. #define JSON_HEDLEY_TI_CL7X_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_TI_CL7X_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
  366. #else
  367. #define JSON_HEDLEY_TI_CL7X_VERSION_CHECK(major,minor,patch) (0)
  368. #endif
  369. #if defined(JSON_HEDLEY_TI_CLPRU_VERSION)
  370. #undef JSON_HEDLEY_TI_CLPRU_VERSION
  371. #endif
  372. #if defined(__TI_COMPILER_VERSION__) && defined(__PRU__)
  373. #define JSON_HEDLEY_TI_CLPRU_VERSION JSON_HEDLEY_VERSION_ENCODE(__TI_COMPILER_VERSION__ / 1000000, (__TI_COMPILER_VERSION__ % 1000000) / 1000, (__TI_COMPILER_VERSION__ % 1000))
  374. #endif
  375. #if defined(JSON_HEDLEY_TI_CLPRU_VERSION_CHECK)
  376. #undef JSON_HEDLEY_TI_CLPRU_VERSION_CHECK
  377. #endif
  378. #if defined(JSON_HEDLEY_TI_CLPRU_VERSION)
  379. #define JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_TI_CLPRU_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
  380. #else
  381. #define JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(major,minor,patch) (0)
  382. #endif
  383. #if defined(JSON_HEDLEY_CRAY_VERSION)
  384. #undef JSON_HEDLEY_CRAY_VERSION
  385. #endif
  386. #if defined(_CRAYC)
  387. #if defined(_RELEASE_PATCHLEVEL)
  388. #define JSON_HEDLEY_CRAY_VERSION JSON_HEDLEY_VERSION_ENCODE(_RELEASE_MAJOR, _RELEASE_MINOR, _RELEASE_PATCHLEVEL)
  389. #else
  390. #define JSON_HEDLEY_CRAY_VERSION JSON_HEDLEY_VERSION_ENCODE(_RELEASE_MAJOR, _RELEASE_MINOR, 0)
  391. #endif
  392. #endif
  393. #if defined(JSON_HEDLEY_CRAY_VERSION_CHECK)
  394. #undef JSON_HEDLEY_CRAY_VERSION_CHECK
  395. #endif
  396. #if defined(JSON_HEDLEY_CRAY_VERSION)
  397. #define JSON_HEDLEY_CRAY_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_CRAY_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
  398. #else
  399. #define JSON_HEDLEY_CRAY_VERSION_CHECK(major,minor,patch) (0)
  400. #endif
  401. #if defined(JSON_HEDLEY_IAR_VERSION)
  402. #undef JSON_HEDLEY_IAR_VERSION
  403. #endif
  404. #if defined(__IAR_SYSTEMS_ICC__)
  405. #if __VER__ > 1000
  406. #define JSON_HEDLEY_IAR_VERSION JSON_HEDLEY_VERSION_ENCODE((__VER__ / 1000000), ((__VER__ / 1000) % 1000), (__VER__ % 1000))
  407. #else
  408. #define JSON_HEDLEY_IAR_VERSION JSON_HEDLEY_VERSION_ENCODE(VER / 100, __VER__ % 100, 0)
  409. #endif
  410. #endif
  411. #if defined(JSON_HEDLEY_IAR_VERSION_CHECK)
  412. #undef JSON_HEDLEY_IAR_VERSION_CHECK
  413. #endif
  414. #if defined(JSON_HEDLEY_IAR_VERSION)
  415. #define JSON_HEDLEY_IAR_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_IAR_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
  416. #else
  417. #define JSON_HEDLEY_IAR_VERSION_CHECK(major,minor,patch) (0)
  418. #endif
  419. #if defined(JSON_HEDLEY_TINYC_VERSION)
  420. #undef JSON_HEDLEY_TINYC_VERSION
  421. #endif
  422. #if defined(__TINYC__)
  423. #define JSON_HEDLEY_TINYC_VERSION JSON_HEDLEY_VERSION_ENCODE(__TINYC__ / 1000, (__TINYC__ / 100) % 10, __TINYC__ % 100)
  424. #endif
  425. #if defined(JSON_HEDLEY_TINYC_VERSION_CHECK)
  426. #undef JSON_HEDLEY_TINYC_VERSION_CHECK
  427. #endif
  428. #if defined(JSON_HEDLEY_TINYC_VERSION)
  429. #define JSON_HEDLEY_TINYC_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_TINYC_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
  430. #else
  431. #define JSON_HEDLEY_TINYC_VERSION_CHECK(major,minor,patch) (0)
  432. #endif
  433. #if defined(JSON_HEDLEY_DMC_VERSION)
  434. #undef JSON_HEDLEY_DMC_VERSION
  435. #endif
  436. #if defined(__DMC__)
  437. #define JSON_HEDLEY_DMC_VERSION JSON_HEDLEY_VERSION_ENCODE(__DMC__ >> 8, (__DMC__ >> 4) & 0xf, __DMC__ & 0xf)
  438. #endif
  439. #if defined(JSON_HEDLEY_DMC_VERSION_CHECK)
  440. #undef JSON_HEDLEY_DMC_VERSION_CHECK
  441. #endif
  442. #if defined(JSON_HEDLEY_DMC_VERSION)
  443. #define JSON_HEDLEY_DMC_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_DMC_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
  444. #else
  445. #define JSON_HEDLEY_DMC_VERSION_CHECK(major,minor,patch) (0)
  446. #endif
  447. #if defined(JSON_HEDLEY_COMPCERT_VERSION)
  448. #undef JSON_HEDLEY_COMPCERT_VERSION
  449. #endif
  450. #if defined(__COMPCERT_VERSION__)
  451. #define JSON_HEDLEY_COMPCERT_VERSION JSON_HEDLEY_VERSION_ENCODE(__COMPCERT_VERSION__ / 10000, (__COMPCERT_VERSION__ / 100) % 100, __COMPCERT_VERSION__ % 100)
  452. #endif
  453. #if defined(JSON_HEDLEY_COMPCERT_VERSION_CHECK)
  454. #undef JSON_HEDLEY_COMPCERT_VERSION_CHECK
  455. #endif
  456. #if defined(JSON_HEDLEY_COMPCERT_VERSION)
  457. #define JSON_HEDLEY_COMPCERT_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_COMPCERT_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
  458. #else
  459. #define JSON_HEDLEY_COMPCERT_VERSION_CHECK(major,minor,patch) (0)
  460. #endif
  461. #if defined(JSON_HEDLEY_PELLES_VERSION)
  462. #undef JSON_HEDLEY_PELLES_VERSION
  463. #endif
  464. #if defined(__POCC__)
  465. #define JSON_HEDLEY_PELLES_VERSION JSON_HEDLEY_VERSION_ENCODE(__POCC__ / 100, __POCC__ % 100, 0)
  466. #endif
  467. #if defined(JSON_HEDLEY_PELLES_VERSION_CHECK)
  468. #undef JSON_HEDLEY_PELLES_VERSION_CHECK
  469. #endif
  470. #if defined(JSON_HEDLEY_PELLES_VERSION)
  471. #define JSON_HEDLEY_PELLES_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_PELLES_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
  472. #else
  473. #define JSON_HEDLEY_PELLES_VERSION_CHECK(major,minor,patch) (0)
  474. #endif
  475. #if defined(JSON_HEDLEY_GCC_VERSION)
  476. #undef JSON_HEDLEY_GCC_VERSION
  477. #endif
  478. #if \
  479. defined(JSON_HEDLEY_GNUC_VERSION) && \
  480. !defined(__clang__) && \
  481. !defined(JSON_HEDLEY_INTEL_VERSION) && \
  482. !defined(JSON_HEDLEY_PGI_VERSION) && \
  483. !defined(JSON_HEDLEY_ARM_VERSION) && \
  484. !defined(JSON_HEDLEY_TI_VERSION) && \
  485. !defined(JSON_HEDLEY_TI_ARMCL_VERSION) && \
  486. !defined(JSON_HEDLEY_TI_CL430_VERSION) && \
  487. !defined(JSON_HEDLEY_TI_CL2000_VERSION) && \
  488. !defined(JSON_HEDLEY_TI_CL6X_VERSION) && \
  489. !defined(JSON_HEDLEY_TI_CL7X_VERSION) && \
  490. !defined(JSON_HEDLEY_TI_CLPRU_VERSION) && \
  491. !defined(__COMPCERT__)
  492. #define JSON_HEDLEY_GCC_VERSION JSON_HEDLEY_GNUC_VERSION
  493. #endif
  494. #if defined(JSON_HEDLEY_GCC_VERSION_CHECK)
  495. #undef JSON_HEDLEY_GCC_VERSION_CHECK
  496. #endif
  497. #if defined(JSON_HEDLEY_GCC_VERSION)
  498. #define JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_GCC_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
  499. #else
  500. #define JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch) (0)
  501. #endif
  502. #if defined(JSON_HEDLEY_HAS_ATTRIBUTE)
  503. #undef JSON_HEDLEY_HAS_ATTRIBUTE
  504. #endif
  505. #if defined(__has_attribute)
  506. #define JSON_HEDLEY_HAS_ATTRIBUTE(attribute) __has_attribute(attribute)
  507. #else
  508. #define JSON_HEDLEY_HAS_ATTRIBUTE(attribute) (0)
  509. #endif
  510. #if defined(JSON_HEDLEY_GNUC_HAS_ATTRIBUTE)
  511. #undef JSON_HEDLEY_GNUC_HAS_ATTRIBUTE
  512. #endif
  513. #if defined(__has_attribute)
  514. #define JSON_HEDLEY_GNUC_HAS_ATTRIBUTE(attribute,major,minor,patch) __has_attribute(attribute)
  515. #else
  516. #define JSON_HEDLEY_GNUC_HAS_ATTRIBUTE(attribute,major,minor,patch) JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch)
  517. #endif
  518. #if defined(JSON_HEDLEY_GCC_HAS_ATTRIBUTE)
  519. #undef JSON_HEDLEY_GCC_HAS_ATTRIBUTE
  520. #endif
  521. #if defined(__has_attribute)
  522. #define JSON_HEDLEY_GCC_HAS_ATTRIBUTE(attribute,major,minor,patch) __has_attribute(attribute)
  523. #else
  524. #define JSON_HEDLEY_GCC_HAS_ATTRIBUTE(attribute,major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch)
  525. #endif
  526. #if defined(JSON_HEDLEY_HAS_CPP_ATTRIBUTE)
  527. #undef JSON_HEDLEY_HAS_CPP_ATTRIBUTE
  528. #endif
  529. #if \
  530. defined(__has_cpp_attribute) && \
  531. defined(__cplusplus) && \
  532. (!defined(JSON_HEDLEY_SUNPRO_VERSION) || JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,15,0))
  533. #define JSON_HEDLEY_HAS_CPP_ATTRIBUTE(attribute) __has_cpp_attribute(attribute)
  534. #else
  535. #define JSON_HEDLEY_HAS_CPP_ATTRIBUTE(attribute) (0)
  536. #endif
  537. #if defined(JSON_HEDLEY_HAS_CPP_ATTRIBUTE_NS)
  538. #undef JSON_HEDLEY_HAS_CPP_ATTRIBUTE_NS
  539. #endif
  540. #if !defined(__cplusplus) || !defined(__has_cpp_attribute)
  541. #define JSON_HEDLEY_HAS_CPP_ATTRIBUTE_NS(ns,attribute) (0)
  542. #elif \
  543. !defined(JSON_HEDLEY_PGI_VERSION) && \
  544. !defined(JSON_HEDLEY_IAR_VERSION) && \
  545. (!defined(JSON_HEDLEY_SUNPRO_VERSION) || JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,15,0)) && \
  546. (!defined(JSON_HEDLEY_MSVC_VERSION) || JSON_HEDLEY_MSVC_VERSION_CHECK(19,20,0))
  547. #define JSON_HEDLEY_HAS_CPP_ATTRIBUTE_NS(ns,attribute) JSON_HEDLEY_HAS_CPP_ATTRIBUTE(ns::attribute)
  548. #else
  549. #define JSON_HEDLEY_HAS_CPP_ATTRIBUTE_NS(ns,attribute) (0)
  550. #endif
  551. #if defined(JSON_HEDLEY_GNUC_HAS_CPP_ATTRIBUTE)
  552. #undef JSON_HEDLEY_GNUC_HAS_CPP_ATTRIBUTE
  553. #endif
  554. #if defined(__has_cpp_attribute) && defined(__cplusplus)
  555. #define JSON_HEDLEY_GNUC_HAS_CPP_ATTRIBUTE(attribute,major,minor,patch) __has_cpp_attribute(attribute)
  556. #else
  557. #define JSON_HEDLEY_GNUC_HAS_CPP_ATTRIBUTE(attribute,major,minor,patch) JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch)
  558. #endif
  559. #if defined(JSON_HEDLEY_GCC_HAS_CPP_ATTRIBUTE)
  560. #undef JSON_HEDLEY_GCC_HAS_CPP_ATTRIBUTE
  561. #endif
  562. #if defined(__has_cpp_attribute) && defined(__cplusplus)
  563. #define JSON_HEDLEY_GCC_HAS_CPP_ATTRIBUTE(attribute,major,minor,patch) __has_cpp_attribute(attribute)
  564. #else
  565. #define JSON_HEDLEY_GCC_HAS_CPP_ATTRIBUTE(attribute,major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch)
  566. #endif
  567. #if defined(JSON_HEDLEY_HAS_BUILTIN)
  568. #undef JSON_HEDLEY_HAS_BUILTIN
  569. #endif
  570. #if defined(__has_builtin)
  571. #define JSON_HEDLEY_HAS_BUILTIN(builtin) __has_builtin(builtin)
  572. #else
  573. #define JSON_HEDLEY_HAS_BUILTIN(builtin) (0)
  574. #endif
  575. #if defined(JSON_HEDLEY_GNUC_HAS_BUILTIN)
  576. #undef JSON_HEDLEY_GNUC_HAS_BUILTIN
  577. #endif
  578. #if defined(__has_builtin)
  579. #define JSON_HEDLEY_GNUC_HAS_BUILTIN(builtin,major,minor,patch) __has_builtin(builtin)
  580. #else
  581. #define JSON_HEDLEY_GNUC_HAS_BUILTIN(builtin,major,minor,patch) JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch)
  582. #endif
  583. #if defined(JSON_HEDLEY_GCC_HAS_BUILTIN)
  584. #undef JSON_HEDLEY_GCC_HAS_BUILTIN
  585. #endif
  586. #if defined(__has_builtin)
  587. #define JSON_HEDLEY_GCC_HAS_BUILTIN(builtin,major,minor,patch) __has_builtin(builtin)
  588. #else
  589. #define JSON_HEDLEY_GCC_HAS_BUILTIN(builtin,major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch)
  590. #endif
  591. #if defined(JSON_HEDLEY_HAS_FEATURE)
  592. #undef JSON_HEDLEY_HAS_FEATURE
  593. #endif
  594. #if defined(__has_feature)
  595. #define JSON_HEDLEY_HAS_FEATURE(feature) __has_feature(feature)
  596. #else
  597. #define JSON_HEDLEY_HAS_FEATURE(feature) (0)
  598. #endif
  599. #if defined(JSON_HEDLEY_GNUC_HAS_FEATURE)
  600. #undef JSON_HEDLEY_GNUC_HAS_FEATURE
  601. #endif
  602. #if defined(__has_feature)
  603. #define JSON_HEDLEY_GNUC_HAS_FEATURE(feature,major,minor,patch) __has_feature(feature)
  604. #else
  605. #define JSON_HEDLEY_GNUC_HAS_FEATURE(feature,major,minor,patch) JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch)
  606. #endif
  607. #if defined(JSON_HEDLEY_GCC_HAS_FEATURE)
  608. #undef JSON_HEDLEY_GCC_HAS_FEATURE
  609. #endif
  610. #if defined(__has_feature)
  611. #define JSON_HEDLEY_GCC_HAS_FEATURE(feature,major,minor,patch) __has_feature(feature)
  612. #else
  613. #define JSON_HEDLEY_GCC_HAS_FEATURE(feature,major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch)
  614. #endif
  615. #if defined(JSON_HEDLEY_HAS_EXTENSION)
  616. #undef JSON_HEDLEY_HAS_EXTENSION
  617. #endif
  618. #if defined(__has_extension)
  619. #define JSON_HEDLEY_HAS_EXTENSION(extension) __has_extension(extension)
  620. #else
  621. #define JSON_HEDLEY_HAS_EXTENSION(extension) (0)
  622. #endif
  623. #if defined(JSON_HEDLEY_GNUC_HAS_EXTENSION)
  624. #undef JSON_HEDLEY_GNUC_HAS_EXTENSION
  625. #endif
  626. #if defined(__has_extension)
  627. #define JSON_HEDLEY_GNUC_HAS_EXTENSION(extension,major,minor,patch) __has_extension(extension)
  628. #else
  629. #define JSON_HEDLEY_GNUC_HAS_EXTENSION(extension,major,minor,patch) JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch)
  630. #endif
  631. #if defined(JSON_HEDLEY_GCC_HAS_EXTENSION)
  632. #undef JSON_HEDLEY_GCC_HAS_EXTENSION
  633. #endif
  634. #if defined(__has_extension)
  635. #define JSON_HEDLEY_GCC_HAS_EXTENSION(extension,major,minor,patch) __has_extension(extension)
  636. #else
  637. #define JSON_HEDLEY_GCC_HAS_EXTENSION(extension,major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch)
  638. #endif
  639. #if defined(JSON_HEDLEY_HAS_DECLSPEC_ATTRIBUTE)
  640. #undef JSON_HEDLEY_HAS_DECLSPEC_ATTRIBUTE
  641. #endif
  642. #if defined(__has_declspec_attribute)
  643. #define JSON_HEDLEY_HAS_DECLSPEC_ATTRIBUTE(attribute) __has_declspec_attribute(attribute)
  644. #else
  645. #define JSON_HEDLEY_HAS_DECLSPEC_ATTRIBUTE(attribute) (0)
  646. #endif
  647. #if defined(JSON_HEDLEY_GNUC_HAS_DECLSPEC_ATTRIBUTE)
  648. #undef JSON_HEDLEY_GNUC_HAS_DECLSPEC_ATTRIBUTE
  649. #endif
  650. #if defined(__has_declspec_attribute)
  651. #define JSON_HEDLEY_GNUC_HAS_DECLSPEC_ATTRIBUTE(attribute,major,minor,patch) __has_declspec_attribute(attribute)
  652. #else
  653. #define JSON_HEDLEY_GNUC_HAS_DECLSPEC_ATTRIBUTE(attribute,major,minor,patch) JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch)
  654. #endif
  655. #if defined(JSON_HEDLEY_GCC_HAS_DECLSPEC_ATTRIBUTE)
  656. #undef JSON_HEDLEY_GCC_HAS_DECLSPEC_ATTRIBUTE
  657. #endif
  658. #if defined(__has_declspec_attribute)
  659. #define JSON_HEDLEY_GCC_HAS_DECLSPEC_ATTRIBUTE(attribute,major,minor,patch) __has_declspec_attribute(attribute)
  660. #else
  661. #define JSON_HEDLEY_GCC_HAS_DECLSPEC_ATTRIBUTE(attribute,major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch)
  662. #endif
  663. #if defined(JSON_HEDLEY_HAS_WARNING)
  664. #undef JSON_HEDLEY_HAS_WARNING
  665. #endif
  666. #if defined(__has_warning)
  667. #define JSON_HEDLEY_HAS_WARNING(warning) __has_warning(warning)
  668. #else
  669. #define JSON_HEDLEY_HAS_WARNING(warning) (0)
  670. #endif
  671. #if defined(JSON_HEDLEY_GNUC_HAS_WARNING)
  672. #undef JSON_HEDLEY_GNUC_HAS_WARNING
  673. #endif
  674. #if defined(__has_warning)
  675. #define JSON_HEDLEY_GNUC_HAS_WARNING(warning,major,minor,patch) __has_warning(warning)
  676. #else
  677. #define JSON_HEDLEY_GNUC_HAS_WARNING(warning,major,minor,patch) JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch)
  678. #endif
  679. #if defined(JSON_HEDLEY_GCC_HAS_WARNING)
  680. #undef JSON_HEDLEY_GCC_HAS_WARNING
  681. #endif
  682. #if defined(__has_warning)
  683. #define JSON_HEDLEY_GCC_HAS_WARNING(warning,major,minor,patch) __has_warning(warning)
  684. #else
  685. #define JSON_HEDLEY_GCC_HAS_WARNING(warning,major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch)
  686. #endif
  687. /* JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_ is for
  688. HEDLEY INTERNAL USE ONLY. API subject to change without notice. */
  689. #if defined(JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_)
  690. #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_
  691. #endif
  692. #if defined(__cplusplus)
  693. # if JSON_HEDLEY_HAS_WARNING("-Wc++98-compat")
  694. # if JSON_HEDLEY_HAS_WARNING("-Wc++17-extensions")
  695. # define JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_(xpr) \
  696. JSON_HEDLEY_DIAGNOSTIC_PUSH \
  697. _Pragma("clang diagnostic ignored \"-Wc++98-compat\"") \
  698. _Pragma("clang diagnostic ignored \"-Wc++17-extensions\"") \
  699. xpr \
  700. JSON_HEDLEY_DIAGNOSTIC_POP
  701. # else
  702. # define JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_(xpr) \
  703. JSON_HEDLEY_DIAGNOSTIC_PUSH \
  704. _Pragma("clang diagnostic ignored \"-Wc++98-compat\"") \
  705. xpr \
  706. JSON_HEDLEY_DIAGNOSTIC_POP
  707. # endif
  708. # endif
  709. #endif
  710. #if !defined(JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_)
  711. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_(x) x
  712. #endif
  713. #if defined(JSON_HEDLEY_CONST_CAST)
  714. #undef JSON_HEDLEY_CONST_CAST
  715. #endif
  716. #if defined(__cplusplus)
  717. # define JSON_HEDLEY_CONST_CAST(T, expr) (const_cast<T>(expr))
  718. #elif \
  719. JSON_HEDLEY_HAS_WARNING("-Wcast-qual") || \
  720. JSON_HEDLEY_GCC_VERSION_CHECK(4,6,0) || \
  721. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0)
  722. # define JSON_HEDLEY_CONST_CAST(T, expr) (__extension__ ({ \
  723. JSON_HEDLEY_DIAGNOSTIC_PUSH \
  724. JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL \
  725. ((T) (expr)); \
  726. JSON_HEDLEY_DIAGNOSTIC_POP \
  727. }))
  728. #else
  729. # define JSON_HEDLEY_CONST_CAST(T, expr) ((T) (expr))
  730. #endif
  731. #if defined(JSON_HEDLEY_REINTERPRET_CAST)
  732. #undef JSON_HEDLEY_REINTERPRET_CAST
  733. #endif
  734. #if defined(__cplusplus)
  735. #define JSON_HEDLEY_REINTERPRET_CAST(T, expr) (reinterpret_cast<T>(expr))
  736. #else
  737. #define JSON_HEDLEY_REINTERPRET_CAST(T, expr) ((T) (expr))
  738. #endif
  739. #if defined(JSON_HEDLEY_STATIC_CAST)
  740. #undef JSON_HEDLEY_STATIC_CAST
  741. #endif
  742. #if defined(__cplusplus)
  743. #define JSON_HEDLEY_STATIC_CAST(T, expr) (static_cast<T>(expr))
  744. #else
  745. #define JSON_HEDLEY_STATIC_CAST(T, expr) ((T) (expr))
  746. #endif
  747. #if defined(JSON_HEDLEY_CPP_CAST)
  748. #undef JSON_HEDLEY_CPP_CAST
  749. #endif
  750. #if defined(__cplusplus)
  751. # if JSON_HEDLEY_HAS_WARNING("-Wold-style-cast")
  752. # define JSON_HEDLEY_CPP_CAST(T, expr) \
  753. JSON_HEDLEY_DIAGNOSTIC_PUSH \
  754. _Pragma("clang diagnostic ignored \"-Wold-style-cast\"") \
  755. ((T) (expr)) \
  756. JSON_HEDLEY_DIAGNOSTIC_POP
  757. # elif JSON_HEDLEY_IAR_VERSION_CHECK(8,3,0)
  758. # define JSON_HEDLEY_CPP_CAST(T, expr) \
  759. JSON_HEDLEY_DIAGNOSTIC_PUSH \
  760. _Pragma("diag_suppress=Pe137") \
  761. JSON_HEDLEY_DIAGNOSTIC_POP \
  762. # else
  763. # define JSON_HEDLEY_CPP_CAST(T, expr) ((T) (expr))
  764. # endif
  765. #else
  766. # define JSON_HEDLEY_CPP_CAST(T, expr) (expr)
  767. #endif
  768. #if \
  769. (defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L)) || \
  770. defined(__clang__) || \
  771. JSON_HEDLEY_GCC_VERSION_CHECK(3,0,0) || \
  772. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
  773. JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0) || \
  774. JSON_HEDLEY_PGI_VERSION_CHECK(18,4,0) || \
  775. JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \
  776. JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \
  777. JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,7,0) || \
  778. JSON_HEDLEY_TI_CL430_VERSION_CHECK(2,0,1) || \
  779. JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,1,0) || \
  780. JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,0,0) || \
  781. JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \
  782. JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \
  783. JSON_HEDLEY_CRAY_VERSION_CHECK(5,0,0) || \
  784. JSON_HEDLEY_TINYC_VERSION_CHECK(0,9,17) || \
  785. JSON_HEDLEY_SUNPRO_VERSION_CHECK(8,0,0) || \
  786. (JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) && defined(__C99_PRAGMA_OPERATOR))
  787. #define JSON_HEDLEY_PRAGMA(value) _Pragma(#value)
  788. #elif JSON_HEDLEY_MSVC_VERSION_CHECK(15,0,0)
  789. #define JSON_HEDLEY_PRAGMA(value) __pragma(value)
  790. #else
  791. #define JSON_HEDLEY_PRAGMA(value)
  792. #endif
  793. #if defined(JSON_HEDLEY_DIAGNOSTIC_PUSH)
  794. #undef JSON_HEDLEY_DIAGNOSTIC_PUSH
  795. #endif
  796. #if defined(JSON_HEDLEY_DIAGNOSTIC_POP)
  797. #undef JSON_HEDLEY_DIAGNOSTIC_POP
  798. #endif
  799. #if defined(__clang__)
  800. #define JSON_HEDLEY_DIAGNOSTIC_PUSH _Pragma("clang diagnostic push")
  801. #define JSON_HEDLEY_DIAGNOSTIC_POP _Pragma("clang diagnostic pop")
  802. #elif JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0)
  803. #define JSON_HEDLEY_DIAGNOSTIC_PUSH _Pragma("warning(push)")
  804. #define JSON_HEDLEY_DIAGNOSTIC_POP _Pragma("warning(pop)")
  805. #elif JSON_HEDLEY_GCC_VERSION_CHECK(4,6,0)
  806. #define JSON_HEDLEY_DIAGNOSTIC_PUSH _Pragma("GCC diagnostic push")
  807. #define JSON_HEDLEY_DIAGNOSTIC_POP _Pragma("GCC diagnostic pop")
  808. #elif JSON_HEDLEY_MSVC_VERSION_CHECK(15,0,0)
  809. #define JSON_HEDLEY_DIAGNOSTIC_PUSH __pragma(warning(push))
  810. #define JSON_HEDLEY_DIAGNOSTIC_POP __pragma(warning(pop))
  811. #elif JSON_HEDLEY_ARM_VERSION_CHECK(5,6,0)
  812. #define JSON_HEDLEY_DIAGNOSTIC_PUSH _Pragma("push")
  813. #define JSON_HEDLEY_DIAGNOSTIC_POP _Pragma("pop")
  814. #elif \
  815. JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \
  816. JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \
  817. JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,4,0) || \
  818. JSON_HEDLEY_TI_CL6X_VERSION_CHECK(8,1,0) || \
  819. JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \
  820. JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0)
  821. #define JSON_HEDLEY_DIAGNOSTIC_PUSH _Pragma("diag_push")
  822. #define JSON_HEDLEY_DIAGNOSTIC_POP _Pragma("diag_pop")
  823. #elif JSON_HEDLEY_PELLES_VERSION_CHECK(2,90,0)
  824. #define JSON_HEDLEY_DIAGNOSTIC_PUSH _Pragma("warning(push)")
  825. #define JSON_HEDLEY_DIAGNOSTIC_POP _Pragma("warning(pop)")
  826. #else
  827. #define JSON_HEDLEY_DIAGNOSTIC_PUSH
  828. #define JSON_HEDLEY_DIAGNOSTIC_POP
  829. #endif
  830. #if defined(JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED)
  831. #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED
  832. #endif
  833. #if JSON_HEDLEY_HAS_WARNING("-Wdeprecated-declarations")
  834. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("clang diagnostic ignored \"-Wdeprecated-declarations\"")
  835. #elif JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0)
  836. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("warning(disable:1478 1786)")
  837. #elif JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0)
  838. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("diag_suppress 1215,1444")
  839. #elif JSON_HEDLEY_GCC_VERSION_CHECK(4,3,0)
  840. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("GCC diagnostic ignored \"-Wdeprecated-declarations\"")
  841. #elif JSON_HEDLEY_MSVC_VERSION_CHECK(15,0,0)
  842. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED __pragma(warning(disable:4996))
  843. #elif \
  844. JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \
  845. (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  846. JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \
  847. (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  848. JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \
  849. (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  850. JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \
  851. (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  852. JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \
  853. JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \
  854. JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0)
  855. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("diag_suppress 1291,1718")
  856. #elif JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,13,0) && !defined(__cplusplus)
  857. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("error_messages(off,E_DEPRECATED_ATT,E_DEPRECATED_ATT_MESS)")
  858. #elif JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,13,0) && defined(__cplusplus)
  859. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("error_messages(off,symdeprecated,symdeprecated2)")
  860. #elif JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0)
  861. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("diag_suppress=Pe1444,Pe1215")
  862. #elif JSON_HEDLEY_PELLES_VERSION_CHECK(2,90,0)
  863. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("warn(disable:2241)")
  864. #else
  865. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED
  866. #endif
  867. #if defined(JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS)
  868. #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS
  869. #endif
  870. #if JSON_HEDLEY_HAS_WARNING("-Wunknown-pragmas")
  871. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("clang diagnostic ignored \"-Wunknown-pragmas\"")
  872. #elif JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0)
  873. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("warning(disable:161)")
  874. #elif JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0)
  875. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("diag_suppress 1675")
  876. #elif JSON_HEDLEY_GCC_VERSION_CHECK(4,3,0)
  877. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("GCC diagnostic ignored \"-Wunknown-pragmas\"")
  878. #elif JSON_HEDLEY_MSVC_VERSION_CHECK(15,0,0)
  879. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS __pragma(warning(disable:4068))
  880. #elif \
  881. JSON_HEDLEY_TI_VERSION_CHECK(16,9,0) || \
  882. JSON_HEDLEY_TI_CL6X_VERSION_CHECK(8,0,0) || \
  883. JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \
  884. JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,3,0)
  885. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("diag_suppress 163")
  886. #elif JSON_HEDLEY_TI_CL6X_VERSION_CHECK(8,0,0)
  887. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("diag_suppress 163")
  888. #elif JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0)
  889. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("diag_suppress=Pe161")
  890. #else
  891. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS
  892. #endif
  893. #if defined(JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES)
  894. #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES
  895. #endif
  896. #if JSON_HEDLEY_HAS_WARNING("-Wunknown-attributes")
  897. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("clang diagnostic ignored \"-Wunknown-attributes\"")
  898. #elif JSON_HEDLEY_GCC_VERSION_CHECK(4,6,0)
  899. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("GCC diagnostic ignored \"-Wdeprecated-declarations\"")
  900. #elif JSON_HEDLEY_INTEL_VERSION_CHECK(17,0,0)
  901. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("warning(disable:1292)")
  902. #elif JSON_HEDLEY_MSVC_VERSION_CHECK(19,0,0)
  903. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES __pragma(warning(disable:5030))
  904. #elif JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0)
  905. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("diag_suppress 1097")
  906. #elif JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,14,0) && defined(__cplusplus)
  907. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("error_messages(off,attrskipunsup)")
  908. #elif \
  909. JSON_HEDLEY_TI_VERSION_CHECK(18,1,0) || \
  910. JSON_HEDLEY_TI_CL6X_VERSION_CHECK(8,3,0) || \
  911. JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0)
  912. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("diag_suppress 1173")
  913. #elif JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0)
  914. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("diag_suppress=Pe1097")
  915. #else
  916. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES
  917. #endif
  918. #if defined(JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL)
  919. #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL
  920. #endif
  921. #if JSON_HEDLEY_HAS_WARNING("-Wcast-qual")
  922. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL _Pragma("clang diagnostic ignored \"-Wcast-qual\"")
  923. #elif JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0)
  924. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL _Pragma("warning(disable:2203 2331)")
  925. #elif JSON_HEDLEY_GCC_VERSION_CHECK(3,0,0)
  926. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL _Pragma("GCC diagnostic ignored \"-Wcast-qual\"")
  927. #else
  928. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL
  929. #endif
  930. #if defined(JSON_HEDLEY_DEPRECATED)
  931. #undef JSON_HEDLEY_DEPRECATED
  932. #endif
  933. #if defined(JSON_HEDLEY_DEPRECATED_FOR)
  934. #undef JSON_HEDLEY_DEPRECATED_FOR
  935. #endif
  936. #if JSON_HEDLEY_MSVC_VERSION_CHECK(14,0,0)
  937. #define JSON_HEDLEY_DEPRECATED(since) __declspec(deprecated("Since " # since))
  938. #define JSON_HEDLEY_DEPRECATED_FOR(since, replacement) __declspec(deprecated("Since " #since "; use " #replacement))
  939. #elif defined(__cplusplus) && (__cplusplus >= 201402L)
  940. #define JSON_HEDLEY_DEPRECATED(since) JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[deprecated("Since " #since)]])
  941. #define JSON_HEDLEY_DEPRECATED_FOR(since, replacement) JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[deprecated("Since " #since "; use " #replacement)]])
  942. #elif \
  943. JSON_HEDLEY_HAS_EXTENSION(attribute_deprecated_with_message) || \
  944. JSON_HEDLEY_GCC_VERSION_CHECK(4,5,0) || \
  945. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
  946. JSON_HEDLEY_ARM_VERSION_CHECK(5,6,0) || \
  947. JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,13,0) || \
  948. JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0) || \
  949. JSON_HEDLEY_TI_VERSION_CHECK(18,1,0) || \
  950. JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(18,1,0) || \
  951. JSON_HEDLEY_TI_CL6X_VERSION_CHECK(8,3,0) || \
  952. JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \
  953. JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,3,0)
  954. #define JSON_HEDLEY_DEPRECATED(since) __attribute__((__deprecated__("Since " #since)))
  955. #define JSON_HEDLEY_DEPRECATED_FOR(since, replacement) __attribute__((__deprecated__("Since " #since "; use " #replacement)))
  956. #elif \
  957. JSON_HEDLEY_HAS_ATTRIBUTE(deprecated) || \
  958. JSON_HEDLEY_GCC_VERSION_CHECK(3,1,0) || \
  959. JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \
  960. JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \
  961. (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  962. JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \
  963. (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  964. JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \
  965. (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  966. JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \
  967. (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  968. JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \
  969. JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \
  970. JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0)
  971. #define JSON_HEDLEY_DEPRECATED(since) __attribute__((__deprecated__))
  972. #define JSON_HEDLEY_DEPRECATED_FOR(since, replacement) __attribute__((__deprecated__))
  973. #elif \
  974. JSON_HEDLEY_MSVC_VERSION_CHECK(13,10,0) || \
  975. JSON_HEDLEY_PELLES_VERSION_CHECK(6,50,0)
  976. #define JSON_HEDLEY_DEPRECATED(since) __declspec(deprecated)
  977. #define JSON_HEDLEY_DEPRECATED_FOR(since, replacement) __declspec(deprecated)
  978. #elif JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0)
  979. #define JSON_HEDLEY_DEPRECATED(since) _Pragma("deprecated")
  980. #define JSON_HEDLEY_DEPRECATED_FOR(since, replacement) _Pragma("deprecated")
  981. #else
  982. #define JSON_HEDLEY_DEPRECATED(since)
  983. #define JSON_HEDLEY_DEPRECATED_FOR(since, replacement)
  984. #endif
  985. #if defined(JSON_HEDLEY_UNAVAILABLE)
  986. #undef JSON_HEDLEY_UNAVAILABLE
  987. #endif
  988. #if \
  989. JSON_HEDLEY_HAS_ATTRIBUTE(warning) || \
  990. JSON_HEDLEY_GCC_VERSION_CHECK(4,3,0) || \
  991. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0)
  992. #define JSON_HEDLEY_UNAVAILABLE(available_since) __attribute__((__warning__("Not available until " #available_since)))
  993. #else
  994. #define JSON_HEDLEY_UNAVAILABLE(available_since)
  995. #endif
  996. #if defined(JSON_HEDLEY_WARN_UNUSED_RESULT)
  997. #undef JSON_HEDLEY_WARN_UNUSED_RESULT
  998. #endif
  999. #if defined(JSON_HEDLEY_WARN_UNUSED_RESULT_MSG)
  1000. #undef JSON_HEDLEY_WARN_UNUSED_RESULT_MSG
  1001. #endif
  1002. #if (JSON_HEDLEY_HAS_CPP_ATTRIBUTE(nodiscard) >= 201907L)
  1003. #define JSON_HEDLEY_WARN_UNUSED_RESULT JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[nodiscard]])
  1004. #define JSON_HEDLEY_WARN_UNUSED_RESULT_MSG(msg) JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[nodiscard(msg)]])
  1005. #elif JSON_HEDLEY_HAS_CPP_ATTRIBUTE(nodiscard)
  1006. #define JSON_HEDLEY_WARN_UNUSED_RESULT JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[nodiscard]])
  1007. #define JSON_HEDLEY_WARN_UNUSED_RESULT_MSG(msg) JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[nodiscard]])
  1008. #elif \
  1009. JSON_HEDLEY_HAS_ATTRIBUTE(warn_unused_result) || \
  1010. JSON_HEDLEY_GCC_VERSION_CHECK(3,4,0) || \
  1011. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
  1012. JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \
  1013. (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  1014. JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \
  1015. (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  1016. JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \
  1017. (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  1018. JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \
  1019. (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  1020. JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \
  1021. JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \
  1022. JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \
  1023. (JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,15,0) && defined(__cplusplus)) || \
  1024. JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0)
  1025. #define JSON_HEDLEY_WARN_UNUSED_RESULT __attribute__((__warn_unused_result__))
  1026. #define JSON_HEDLEY_WARN_UNUSED_RESULT_MSG(msg) __attribute__((__warn_unused_result__))
  1027. #elif defined(_Check_return_) /* SAL */
  1028. #define JSON_HEDLEY_WARN_UNUSED_RESULT _Check_return_
  1029. #define JSON_HEDLEY_WARN_UNUSED_RESULT_MSG(msg) _Check_return_
  1030. #else
  1031. #define JSON_HEDLEY_WARN_UNUSED_RESULT
  1032. #define JSON_HEDLEY_WARN_UNUSED_RESULT_MSG(msg)
  1033. #endif
  1034. #if defined(JSON_HEDLEY_SENTINEL)
  1035. #undef JSON_HEDLEY_SENTINEL
  1036. #endif
  1037. #if \
  1038. JSON_HEDLEY_HAS_ATTRIBUTE(sentinel) || \
  1039. JSON_HEDLEY_GCC_VERSION_CHECK(4,0,0) || \
  1040. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
  1041. JSON_HEDLEY_ARM_VERSION_CHECK(5,4,0)
  1042. #define JSON_HEDLEY_SENTINEL(position) __attribute__((__sentinel__(position)))
  1043. #else
  1044. #define JSON_HEDLEY_SENTINEL(position)
  1045. #endif
  1046. #if defined(JSON_HEDLEY_NO_RETURN)
  1047. #undef JSON_HEDLEY_NO_RETURN
  1048. #endif
  1049. #if JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0)
  1050. #define JSON_HEDLEY_NO_RETURN __noreturn
  1051. #elif JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0)
  1052. #define JSON_HEDLEY_NO_RETURN __attribute__((__noreturn__))
  1053. #elif defined(__STDC_VERSION__) && __STDC_VERSION__ >= 201112L
  1054. #define JSON_HEDLEY_NO_RETURN _Noreturn
  1055. #elif defined(__cplusplus) && (__cplusplus >= 201103L)
  1056. #define JSON_HEDLEY_NO_RETURN JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[noreturn]])
  1057. #elif \
  1058. JSON_HEDLEY_HAS_ATTRIBUTE(noreturn) || \
  1059. JSON_HEDLEY_GCC_VERSION_CHECK(3,2,0) || \
  1060. JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,11,0) || \
  1061. JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \
  1062. JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \
  1063. JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \
  1064. (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  1065. JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \
  1066. (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  1067. JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \
  1068. (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  1069. JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \
  1070. (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  1071. JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \
  1072. JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \
  1073. JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0)
  1074. #define JSON_HEDLEY_NO_RETURN __attribute__((__noreturn__))
  1075. #elif JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,10,0)
  1076. #define JSON_HEDLEY_NO_RETURN _Pragma("does_not_return")
  1077. #elif JSON_HEDLEY_MSVC_VERSION_CHECK(13,10,0)
  1078. #define JSON_HEDLEY_NO_RETURN __declspec(noreturn)
  1079. #elif JSON_HEDLEY_TI_CL6X_VERSION_CHECK(6,0,0) && defined(__cplusplus)
  1080. #define JSON_HEDLEY_NO_RETURN _Pragma("FUNC_NEVER_RETURNS;")
  1081. #elif JSON_HEDLEY_COMPCERT_VERSION_CHECK(3,2,0)
  1082. #define JSON_HEDLEY_NO_RETURN __attribute((noreturn))
  1083. #elif JSON_HEDLEY_PELLES_VERSION_CHECK(9,0,0)
  1084. #define JSON_HEDLEY_NO_RETURN __declspec(noreturn)
  1085. #else
  1086. #define JSON_HEDLEY_NO_RETURN
  1087. #endif
  1088. #if defined(JSON_HEDLEY_NO_ESCAPE)
  1089. #undef JSON_HEDLEY_NO_ESCAPE
  1090. #endif
  1091. #if JSON_HEDLEY_HAS_ATTRIBUTE(noescape)
  1092. #define JSON_HEDLEY_NO_ESCAPE __attribute__((__noescape__))
  1093. #else
  1094. #define JSON_HEDLEY_NO_ESCAPE
  1095. #endif
  1096. #if defined(JSON_HEDLEY_UNREACHABLE)
  1097. #undef JSON_HEDLEY_UNREACHABLE
  1098. #endif
  1099. #if defined(JSON_HEDLEY_UNREACHABLE_RETURN)
  1100. #undef JSON_HEDLEY_UNREACHABLE_RETURN
  1101. #endif
  1102. #if defined(JSON_HEDLEY_ASSUME)
  1103. #undef JSON_HEDLEY_ASSUME
  1104. #endif
  1105. #if \
  1106. JSON_HEDLEY_MSVC_VERSION_CHECK(13,10,0) || \
  1107. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0)
  1108. #define JSON_HEDLEY_ASSUME(expr) __assume(expr)
  1109. #elif JSON_HEDLEY_HAS_BUILTIN(__builtin_assume)
  1110. #define JSON_HEDLEY_ASSUME(expr) __builtin_assume(expr)
  1111. #elif \
  1112. JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,2,0) || \
  1113. JSON_HEDLEY_TI_CL6X_VERSION_CHECK(4,0,0)
  1114. #if defined(__cplusplus)
  1115. #define JSON_HEDLEY_ASSUME(expr) std::_nassert(expr)
  1116. #else
  1117. #define JSON_HEDLEY_ASSUME(expr) _nassert(expr)
  1118. #endif
  1119. #endif
  1120. #if \
  1121. (JSON_HEDLEY_HAS_BUILTIN(__builtin_unreachable) && (!defined(JSON_HEDLEY_ARM_VERSION))) || \
  1122. JSON_HEDLEY_GCC_VERSION_CHECK(4,5,0) || \
  1123. JSON_HEDLEY_PGI_VERSION_CHECK(18,10,0) || \
  1124. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
  1125. JSON_HEDLEY_IBM_VERSION_CHECK(13,1,5)
  1126. #define JSON_HEDLEY_UNREACHABLE() __builtin_unreachable()
  1127. #elif defined(JSON_HEDLEY_ASSUME)
  1128. #define JSON_HEDLEY_UNREACHABLE() JSON_HEDLEY_ASSUME(0)
  1129. #endif
  1130. #if !defined(JSON_HEDLEY_ASSUME)
  1131. #if defined(JSON_HEDLEY_UNREACHABLE)
  1132. #define JSON_HEDLEY_ASSUME(expr) JSON_HEDLEY_STATIC_CAST(void, ((expr) ? 1 : (JSON_HEDLEY_UNREACHABLE(), 1)))
  1133. #else
  1134. #define JSON_HEDLEY_ASSUME(expr) JSON_HEDLEY_STATIC_CAST(void, expr)
  1135. #endif
  1136. #endif
  1137. #if defined(JSON_HEDLEY_UNREACHABLE)
  1138. #if \
  1139. JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,2,0) || \
  1140. JSON_HEDLEY_TI_CL6X_VERSION_CHECK(4,0,0)
  1141. #define JSON_HEDLEY_UNREACHABLE_RETURN(value) return (JSON_HEDLEY_STATIC_CAST(void, JSON_HEDLEY_ASSUME(0)), (value))
  1142. #else
  1143. #define JSON_HEDLEY_UNREACHABLE_RETURN(value) JSON_HEDLEY_UNREACHABLE()
  1144. #endif
  1145. #else
  1146. #define JSON_HEDLEY_UNREACHABLE_RETURN(value) return (value)
  1147. #endif
  1148. #if !defined(JSON_HEDLEY_UNREACHABLE)
  1149. #define JSON_HEDLEY_UNREACHABLE() JSON_HEDLEY_ASSUME(0)
  1150. #endif
  1151. JSON_HEDLEY_DIAGNOSTIC_PUSH
  1152. #if JSON_HEDLEY_HAS_WARNING("-Wpedantic")
  1153. #pragma clang diagnostic ignored "-Wpedantic"
  1154. #endif
  1155. #if JSON_HEDLEY_HAS_WARNING("-Wc++98-compat-pedantic") && defined(__cplusplus)
  1156. #pragma clang diagnostic ignored "-Wc++98-compat-pedantic"
  1157. #endif
  1158. #if JSON_HEDLEY_GCC_HAS_WARNING("-Wvariadic-macros",4,0,0)
  1159. #if defined(__clang__)
  1160. #pragma clang diagnostic ignored "-Wvariadic-macros"
  1161. #elif defined(JSON_HEDLEY_GCC_VERSION)
  1162. #pragma GCC diagnostic ignored "-Wvariadic-macros"
  1163. #endif
  1164. #endif
  1165. #if defined(JSON_HEDLEY_NON_NULL)
  1166. #undef JSON_HEDLEY_NON_NULL
  1167. #endif
  1168. #if \
  1169. JSON_HEDLEY_HAS_ATTRIBUTE(nonnull) || \
  1170. JSON_HEDLEY_GCC_VERSION_CHECK(3,3,0) || \
  1171. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
  1172. JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0)
  1173. #define JSON_HEDLEY_NON_NULL(...) __attribute__((__nonnull__(__VA_ARGS__)))
  1174. #else
  1175. #define JSON_HEDLEY_NON_NULL(...)
  1176. #endif
  1177. JSON_HEDLEY_DIAGNOSTIC_POP
  1178. #if defined(JSON_HEDLEY_PRINTF_FORMAT)
  1179. #undef JSON_HEDLEY_PRINTF_FORMAT
  1180. #endif
  1181. #if defined(__MINGW32__) && JSON_HEDLEY_GCC_HAS_ATTRIBUTE(format,4,4,0) && !defined(__USE_MINGW_ANSI_STDIO)
  1182. #define JSON_HEDLEY_PRINTF_FORMAT(string_idx,first_to_check) __attribute__((__format__(ms_printf, string_idx, first_to_check)))
  1183. #elif defined(__MINGW32__) && JSON_HEDLEY_GCC_HAS_ATTRIBUTE(format,4,4,0) && defined(__USE_MINGW_ANSI_STDIO)
  1184. #define JSON_HEDLEY_PRINTF_FORMAT(string_idx,first_to_check) __attribute__((__format__(gnu_printf, string_idx, first_to_check)))
  1185. #elif \
  1186. JSON_HEDLEY_HAS_ATTRIBUTE(format) || \
  1187. JSON_HEDLEY_GCC_VERSION_CHECK(3,1,0) || \
  1188. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
  1189. JSON_HEDLEY_ARM_VERSION_CHECK(5,6,0) || \
  1190. JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \
  1191. JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \
  1192. (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  1193. JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \
  1194. (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  1195. JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \
  1196. (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  1197. JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \
  1198. (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  1199. JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \
  1200. JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \
  1201. JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0)
  1202. #define JSON_HEDLEY_PRINTF_FORMAT(string_idx,first_to_check) __attribute__((__format__(__printf__, string_idx, first_to_check)))
  1203. #elif JSON_HEDLEY_PELLES_VERSION_CHECK(6,0,0)
  1204. #define JSON_HEDLEY_PRINTF_FORMAT(string_idx,first_to_check) __declspec(vaformat(printf,string_idx,first_to_check))
  1205. #else
  1206. #define JSON_HEDLEY_PRINTF_FORMAT(string_idx,first_to_check)
  1207. #endif
  1208. #if defined(JSON_HEDLEY_CONSTEXPR)
  1209. #undef JSON_HEDLEY_CONSTEXPR
  1210. #endif
  1211. #if defined(__cplusplus)
  1212. #if __cplusplus >= 201103L
  1213. #define JSON_HEDLEY_CONSTEXPR JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_(constexpr)
  1214. #endif
  1215. #endif
  1216. #if !defined(JSON_HEDLEY_CONSTEXPR)
  1217. #define JSON_HEDLEY_CONSTEXPR
  1218. #endif
  1219. #if defined(JSON_HEDLEY_PREDICT)
  1220. #undef JSON_HEDLEY_PREDICT
  1221. #endif
  1222. #if defined(JSON_HEDLEY_LIKELY)
  1223. #undef JSON_HEDLEY_LIKELY
  1224. #endif
  1225. #if defined(JSON_HEDLEY_UNLIKELY)
  1226. #undef JSON_HEDLEY_UNLIKELY
  1227. #endif
  1228. #if defined(JSON_HEDLEY_UNPREDICTABLE)
  1229. #undef JSON_HEDLEY_UNPREDICTABLE
  1230. #endif
  1231. #if JSON_HEDLEY_HAS_BUILTIN(__builtin_unpredictable)
  1232. #define JSON_HEDLEY_UNPREDICTABLE(expr) __builtin_unpredictable((expr))
  1233. #endif
  1234. #if \
  1235. JSON_HEDLEY_HAS_BUILTIN(__builtin_expect_with_probability) || \
  1236. JSON_HEDLEY_GCC_VERSION_CHECK(9,0,0)
  1237. # define JSON_HEDLEY_PREDICT(expr, value, probability) __builtin_expect_with_probability( (expr), (value), (probability))
  1238. # define JSON_HEDLEY_PREDICT_TRUE(expr, probability) __builtin_expect_with_probability(!!(expr), 1 , (probability))
  1239. # define JSON_HEDLEY_PREDICT_FALSE(expr, probability) __builtin_expect_with_probability(!!(expr), 0 , (probability))
  1240. # define JSON_HEDLEY_LIKELY(expr) __builtin_expect (!!(expr), 1 )
  1241. # define JSON_HEDLEY_UNLIKELY(expr) __builtin_expect (!!(expr), 0 )
  1242. #elif \
  1243. JSON_HEDLEY_HAS_BUILTIN(__builtin_expect) || \
  1244. JSON_HEDLEY_GCC_VERSION_CHECK(3,0,0) || \
  1245. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
  1246. (JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,15,0) && defined(__cplusplus)) || \
  1247. JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \
  1248. JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \
  1249. JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \
  1250. JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,7,0) || \
  1251. JSON_HEDLEY_TI_CL430_VERSION_CHECK(3,1,0) || \
  1252. JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,1,0) || \
  1253. JSON_HEDLEY_TI_CL6X_VERSION_CHECK(6,1,0) || \
  1254. JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \
  1255. JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \
  1256. JSON_HEDLEY_TINYC_VERSION_CHECK(0,9,27) || \
  1257. JSON_HEDLEY_CRAY_VERSION_CHECK(8,1,0)
  1258. # define JSON_HEDLEY_PREDICT(expr, expected, probability) \
  1259. (((probability) >= 0.9) ? __builtin_expect((expr), (expected)) : (JSON_HEDLEY_STATIC_CAST(void, expected), (expr)))
  1260. # define JSON_HEDLEY_PREDICT_TRUE(expr, probability) \
  1261. (__extension__ ({ \
  1262. double hedley_probability_ = (probability); \
  1263. ((hedley_probability_ >= 0.9) ? __builtin_expect(!!(expr), 1) : ((hedley_probability_ <= 0.1) ? __builtin_expect(!!(expr), 0) : !!(expr))); \
  1264. }))
  1265. # define JSON_HEDLEY_PREDICT_FALSE(expr, probability) \
  1266. (__extension__ ({ \
  1267. double hedley_probability_ = (probability); \
  1268. ((hedley_probability_ >= 0.9) ? __builtin_expect(!!(expr), 0) : ((hedley_probability_ <= 0.1) ? __builtin_expect(!!(expr), 1) : !!(expr))); \
  1269. }))
  1270. # define JSON_HEDLEY_LIKELY(expr) __builtin_expect(!!(expr), 1)
  1271. # define JSON_HEDLEY_UNLIKELY(expr) __builtin_expect(!!(expr), 0)
  1272. #else
  1273. # define JSON_HEDLEY_PREDICT(expr, expected, probability) (JSON_HEDLEY_STATIC_CAST(void, expected), (expr))
  1274. # define JSON_HEDLEY_PREDICT_TRUE(expr, probability) (!!(expr))
  1275. # define JSON_HEDLEY_PREDICT_FALSE(expr, probability) (!!(expr))
  1276. # define JSON_HEDLEY_LIKELY(expr) (!!(expr))
  1277. # define JSON_HEDLEY_UNLIKELY(expr) (!!(expr))
  1278. #endif
  1279. #if !defined(JSON_HEDLEY_UNPREDICTABLE)
  1280. #define JSON_HEDLEY_UNPREDICTABLE(expr) JSON_HEDLEY_PREDICT(expr, 1, 0.5)
  1281. #endif
  1282. #if defined(JSON_HEDLEY_MALLOC)
  1283. #undef JSON_HEDLEY_MALLOC
  1284. #endif
  1285. #if \
  1286. JSON_HEDLEY_HAS_ATTRIBUTE(malloc) || \
  1287. JSON_HEDLEY_GCC_VERSION_CHECK(3,1,0) || \
  1288. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
  1289. JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,11,0) || \
  1290. JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \
  1291. JSON_HEDLEY_IBM_VERSION_CHECK(12,1,0) || \
  1292. JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \
  1293. (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  1294. JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \
  1295. (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  1296. JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \
  1297. (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  1298. JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \
  1299. (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  1300. JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \
  1301. JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \
  1302. JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0)
  1303. #define JSON_HEDLEY_MALLOC __attribute__((__malloc__))
  1304. #elif JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,10,0)
  1305. #define JSON_HEDLEY_MALLOC _Pragma("returns_new_memory")
  1306. #elif JSON_HEDLEY_MSVC_VERSION_CHECK(14, 0, 0)
  1307. #define JSON_HEDLEY_MALLOC __declspec(restrict)
  1308. #else
  1309. #define JSON_HEDLEY_MALLOC
  1310. #endif
  1311. #if defined(JSON_HEDLEY_PURE)
  1312. #undef JSON_HEDLEY_PURE
  1313. #endif
  1314. #if \
  1315. JSON_HEDLEY_HAS_ATTRIBUTE(pure) || \
  1316. JSON_HEDLEY_GCC_VERSION_CHECK(2,96,0) || \
  1317. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
  1318. JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,11,0) || \
  1319. JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \
  1320. JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \
  1321. JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \
  1322. (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  1323. JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \
  1324. (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  1325. JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \
  1326. (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  1327. JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \
  1328. (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  1329. JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \
  1330. JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \
  1331. JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \
  1332. JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0)
  1333. # define JSON_HEDLEY_PURE __attribute__((__pure__))
  1334. #elif JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,10,0)
  1335. # define JSON_HEDLEY_PURE _Pragma("does_not_write_global_data")
  1336. #elif defined(__cplusplus) && \
  1337. ( \
  1338. JSON_HEDLEY_TI_CL430_VERSION_CHECK(2,0,1) || \
  1339. JSON_HEDLEY_TI_CL6X_VERSION_CHECK(4,0,0) || \
  1340. JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) \
  1341. )
  1342. # define JSON_HEDLEY_PURE _Pragma("FUNC_IS_PURE;")
  1343. #else
  1344. # define JSON_HEDLEY_PURE
  1345. #endif
  1346. #if defined(JSON_HEDLEY_CONST)
  1347. #undef JSON_HEDLEY_CONST
  1348. #endif
  1349. #if \
  1350. JSON_HEDLEY_HAS_ATTRIBUTE(const) || \
  1351. JSON_HEDLEY_GCC_VERSION_CHECK(2,5,0) || \
  1352. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
  1353. JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,11,0) || \
  1354. JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \
  1355. JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \
  1356. JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \
  1357. (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  1358. JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \
  1359. (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  1360. JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \
  1361. (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  1362. JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \
  1363. (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  1364. JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \
  1365. JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \
  1366. JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \
  1367. JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0)
  1368. #define JSON_HEDLEY_CONST __attribute__((__const__))
  1369. #elif \
  1370. JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,10,0)
  1371. #define JSON_HEDLEY_CONST _Pragma("no_side_effect")
  1372. #else
  1373. #define JSON_HEDLEY_CONST JSON_HEDLEY_PURE
  1374. #endif
  1375. #if defined(JSON_HEDLEY_RESTRICT)
  1376. #undef JSON_HEDLEY_RESTRICT
  1377. #endif
  1378. #if defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) && !defined(__cplusplus)
  1379. #define JSON_HEDLEY_RESTRICT restrict
  1380. #elif \
  1381. JSON_HEDLEY_GCC_VERSION_CHECK(3,1,0) || \
  1382. JSON_HEDLEY_MSVC_VERSION_CHECK(14,0,0) || \
  1383. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
  1384. JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \
  1385. JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \
  1386. JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0) || \
  1387. JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \
  1388. JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,2,4) || \
  1389. JSON_HEDLEY_TI_CL6X_VERSION_CHECK(8,1,0) || \
  1390. JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \
  1391. (JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,14,0) && defined(__cplusplus)) || \
  1392. JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0) || \
  1393. defined(__clang__)
  1394. #define JSON_HEDLEY_RESTRICT __restrict
  1395. #elif JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,3,0) && !defined(__cplusplus)
  1396. #define JSON_HEDLEY_RESTRICT _Restrict
  1397. #else
  1398. #define JSON_HEDLEY_RESTRICT
  1399. #endif
  1400. #if defined(JSON_HEDLEY_INLINE)
  1401. #undef JSON_HEDLEY_INLINE
  1402. #endif
  1403. #if \
  1404. (defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L)) || \
  1405. (defined(__cplusplus) && (__cplusplus >= 199711L))
  1406. #define JSON_HEDLEY_INLINE inline
  1407. #elif \
  1408. defined(JSON_HEDLEY_GCC_VERSION) || \
  1409. JSON_HEDLEY_ARM_VERSION_CHECK(6,2,0)
  1410. #define JSON_HEDLEY_INLINE __inline__
  1411. #elif \
  1412. JSON_HEDLEY_MSVC_VERSION_CHECK(12,0,0) || \
  1413. JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \
  1414. JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,1,0) || \
  1415. JSON_HEDLEY_TI_CL430_VERSION_CHECK(3,1,0) || \
  1416. JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,2,0) || \
  1417. JSON_HEDLEY_TI_CL6X_VERSION_CHECK(8,0,0) || \
  1418. JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \
  1419. JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0)
  1420. #define JSON_HEDLEY_INLINE __inline
  1421. #else
  1422. #define JSON_HEDLEY_INLINE
  1423. #endif
  1424. #if defined(JSON_HEDLEY_ALWAYS_INLINE)
  1425. #undef JSON_HEDLEY_ALWAYS_INLINE
  1426. #endif
  1427. #if \
  1428. JSON_HEDLEY_HAS_ATTRIBUTE(always_inline) || \
  1429. JSON_HEDLEY_GCC_VERSION_CHECK(4,0,0) || \
  1430. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
  1431. JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,11,0) || \
  1432. JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \
  1433. JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \
  1434. JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \
  1435. (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  1436. JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \
  1437. (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  1438. JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \
  1439. (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  1440. JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \
  1441. (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  1442. JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \
  1443. JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \
  1444. JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0)
  1445. # define JSON_HEDLEY_ALWAYS_INLINE __attribute__((__always_inline__)) JSON_HEDLEY_INLINE
  1446. #elif JSON_HEDLEY_MSVC_VERSION_CHECK(12,0,0)
  1447. # define JSON_HEDLEY_ALWAYS_INLINE __forceinline
  1448. #elif defined(__cplusplus) && \
  1449. ( \
  1450. JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \
  1451. JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \
  1452. JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \
  1453. JSON_HEDLEY_TI_CL6X_VERSION_CHECK(6,1,0) || \
  1454. JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \
  1455. JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) \
  1456. )
  1457. # define JSON_HEDLEY_ALWAYS_INLINE _Pragma("FUNC_ALWAYS_INLINE;")
  1458. #elif JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0)
  1459. # define JSON_HEDLEY_ALWAYS_INLINE _Pragma("inline=forced")
  1460. #else
  1461. # define JSON_HEDLEY_ALWAYS_INLINE JSON_HEDLEY_INLINE
  1462. #endif
  1463. #if defined(JSON_HEDLEY_NEVER_INLINE)
  1464. #undef JSON_HEDLEY_NEVER_INLINE
  1465. #endif
  1466. #if \
  1467. JSON_HEDLEY_HAS_ATTRIBUTE(noinline) || \
  1468. JSON_HEDLEY_GCC_VERSION_CHECK(4,0,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. #define JSON_HEDLEY_NEVER_INLINE __attribute__((__noinline__))
  1485. #elif JSON_HEDLEY_MSVC_VERSION_CHECK(13,10,0)
  1486. #define JSON_HEDLEY_NEVER_INLINE __declspec(noinline)
  1487. #elif JSON_HEDLEY_PGI_VERSION_CHECK(10,2,0)
  1488. #define JSON_HEDLEY_NEVER_INLINE _Pragma("noinline")
  1489. #elif JSON_HEDLEY_TI_CL6X_VERSION_CHECK(6,0,0) && defined(__cplusplus)
  1490. #define JSON_HEDLEY_NEVER_INLINE _Pragma("FUNC_CANNOT_INLINE;")
  1491. #elif JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0)
  1492. #define JSON_HEDLEY_NEVER_INLINE _Pragma("inline=never")
  1493. #elif JSON_HEDLEY_COMPCERT_VERSION_CHECK(3,2,0)
  1494. #define JSON_HEDLEY_NEVER_INLINE __attribute((noinline))
  1495. #elif JSON_HEDLEY_PELLES_VERSION_CHECK(9,0,0)
  1496. #define JSON_HEDLEY_NEVER_INLINE __declspec(noinline)
  1497. #else
  1498. #define JSON_HEDLEY_NEVER_INLINE
  1499. #endif
  1500. #if defined(JSON_HEDLEY_PRIVATE)
  1501. #undef JSON_HEDLEY_PRIVATE
  1502. #endif
  1503. #if defined(JSON_HEDLEY_PUBLIC)
  1504. #undef JSON_HEDLEY_PUBLIC
  1505. #endif
  1506. #if defined(JSON_HEDLEY_IMPORT)
  1507. #undef JSON_HEDLEY_IMPORT
  1508. #endif
  1509. #if defined(_WIN32) || defined(__CYGWIN__)
  1510. # define JSON_HEDLEY_PRIVATE
  1511. # define JSON_HEDLEY_PUBLIC __declspec(dllexport)
  1512. # define JSON_HEDLEY_IMPORT __declspec(dllimport)
  1513. #else
  1514. # if \
  1515. JSON_HEDLEY_HAS_ATTRIBUTE(visibility) || \
  1516. JSON_HEDLEY_GCC_VERSION_CHECK(3,3,0) || \
  1517. JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,11,0) || \
  1518. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
  1519. JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \
  1520. JSON_HEDLEY_IBM_VERSION_CHECK(13,1,0) || \
  1521. ( \
  1522. defined(__TI_EABI__) && \
  1523. ( \
  1524. (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  1525. JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) \
  1526. ) \
  1527. )
  1528. # define JSON_HEDLEY_PRIVATE __attribute__((__visibility__("hidden")))
  1529. # define JSON_HEDLEY_PUBLIC __attribute__((__visibility__("default")))
  1530. # else
  1531. # define JSON_HEDLEY_PRIVATE
  1532. # define JSON_HEDLEY_PUBLIC
  1533. # endif
  1534. # define JSON_HEDLEY_IMPORT extern
  1535. #endif
  1536. #if defined(JSON_HEDLEY_NO_THROW)
  1537. #undef JSON_HEDLEY_NO_THROW
  1538. #endif
  1539. #if \
  1540. JSON_HEDLEY_HAS_ATTRIBUTE(nothrow) || \
  1541. JSON_HEDLEY_GCC_VERSION_CHECK(3,3,0) || \
  1542. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0)
  1543. #define JSON_HEDLEY_NO_THROW __attribute__((__nothrow__))
  1544. #elif \
  1545. JSON_HEDLEY_MSVC_VERSION_CHECK(13,1,0) || \
  1546. JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0)
  1547. #define JSON_HEDLEY_NO_THROW __declspec(nothrow)
  1548. #else
  1549. #define JSON_HEDLEY_NO_THROW
  1550. #endif
  1551. #if defined(JSON_HEDLEY_FALL_THROUGH)
  1552. #undef JSON_HEDLEY_FALL_THROUGH
  1553. #endif
  1554. #if \
  1555. JSON_HEDLEY_HAS_ATTRIBUTE(fallthrough) || \
  1556. JSON_HEDLEY_GCC_VERSION_CHECK(7,0,0)
  1557. #define JSON_HEDLEY_FALL_THROUGH __attribute__((__fallthrough__))
  1558. #elif JSON_HEDLEY_HAS_CPP_ATTRIBUTE_NS(clang,fallthrough)
  1559. #define JSON_HEDLEY_FALL_THROUGH JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[clang::fallthrough]])
  1560. #elif JSON_HEDLEY_HAS_CPP_ATTRIBUTE(fallthrough)
  1561. #define JSON_HEDLEY_FALL_THROUGH JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[fallthrough]])
  1562. #elif defined(__fallthrough) /* SAL */
  1563. #define JSON_HEDLEY_FALL_THROUGH __fallthrough
  1564. #else
  1565. #define JSON_HEDLEY_FALL_THROUGH
  1566. #endif
  1567. #if defined(JSON_HEDLEY_RETURNS_NON_NULL)
  1568. #undef JSON_HEDLEY_RETURNS_NON_NULL
  1569. #endif
  1570. #if \
  1571. JSON_HEDLEY_HAS_ATTRIBUTE(returns_nonnull) || \
  1572. JSON_HEDLEY_GCC_VERSION_CHECK(4,9,0)
  1573. #define JSON_HEDLEY_RETURNS_NON_NULL __attribute__((__returns_nonnull__))
  1574. #elif defined(_Ret_notnull_) /* SAL */
  1575. #define JSON_HEDLEY_RETURNS_NON_NULL _Ret_notnull_
  1576. #else
  1577. #define JSON_HEDLEY_RETURNS_NON_NULL
  1578. #endif
  1579. #if defined(JSON_HEDLEY_ARRAY_PARAM)
  1580. #undef JSON_HEDLEY_ARRAY_PARAM
  1581. #endif
  1582. #if \
  1583. defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) && \
  1584. !defined(__STDC_NO_VLA__) && \
  1585. !defined(__cplusplus) && \
  1586. !defined(JSON_HEDLEY_PGI_VERSION) && \
  1587. !defined(JSON_HEDLEY_TINYC_VERSION)
  1588. #define JSON_HEDLEY_ARRAY_PARAM(name) (name)
  1589. #else
  1590. #define JSON_HEDLEY_ARRAY_PARAM(name)
  1591. #endif
  1592. #if defined(JSON_HEDLEY_IS_CONSTANT)
  1593. #undef JSON_HEDLEY_IS_CONSTANT
  1594. #endif
  1595. #if defined(JSON_HEDLEY_REQUIRE_CONSTEXPR)
  1596. #undef JSON_HEDLEY_REQUIRE_CONSTEXPR
  1597. #endif
  1598. /* JSON_HEDLEY_IS_CONSTEXPR_ is for
  1599. HEDLEY INTERNAL USE ONLY. API subject to change without notice. */
  1600. #if defined(JSON_HEDLEY_IS_CONSTEXPR_)
  1601. #undef JSON_HEDLEY_IS_CONSTEXPR_
  1602. #endif
  1603. #if \
  1604. JSON_HEDLEY_HAS_BUILTIN(__builtin_constant_p) || \
  1605. JSON_HEDLEY_GCC_VERSION_CHECK(3,4,0) || \
  1606. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
  1607. JSON_HEDLEY_TINYC_VERSION_CHECK(0,9,19) || \
  1608. JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \
  1609. JSON_HEDLEY_IBM_VERSION_CHECK(13,1,0) || \
  1610. JSON_HEDLEY_TI_CL6X_VERSION_CHECK(6,1,0) || \
  1611. (JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,10,0) && !defined(__cplusplus)) || \
  1612. JSON_HEDLEY_CRAY_VERSION_CHECK(8,1,0)
  1613. #define JSON_HEDLEY_IS_CONSTANT(expr) __builtin_constant_p(expr)
  1614. #endif
  1615. #if !defined(__cplusplus)
  1616. # if \
  1617. JSON_HEDLEY_HAS_BUILTIN(__builtin_types_compatible_p) || \
  1618. JSON_HEDLEY_GCC_VERSION_CHECK(3,4,0) || \
  1619. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
  1620. JSON_HEDLEY_IBM_VERSION_CHECK(13,1,0) || \
  1621. JSON_HEDLEY_CRAY_VERSION_CHECK(8,1,0) || \
  1622. JSON_HEDLEY_ARM_VERSION_CHECK(5,4,0) || \
  1623. JSON_HEDLEY_TINYC_VERSION_CHECK(0,9,24)
  1624. #if defined(__INTPTR_TYPE__)
  1625. #define JSON_HEDLEY_IS_CONSTEXPR_(expr) __builtin_types_compatible_p(__typeof__((1 ? (void*) ((__INTPTR_TYPE__) ((expr) * 0)) : (int*) 0)), int*)
  1626. #else
  1627. #include <stdint.h>
  1628. #define JSON_HEDLEY_IS_CONSTEXPR_(expr) __builtin_types_compatible_p(__typeof__((1 ? (void*) ((intptr_t) ((expr) * 0)) : (int*) 0)), int*)
  1629. #endif
  1630. # elif \
  1631. ( \
  1632. defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 201112L) && \
  1633. !defined(JSON_HEDLEY_SUNPRO_VERSION) && \
  1634. !defined(JSON_HEDLEY_PGI_VERSION) && \
  1635. !defined(JSON_HEDLEY_IAR_VERSION)) || \
  1636. JSON_HEDLEY_HAS_EXTENSION(c_generic_selections) || \
  1637. JSON_HEDLEY_GCC_VERSION_CHECK(4,9,0) || \
  1638. JSON_HEDLEY_INTEL_VERSION_CHECK(17,0,0) || \
  1639. JSON_HEDLEY_IBM_VERSION_CHECK(12,1,0) || \
  1640. JSON_HEDLEY_ARM_VERSION_CHECK(5,3,0)
  1641. #if defined(__INTPTR_TYPE__)
  1642. #define JSON_HEDLEY_IS_CONSTEXPR_(expr) _Generic((1 ? (void*) ((__INTPTR_TYPE__) ((expr) * 0)) : (int*) 0), int*: 1, void*: 0)
  1643. #else
  1644. #include <stdint.h>
  1645. #define JSON_HEDLEY_IS_CONSTEXPR_(expr) _Generic((1 ? (void*) ((intptr_t) * 0) : (int*) 0), int*: 1, void*: 0)
  1646. #endif
  1647. # elif \
  1648. defined(JSON_HEDLEY_GCC_VERSION) || \
  1649. defined(JSON_HEDLEY_INTEL_VERSION) || \
  1650. defined(JSON_HEDLEY_TINYC_VERSION) || \
  1651. defined(JSON_HEDLEY_TI_ARMCL_VERSION) || \
  1652. JSON_HEDLEY_TI_CL430_VERSION_CHECK(18,12,0) || \
  1653. defined(JSON_HEDLEY_TI_CL2000_VERSION) || \
  1654. defined(JSON_HEDLEY_TI_CL6X_VERSION) || \
  1655. defined(JSON_HEDLEY_TI_CL7X_VERSION) || \
  1656. defined(JSON_HEDLEY_TI_CLPRU_VERSION) || \
  1657. defined(__clang__)
  1658. # define JSON_HEDLEY_IS_CONSTEXPR_(expr) ( \
  1659. sizeof(void) != \
  1660. sizeof(*( \
  1661. 1 ? \
  1662. ((void*) ((expr) * 0L) ) : \
  1663. ((struct { char v[sizeof(void) * 2]; } *) 1) \
  1664. ) \
  1665. ) \
  1666. )
  1667. # endif
  1668. #endif
  1669. #if defined(JSON_HEDLEY_IS_CONSTEXPR_)
  1670. #if !defined(JSON_HEDLEY_IS_CONSTANT)
  1671. #define JSON_HEDLEY_IS_CONSTANT(expr) JSON_HEDLEY_IS_CONSTEXPR_(expr)
  1672. #endif
  1673. #define JSON_HEDLEY_REQUIRE_CONSTEXPR(expr) (JSON_HEDLEY_IS_CONSTEXPR_(expr) ? (expr) : (-1))
  1674. #else
  1675. #if !defined(JSON_HEDLEY_IS_CONSTANT)
  1676. #define JSON_HEDLEY_IS_CONSTANT(expr) (0)
  1677. #endif
  1678. #define JSON_HEDLEY_REQUIRE_CONSTEXPR(expr) (expr)
  1679. #endif
  1680. #if defined(JSON_HEDLEY_BEGIN_C_DECLS)
  1681. #undef JSON_HEDLEY_BEGIN_C_DECLS
  1682. #endif
  1683. #if defined(JSON_HEDLEY_END_C_DECLS)
  1684. #undef JSON_HEDLEY_END_C_DECLS
  1685. #endif
  1686. #if defined(JSON_HEDLEY_C_DECL)
  1687. #undef JSON_HEDLEY_C_DECL
  1688. #endif
  1689. #if defined(__cplusplus)
  1690. #define JSON_HEDLEY_BEGIN_C_DECLS extern "C" {
  1691. #define JSON_HEDLEY_END_C_DECLS }
  1692. #define JSON_HEDLEY_C_DECL extern "C"
  1693. #else
  1694. #define JSON_HEDLEY_BEGIN_C_DECLS
  1695. #define JSON_HEDLEY_END_C_DECLS
  1696. #define JSON_HEDLEY_C_DECL
  1697. #endif
  1698. #if defined(JSON_HEDLEY_STATIC_ASSERT)
  1699. #undef JSON_HEDLEY_STATIC_ASSERT
  1700. #endif
  1701. #if \
  1702. !defined(__cplusplus) && ( \
  1703. (defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 201112L)) || \
  1704. JSON_HEDLEY_HAS_FEATURE(c_static_assert) || \
  1705. JSON_HEDLEY_GCC_VERSION_CHECK(6,0,0) || \
  1706. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
  1707. defined(_Static_assert) \
  1708. )
  1709. # define JSON_HEDLEY_STATIC_ASSERT(expr, message) _Static_assert(expr, message)
  1710. #elif \
  1711. (defined(__cplusplus) && (__cplusplus >= 201103L)) || \
  1712. JSON_HEDLEY_MSVC_VERSION_CHECK(16,0,0)
  1713. # define JSON_HEDLEY_STATIC_ASSERT(expr, message) JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_(static_assert(expr, message))
  1714. #else
  1715. # define JSON_HEDLEY_STATIC_ASSERT(expr, message)
  1716. #endif
  1717. #if defined(JSON_HEDLEY_NULL)
  1718. #undef JSON_HEDLEY_NULL
  1719. #endif
  1720. #if defined(__cplusplus)
  1721. #if __cplusplus >= 201103L
  1722. #define JSON_HEDLEY_NULL JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_(nullptr)
  1723. #elif defined(NULL)
  1724. #define JSON_HEDLEY_NULL NULL
  1725. #else
  1726. #define JSON_HEDLEY_NULL JSON_HEDLEY_STATIC_CAST(void*, 0)
  1727. #endif
  1728. #elif defined(NULL)
  1729. #define JSON_HEDLEY_NULL NULL
  1730. #else
  1731. #define JSON_HEDLEY_NULL ((void*) 0)
  1732. #endif
  1733. #if defined(JSON_HEDLEY_MESSAGE)
  1734. #undef JSON_HEDLEY_MESSAGE
  1735. #endif
  1736. #if JSON_HEDLEY_HAS_WARNING("-Wunknown-pragmas")
  1737. # define JSON_HEDLEY_MESSAGE(msg) \
  1738. JSON_HEDLEY_DIAGNOSTIC_PUSH \
  1739. JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS \
  1740. JSON_HEDLEY_PRAGMA(message msg) \
  1741. JSON_HEDLEY_DIAGNOSTIC_POP
  1742. #elif \
  1743. JSON_HEDLEY_GCC_VERSION_CHECK(4,4,0) || \
  1744. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0)
  1745. # define JSON_HEDLEY_MESSAGE(msg) JSON_HEDLEY_PRAGMA(message msg)
  1746. #elif JSON_HEDLEY_CRAY_VERSION_CHECK(5,0,0)
  1747. # define JSON_HEDLEY_MESSAGE(msg) JSON_HEDLEY_PRAGMA(_CRI message msg)
  1748. #elif JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0)
  1749. # define JSON_HEDLEY_MESSAGE(msg) JSON_HEDLEY_PRAGMA(message(msg))
  1750. #elif JSON_HEDLEY_PELLES_VERSION_CHECK(2,0,0)
  1751. # define JSON_HEDLEY_MESSAGE(msg) JSON_HEDLEY_PRAGMA(message(msg))
  1752. #else
  1753. # define JSON_HEDLEY_MESSAGE(msg)
  1754. #endif
  1755. #if defined(JSON_HEDLEY_WARNING)
  1756. #undef JSON_HEDLEY_WARNING
  1757. #endif
  1758. #if JSON_HEDLEY_HAS_WARNING("-Wunknown-pragmas")
  1759. # define JSON_HEDLEY_WARNING(msg) \
  1760. JSON_HEDLEY_DIAGNOSTIC_PUSH \
  1761. JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS \
  1762. JSON_HEDLEY_PRAGMA(clang warning msg) \
  1763. JSON_HEDLEY_DIAGNOSTIC_POP
  1764. #elif \
  1765. JSON_HEDLEY_GCC_VERSION_CHECK(4,8,0) || \
  1766. JSON_HEDLEY_PGI_VERSION_CHECK(18,4,0) || \
  1767. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0)
  1768. # define JSON_HEDLEY_WARNING(msg) JSON_HEDLEY_PRAGMA(GCC warning msg)
  1769. #elif JSON_HEDLEY_MSVC_VERSION_CHECK(15,0,0)
  1770. # define JSON_HEDLEY_WARNING(msg) JSON_HEDLEY_PRAGMA(message(msg))
  1771. #else
  1772. # define JSON_HEDLEY_WARNING(msg) JSON_HEDLEY_MESSAGE(msg)
  1773. #endif
  1774. #if defined(JSON_HEDLEY_REQUIRE)
  1775. #undef JSON_HEDLEY_REQUIRE
  1776. #endif
  1777. #if defined(JSON_HEDLEY_REQUIRE_MSG)
  1778. #undef JSON_HEDLEY_REQUIRE_MSG
  1779. #endif
  1780. #if JSON_HEDLEY_HAS_ATTRIBUTE(diagnose_if)
  1781. # if JSON_HEDLEY_HAS_WARNING("-Wgcc-compat")
  1782. # define JSON_HEDLEY_REQUIRE(expr) \
  1783. JSON_HEDLEY_DIAGNOSTIC_PUSH \
  1784. _Pragma("clang diagnostic ignored \"-Wgcc-compat\"") \
  1785. __attribute__((diagnose_if(!(expr), #expr, "error"))) \
  1786. JSON_HEDLEY_DIAGNOSTIC_POP
  1787. # define JSON_HEDLEY_REQUIRE_MSG(expr,msg) \
  1788. JSON_HEDLEY_DIAGNOSTIC_PUSH \
  1789. _Pragma("clang diagnostic ignored \"-Wgcc-compat\"") \
  1790. __attribute__((diagnose_if(!(expr), msg, "error"))) \
  1791. JSON_HEDLEY_DIAGNOSTIC_POP
  1792. # else
  1793. # define JSON_HEDLEY_REQUIRE(expr) __attribute__((diagnose_if(!(expr), #expr, "error")))
  1794. # define JSON_HEDLEY_REQUIRE_MSG(expr,msg) __attribute__((diagnose_if(!(expr), msg, "error")))
  1795. # endif
  1796. #else
  1797. # define JSON_HEDLEY_REQUIRE(expr)
  1798. # define JSON_HEDLEY_REQUIRE_MSG(expr,msg)
  1799. #endif
  1800. #if defined(JSON_HEDLEY_FLAGS)
  1801. #undef JSON_HEDLEY_FLAGS
  1802. #endif
  1803. #if JSON_HEDLEY_HAS_ATTRIBUTE(flag_enum)
  1804. #define JSON_HEDLEY_FLAGS __attribute__((__flag_enum__))
  1805. #endif
  1806. #if defined(JSON_HEDLEY_FLAGS_CAST)
  1807. #undef JSON_HEDLEY_FLAGS_CAST
  1808. #endif
  1809. #if JSON_HEDLEY_INTEL_VERSION_CHECK(19,0,0)
  1810. # define JSON_HEDLEY_FLAGS_CAST(T, expr) (__extension__ ({ \
  1811. JSON_HEDLEY_DIAGNOSTIC_PUSH \
  1812. _Pragma("warning(disable:188)") \
  1813. ((T) (expr)); \
  1814. JSON_HEDLEY_DIAGNOSTIC_POP \
  1815. }))
  1816. #else
  1817. # define JSON_HEDLEY_FLAGS_CAST(T, expr) JSON_HEDLEY_STATIC_CAST(T, expr)
  1818. #endif
  1819. #if defined(JSON_HEDLEY_EMPTY_BASES)
  1820. #undef JSON_HEDLEY_EMPTY_BASES
  1821. #endif
  1822. #if JSON_HEDLEY_MSVC_VERSION_CHECK(19,0,23918) && !JSON_HEDLEY_MSVC_VERSION_CHECK(20,0,0)
  1823. #define JSON_HEDLEY_EMPTY_BASES __declspec(empty_bases)
  1824. #else
  1825. #define JSON_HEDLEY_EMPTY_BASES
  1826. #endif
  1827. /* Remaining macros are deprecated. */
  1828. #if defined(JSON_HEDLEY_GCC_NOT_CLANG_VERSION_CHECK)
  1829. #undef JSON_HEDLEY_GCC_NOT_CLANG_VERSION_CHECK
  1830. #endif
  1831. #if defined(__clang__)
  1832. #define JSON_HEDLEY_GCC_NOT_CLANG_VERSION_CHECK(major,minor,patch) (0)
  1833. #else
  1834. #define JSON_HEDLEY_GCC_NOT_CLANG_VERSION_CHECK(major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch)
  1835. #endif
  1836. #if defined(JSON_HEDLEY_CLANG_HAS_ATTRIBUTE)
  1837. #undef JSON_HEDLEY_CLANG_HAS_ATTRIBUTE
  1838. #endif
  1839. #define JSON_HEDLEY_CLANG_HAS_ATTRIBUTE(attribute) JSON_HEDLEY_HAS_ATTRIBUTE(attribute)
  1840. #if defined(JSON_HEDLEY_CLANG_HAS_CPP_ATTRIBUTE)
  1841. #undef JSON_HEDLEY_CLANG_HAS_CPP_ATTRIBUTE
  1842. #endif
  1843. #define JSON_HEDLEY_CLANG_HAS_CPP_ATTRIBUTE(attribute) JSON_HEDLEY_HAS_CPP_ATTRIBUTE(attribute)
  1844. #if defined(JSON_HEDLEY_CLANG_HAS_BUILTIN)
  1845. #undef JSON_HEDLEY_CLANG_HAS_BUILTIN
  1846. #endif
  1847. #define JSON_HEDLEY_CLANG_HAS_BUILTIN(builtin) JSON_HEDLEY_HAS_BUILTIN(builtin)
  1848. #if defined(JSON_HEDLEY_CLANG_HAS_FEATURE)
  1849. #undef JSON_HEDLEY_CLANG_HAS_FEATURE
  1850. #endif
  1851. #define JSON_HEDLEY_CLANG_HAS_FEATURE(feature) JSON_HEDLEY_HAS_FEATURE(feature)
  1852. #if defined(JSON_HEDLEY_CLANG_HAS_EXTENSION)
  1853. #undef JSON_HEDLEY_CLANG_HAS_EXTENSION
  1854. #endif
  1855. #define JSON_HEDLEY_CLANG_HAS_EXTENSION(extension) JSON_HEDLEY_HAS_EXTENSION(extension)
  1856. #if defined(JSON_HEDLEY_CLANG_HAS_DECLSPEC_DECLSPEC_ATTRIBUTE)
  1857. #undef JSON_HEDLEY_CLANG_HAS_DECLSPEC_DECLSPEC_ATTRIBUTE
  1858. #endif
  1859. #define JSON_HEDLEY_CLANG_HAS_DECLSPEC_ATTRIBUTE(attribute) JSON_HEDLEY_HAS_DECLSPEC_ATTRIBUTE(attribute)
  1860. #if defined(JSON_HEDLEY_CLANG_HAS_WARNING)
  1861. #undef JSON_HEDLEY_CLANG_HAS_WARNING
  1862. #endif
  1863. #define JSON_HEDLEY_CLANG_HAS_WARNING(warning) JSON_HEDLEY_HAS_WARNING(warning)
  1864. #endif /* !defined(JSON_HEDLEY_VERSION) || (JSON_HEDLEY_VERSION < X) */
  1865. // This file contains all internal macro definitions
  1866. // You MUST include macro_unscope.hpp at the end of json.hpp to undef all of them
  1867. // exclude unsupported compilers
  1868. #if !defined(JSON_SKIP_UNSUPPORTED_COMPILER_CHECK)
  1869. #if defined(__clang__)
  1870. #if (__clang_major__ * 10000 + __clang_minor__ * 100 + __clang_patchlevel__) < 30400
  1871. #error "unsupported Clang version - see https://github.com/nlohmann/json#supported-compilers"
  1872. #endif
  1873. #elif defined(__GNUC__) && !(defined(__ICC) || defined(__INTEL_COMPILER))
  1874. #if (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__) < 40800
  1875. #error "unsupported GCC version - see https://github.com/nlohmann/json#supported-compilers"
  1876. #endif
  1877. #endif
  1878. #endif
  1879. // C++ language standard detection
  1880. #if (defined(__cplusplus) && __cplusplus >= 202002L) || (defined(_MSVC_LANG) && _MSVC_LANG >= 202002L)
  1881. #define JSON_HAS_CPP_20
  1882. #define JSON_HAS_CPP_17
  1883. #define JSON_HAS_CPP_14
  1884. #elif (defined(__cplusplus) && __cplusplus >= 201703L) || (defined(_HAS_CXX17) && _HAS_CXX17 == 1) // fix for issue #464
  1885. #define JSON_HAS_CPP_17
  1886. #define JSON_HAS_CPP_14
  1887. #elif (defined(__cplusplus) && __cplusplus >= 201402L) || (defined(_HAS_CXX14) && _HAS_CXX14 == 1)
  1888. #define JSON_HAS_CPP_14
  1889. #endif
  1890. // disable float-equal warnings on GCC/clang
  1891. #if defined(__clang__) || defined(__GNUC__) || defined(__GNUG__)
  1892. #pragma GCC diagnostic push
  1893. #pragma GCC diagnostic ignored "-Wfloat-equal"
  1894. #endif
  1895. // disable documentation warnings on clang
  1896. #if defined(__clang__)
  1897. #pragma GCC diagnostic push
  1898. #pragma GCC diagnostic ignored "-Wdocumentation"
  1899. #endif
  1900. // allow to disable exceptions
  1901. #if (defined(__cpp_exceptions) || defined(__EXCEPTIONS) || defined(_CPPUNWIND)) && !defined(JSON_NOEXCEPTION)
  1902. #define JSON_THROW(exception) throw exception
  1903. #define JSON_TRY try
  1904. #define JSON_CATCH(exception) catch(exception)
  1905. #define JSON_INTERNAL_CATCH(exception) catch(exception)
  1906. #else
  1907. #include <cstdlib>
  1908. #define JSON_THROW(exception) std::abort()
  1909. #define JSON_TRY if(true)
  1910. #define JSON_CATCH(exception) if(false)
  1911. #define JSON_INTERNAL_CATCH(exception) if(false)
  1912. #endif
  1913. // override exception macros
  1914. #if defined(JSON_THROW_USER)
  1915. #undef JSON_THROW
  1916. #define JSON_THROW JSON_THROW_USER
  1917. #endif
  1918. #if defined(JSON_TRY_USER)
  1919. #undef JSON_TRY
  1920. #define JSON_TRY JSON_TRY_USER
  1921. #endif
  1922. #if defined(JSON_CATCH_USER)
  1923. #undef JSON_CATCH
  1924. #define JSON_CATCH JSON_CATCH_USER
  1925. #undef JSON_INTERNAL_CATCH
  1926. #define JSON_INTERNAL_CATCH JSON_CATCH_USER
  1927. #endif
  1928. #if defined(JSON_INTERNAL_CATCH_USER)
  1929. #undef JSON_INTERNAL_CATCH
  1930. #define JSON_INTERNAL_CATCH JSON_INTERNAL_CATCH_USER
  1931. #endif
  1932. // allow to override assert
  1933. #if !defined(JSON_ASSERT)
  1934. #include <cassert> // assert
  1935. #define JSON_ASSERT(x) assert(x)
  1936. #endif
  1937. /*!
  1938. @brief macro to briefly define a mapping between an enum and JSON
  1939. @def NLOHMANN_JSON_SERIALIZE_ENUM
  1940. @since version 3.4.0
  1941. */
  1942. #define NLOHMANN_JSON_SERIALIZE_ENUM(ENUM_TYPE, ...) \
  1943. template<typename BasicJsonType> \
  1944. inline void to_json(BasicJsonType& j, const ENUM_TYPE& e) \
  1945. { \
  1946. static_assert(std::is_enum<ENUM_TYPE>::value, #ENUM_TYPE " must be an enum!"); \
  1947. static const std::pair<ENUM_TYPE, BasicJsonType> m[] = __VA_ARGS__; \
  1948. auto it = std::find_if(std::begin(m), std::end(m), \
  1949. [e](const std::pair<ENUM_TYPE, BasicJsonType>& ej_pair) -> bool \
  1950. { \
  1951. return ej_pair.first == e; \
  1952. }); \
  1953. j = ((it != std::end(m)) ? it : std::begin(m))->second; \
  1954. } \
  1955. template<typename BasicJsonType> \
  1956. inline void from_json(const BasicJsonType& j, ENUM_TYPE& e) \
  1957. { \
  1958. static_assert(std::is_enum<ENUM_TYPE>::value, #ENUM_TYPE " must be an enum!"); \
  1959. static const std::pair<ENUM_TYPE, BasicJsonType> m[] = __VA_ARGS__; \
  1960. auto it = std::find_if(std::begin(m), std::end(m), \
  1961. [&j](const std::pair<ENUM_TYPE, BasicJsonType>& ej_pair) -> bool \
  1962. { \
  1963. return ej_pair.second == j; \
  1964. }); \
  1965. e = ((it != std::end(m)) ? it : std::begin(m))->first; \
  1966. }
  1967. // Ugly macros to avoid uglier copy-paste when specializing basic_json. They
  1968. // may be removed in the future once the class is split.
  1969. #define NLOHMANN_BASIC_JSON_TPL_DECLARATION \
  1970. template<template<typename, typename, typename...> class ObjectType, \
  1971. template<typename, typename...> class ArrayType, \
  1972. class StringType, class BooleanType, class NumberIntegerType, \
  1973. class NumberUnsignedType, class NumberFloatType, \
  1974. template<typename> class AllocatorType, \
  1975. template<typename, typename = void> class JSONSerializer, \
  1976. class BinaryType>
  1977. #define NLOHMANN_BASIC_JSON_TPL \
  1978. basic_json<ObjectType, ArrayType, StringType, BooleanType, \
  1979. NumberIntegerType, NumberUnsignedType, NumberFloatType, \
  1980. AllocatorType, JSONSerializer, BinaryType>
  1981. // Macros to simplify conversion from/to types
  1982. #define NLOHMANN_JSON_EXPAND( x ) x
  1983. #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
  1984. #define NLOHMANN_JSON_PASTE(...) NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_GET_MACRO(__VA_ARGS__, \
  1985. NLOHMANN_JSON_PASTE64, \
  1986. NLOHMANN_JSON_PASTE63, \
  1987. NLOHMANN_JSON_PASTE62, \
  1988. NLOHMANN_JSON_PASTE61, \
  1989. NLOHMANN_JSON_PASTE60, \
  1990. NLOHMANN_JSON_PASTE59, \
  1991. NLOHMANN_JSON_PASTE58, \
  1992. NLOHMANN_JSON_PASTE57, \
  1993. NLOHMANN_JSON_PASTE56, \
  1994. NLOHMANN_JSON_PASTE55, \
  1995. NLOHMANN_JSON_PASTE54, \
  1996. NLOHMANN_JSON_PASTE53, \
  1997. NLOHMANN_JSON_PASTE52, \
  1998. NLOHMANN_JSON_PASTE51, \
  1999. NLOHMANN_JSON_PASTE50, \
  2000. NLOHMANN_JSON_PASTE49, \
  2001. NLOHMANN_JSON_PASTE48, \
  2002. NLOHMANN_JSON_PASTE47, \
  2003. NLOHMANN_JSON_PASTE46, \
  2004. NLOHMANN_JSON_PASTE45, \
  2005. NLOHMANN_JSON_PASTE44, \
  2006. NLOHMANN_JSON_PASTE43, \
  2007. NLOHMANN_JSON_PASTE42, \
  2008. NLOHMANN_JSON_PASTE41, \
  2009. NLOHMANN_JSON_PASTE40, \
  2010. NLOHMANN_JSON_PASTE39, \
  2011. NLOHMANN_JSON_PASTE38, \
  2012. NLOHMANN_JSON_PASTE37, \
  2013. NLOHMANN_JSON_PASTE36, \
  2014. NLOHMANN_JSON_PASTE35, \
  2015. NLOHMANN_JSON_PASTE34, \
  2016. NLOHMANN_JSON_PASTE33, \
  2017. NLOHMANN_JSON_PASTE32, \
  2018. NLOHMANN_JSON_PASTE31, \
  2019. NLOHMANN_JSON_PASTE30, \
  2020. NLOHMANN_JSON_PASTE29, \
  2021. NLOHMANN_JSON_PASTE28, \
  2022. NLOHMANN_JSON_PASTE27, \
  2023. NLOHMANN_JSON_PASTE26, \
  2024. NLOHMANN_JSON_PASTE25, \
  2025. NLOHMANN_JSON_PASTE24, \
  2026. NLOHMANN_JSON_PASTE23, \
  2027. NLOHMANN_JSON_PASTE22, \
  2028. NLOHMANN_JSON_PASTE21, \
  2029. NLOHMANN_JSON_PASTE20, \
  2030. NLOHMANN_JSON_PASTE19, \
  2031. NLOHMANN_JSON_PASTE18, \
  2032. NLOHMANN_JSON_PASTE17, \
  2033. NLOHMANN_JSON_PASTE16, \
  2034. NLOHMANN_JSON_PASTE15, \
  2035. NLOHMANN_JSON_PASTE14, \
  2036. NLOHMANN_JSON_PASTE13, \
  2037. NLOHMANN_JSON_PASTE12, \
  2038. NLOHMANN_JSON_PASTE11, \
  2039. NLOHMANN_JSON_PASTE10, \
  2040. NLOHMANN_JSON_PASTE9, \
  2041. NLOHMANN_JSON_PASTE8, \
  2042. NLOHMANN_JSON_PASTE7, \
  2043. NLOHMANN_JSON_PASTE6, \
  2044. NLOHMANN_JSON_PASTE5, \
  2045. NLOHMANN_JSON_PASTE4, \
  2046. NLOHMANN_JSON_PASTE3, \
  2047. NLOHMANN_JSON_PASTE2, \
  2048. NLOHMANN_JSON_PASTE1)(__VA_ARGS__))
  2049. #define NLOHMANN_JSON_PASTE2(func, v1) func(v1)
  2050. #define NLOHMANN_JSON_PASTE3(func, v1, v2) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE2(func, v2)
  2051. #define NLOHMANN_JSON_PASTE4(func, v1, v2, v3) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE3(func, v2, v3)
  2052. #define NLOHMANN_JSON_PASTE5(func, v1, v2, v3, v4) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE4(func, v2, v3, v4)
  2053. #define NLOHMANN_JSON_PASTE6(func, v1, v2, v3, v4, v5) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE5(func, v2, v3, v4, v5)
  2054. #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)
  2055. #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)
  2056. #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)
  2057. #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)
  2058. #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)
  2059. #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)
  2060. #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)
  2061. #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)
  2062. #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)
  2063. #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)
  2064. #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)
  2065. #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)
  2066. #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)
  2067. #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)
  2068. #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)
  2069. #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)
  2070. #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)
  2071. #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)
  2072. #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)
  2073. #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)
  2074. #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)
  2075. #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)
  2076. #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)
  2077. #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)
  2078. #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)
  2079. #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)
  2080. #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)
  2081. #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)
  2082. #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)
  2083. #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)
  2084. #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)
  2085. #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)
  2086. #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)
  2087. #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)
  2088. #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)
  2089. #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)
  2090. #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)
  2091. #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)
  2092. #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)
  2093. #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)
  2094. #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)
  2095. #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)
  2096. #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)
  2097. #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)
  2098. #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)
  2099. #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)
  2100. #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)
  2101. #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)
  2102. #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)
  2103. #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)
  2104. #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)
  2105. #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)
  2106. #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)
  2107. #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)
  2108. #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)
  2109. #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)
  2110. #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)
  2111. #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)
  2112. #define NLOHMANN_JSON_TO(v1) nlohmann_json_j[#v1] = nlohmann_json_t.v1;
  2113. #define NLOHMANN_JSON_FROM(v1) nlohmann_json_j.at(#v1).get_to(nlohmann_json_t.v1);
  2114. /*!
  2115. @brief macro
  2116. @def NLOHMANN_DEFINE_TYPE_INTRUSIVE
  2117. @since version 3.9.0
  2118. */
  2119. #define NLOHMANN_DEFINE_TYPE_INTRUSIVE(Type, ...) \
  2120. 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__)) } \
  2121. 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__)) }
  2122. /*!
  2123. @brief macro
  2124. @def NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE
  2125. @since version 3.9.0
  2126. */
  2127. #define NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE(Type, ...) \
  2128. 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__)) } \
  2129. 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__)) }
  2130. #ifndef JSON_USE_IMPLICIT_CONVERSIONS
  2131. #define JSON_USE_IMPLICIT_CONVERSIONS 1
  2132. #endif
  2133. #if JSON_USE_IMPLICIT_CONVERSIONS
  2134. #define JSON_EXPLICIT
  2135. #else
  2136. #define JSON_EXPLICIT explicit
  2137. #endif
  2138. namespace nlohmann
  2139. {
  2140. namespace detail
  2141. {
  2142. ////////////////
  2143. // exceptions //
  2144. ////////////////
  2145. /*!
  2146. @brief general exception of the @ref basic_json class
  2147. This class is an extension of `std::exception` objects with a member @a id for
  2148. exception ids. It is used as the base class for all exceptions thrown by the
  2149. @ref basic_json class. This class can hence be used as "wildcard" to catch
  2150. exceptions.
  2151. Subclasses:
  2152. - @ref parse_error for exceptions indicating a parse error
  2153. - @ref invalid_iterator for exceptions indicating errors with iterators
  2154. - @ref type_error for exceptions indicating executing a member function with
  2155. a wrong type
  2156. - @ref out_of_range for exceptions indicating access out of the defined range
  2157. - @ref other_error for exceptions indicating other library errors
  2158. @internal
  2159. @note To have nothrow-copy-constructible exceptions, we internally use
  2160. `std::runtime_error` which can cope with arbitrary-length error messages.
  2161. Intermediate strings are built with static functions and then passed to
  2162. the actual constructor.
  2163. @endinternal
  2164. @liveexample{The following code shows how arbitrary library exceptions can be
  2165. caught.,exception}
  2166. @since version 3.0.0
  2167. */
  2168. class exception : public std::exception
  2169. {
  2170. public:
  2171. /// returns the explanatory string
  2172. JSON_HEDLEY_RETURNS_NON_NULL
  2173. const char* what() const noexcept override
  2174. {
  2175. return m.what();
  2176. }
  2177. /// the id of the exception
  2178. const int id;
  2179. protected:
  2180. JSON_HEDLEY_NON_NULL(3)
  2181. exception(int id_, const char* what_arg) : id(id_), m(what_arg) {}
  2182. static std::string name(const std::string& ename, int id_)
  2183. {
  2184. return "[json.exception." + ename + "." + std::to_string(id_) + "] ";
  2185. }
  2186. private:
  2187. /// an exception object as storage for error messages
  2188. std::runtime_error m;
  2189. };
  2190. /*!
  2191. @brief exception indicating a parse error
  2192. This exception is thrown by the library when a parse error occurs. Parse errors
  2193. can occur during the deserialization of JSON text, CBOR, MessagePack, as well
  2194. as when using JSON Patch.
  2195. Member @a byte holds the byte index of the last read character in the input
  2196. file.
  2197. Exceptions have ids 1xx.
  2198. name / id | example message | description
  2199. ------------------------------ | --------------- | -------------------------
  2200. 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.
  2201. 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.
  2202. 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.
  2203. 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.
  2204. 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.
  2205. 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`.
  2206. 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.
  2207. 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.
  2208. json.exception.parse_error.109 | parse error: array index 'one' is not a number | A JSON Pointer array index must be a number.
  2209. 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.
  2210. 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.
  2211. 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.
  2212. json.exception.parse_error.114 | parse error: Unsupported BSON record type 0x0F | The parsing of the corresponding BSON record type is not implemented (yet).
  2213. 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.
  2214. @note For an input with n bytes, 1 is the index of the first character and n+1
  2215. is the index of the terminating null byte or the end of file. This also
  2216. holds true when reading a byte vector (CBOR or MessagePack).
  2217. @liveexample{The following code shows how a `parse_error` exception can be
  2218. caught.,parse_error}
  2219. @sa - @ref exception for the base class of the library exceptions
  2220. @sa - @ref invalid_iterator for exceptions indicating errors with iterators
  2221. @sa - @ref type_error for exceptions indicating executing a member function with
  2222. a wrong type
  2223. @sa - @ref out_of_range for exceptions indicating access out of the defined range
  2224. @sa - @ref other_error for exceptions indicating other library errors
  2225. @since version 3.0.0
  2226. */
  2227. class parse_error : public exception
  2228. {
  2229. public:
  2230. /*!
  2231. @brief create a parse error exception
  2232. @param[in] id_ the id of the exception
  2233. @param[in] pos the position where the error occurred (or with
  2234. chars_read_total=0 if the position cannot be
  2235. determined)
  2236. @param[in] what_arg the explanatory string
  2237. @return parse_error object
  2238. */
  2239. static parse_error create(int id_, const position_t& pos, const std::string& what_arg)
  2240. {
  2241. std::string w = exception::name("parse_error", id_) + "parse error" +
  2242. position_string(pos) + ": " + what_arg;
  2243. return parse_error(id_, pos.chars_read_total, w.c_str());
  2244. }
  2245. static parse_error create(int id_, std::size_t byte_, const std::string& what_arg)
  2246. {
  2247. std::string w = exception::name("parse_error", id_) + "parse error" +
  2248. (byte_ != 0 ? (" at byte " + std::to_string(byte_)) : "") +
  2249. ": " + what_arg;
  2250. return parse_error(id_, byte_, w.c_str());
  2251. }
  2252. /*!
  2253. @brief byte index of the parse error
  2254. The byte index of the last read character in the input file.
  2255. @note For an input with n bytes, 1 is the index of the first character and
  2256. n+1 is the index of the terminating null byte or the end of file.
  2257. This also holds true when reading a byte vector (CBOR or MessagePack).
  2258. */
  2259. const std::size_t byte;
  2260. private:
  2261. parse_error(int id_, std::size_t byte_, const char* what_arg)
  2262. : exception(id_, what_arg), byte(byte_) {}
  2263. static std::string position_string(const position_t& pos)
  2264. {
  2265. return " at line " + std::to_string(pos.lines_read + 1) +
  2266. ", column " + std::to_string(pos.chars_read_current_line);
  2267. }
  2268. };
  2269. /*!
  2270. @brief exception indicating errors with iterators
  2271. This exception is thrown if iterators passed to a library function do not match
  2272. the expected semantics.
  2273. Exceptions have ids 2xx.
  2274. name / id | example message | description
  2275. ----------------------------------- | --------------- | -------------------------
  2276. 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.
  2277. 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.
  2278. 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.
  2279. 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.
  2280. 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.
  2281. 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.
  2282. 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.
  2283. 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.
  2284. 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.
  2285. 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.
  2286. 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.
  2287. json.exception.invalid_iterator.212 | cannot compare iterators of different containers | When two iterators are compared, they must belong to the same container.
  2288. json.exception.invalid_iterator.213 | cannot compare order of object iterators | The order of object iterators cannot be compared, because JSON objects are unordered.
  2289. 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().
  2290. @liveexample{The following code shows how an `invalid_iterator` exception can be
  2291. caught.,invalid_iterator}
  2292. @sa - @ref exception for the base class of the library exceptions
  2293. @sa - @ref parse_error for exceptions indicating a parse error
  2294. @sa - @ref type_error for exceptions indicating executing a member function with
  2295. a wrong type
  2296. @sa - @ref out_of_range for exceptions indicating access out of the defined range
  2297. @sa - @ref other_error for exceptions indicating other library errors
  2298. @since version 3.0.0
  2299. */
  2300. class invalid_iterator : public exception
  2301. {
  2302. public:
  2303. static invalid_iterator create(int id_, const std::string& what_arg)
  2304. {
  2305. std::string w = exception::name("invalid_iterator", id_) + what_arg;
  2306. return invalid_iterator(id_, w.c_str());
  2307. }
  2308. private:
  2309. JSON_HEDLEY_NON_NULL(3)
  2310. invalid_iterator(int id_, const char* what_arg)
  2311. : exception(id_, what_arg) {}
  2312. };
  2313. /*!
  2314. @brief exception indicating executing a member function with a wrong type
  2315. This exception is thrown in case of a type error; that is, a library function is
  2316. executed on a JSON value whose type does not match the expected semantics.
  2317. Exceptions have ids 3xx.
  2318. name / id | example message | description
  2319. ----------------------------- | --------------- | -------------------------
  2320. 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.
  2321. 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.
  2322. 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 &.
  2323. json.exception.type_error.304 | cannot use at() with string | The @ref at() member functions can only be executed for certain JSON types.
  2324. json.exception.type_error.305 | cannot use operator[] with string | The @ref operator[] member functions can only be executed for certain JSON types.
  2325. json.exception.type_error.306 | cannot use value() with string | The @ref value() member functions can only be executed for certain JSON types.
  2326. json.exception.type_error.307 | cannot use erase() with string | The @ref erase() member functions can only be executed for certain JSON types.
  2327. 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.
  2328. json.exception.type_error.309 | cannot use insert() with | The @ref insert() member functions can only be executed for certain JSON types.
  2329. json.exception.type_error.310 | cannot use swap() with number | The @ref swap() member functions can only be executed for certain JSON types.
  2330. 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.
  2331. json.exception.type_error.312 | cannot use update() with string | The @ref update() member functions can only be executed for certain JSON types.
  2332. 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.
  2333. json.exception.type_error.314 | only objects can be unflattened | The @ref unflatten function only works for an object whose keys are JSON Pointers.
  2334. 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.
  2335. 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. |
  2336. 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) |
  2337. @liveexample{The following code shows how a `type_error` exception can be
  2338. caught.,type_error}
  2339. @sa - @ref exception for the base class of the library exceptions
  2340. @sa - @ref parse_error for exceptions indicating a parse error
  2341. @sa - @ref invalid_iterator for exceptions indicating errors with iterators
  2342. @sa - @ref out_of_range for exceptions indicating access out of the defined range
  2343. @sa - @ref other_error for exceptions indicating other library errors
  2344. @since version 3.0.0
  2345. */
  2346. class type_error : public exception
  2347. {
  2348. public:
  2349. static type_error create(int id_, const std::string& what_arg)
  2350. {
  2351. std::string w = exception::name("type_error", id_) + what_arg;
  2352. return type_error(id_, w.c_str());
  2353. }
  2354. private:
  2355. JSON_HEDLEY_NON_NULL(3)
  2356. type_error(int id_, const char* what_arg) : exception(id_, what_arg) {}
  2357. };
  2358. /*!
  2359. @brief exception indicating access out of the defined range
  2360. This exception is thrown in case a library function is called on an input
  2361. parameter that exceeds the expected range, for instance in case of array
  2362. indices or nonexisting object keys.
  2363. Exceptions have ids 4xx.
  2364. name / id | example message | description
  2365. ------------------------------- | --------------- | -------------------------
  2366. 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.
  2367. 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.
  2368. json.exception.out_of_range.403 | key 'foo' not found | The provided key was not found in the JSON object.
  2369. json.exception.out_of_range.404 | unresolved reference token 'foo' | A reference token in a JSON Pointer could not be resolved.
  2370. 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.
  2371. 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.
  2372. 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) |
  2373. json.exception.out_of_range.408 | excessive array size: 8658170730974374167 | The size (following `#`) of an UBJSON array or object exceeds the maximal capacity. |
  2374. 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 |
  2375. @liveexample{The following code shows how an `out_of_range` exception can be
  2376. caught.,out_of_range}
  2377. @sa - @ref exception for the base class of the library exceptions
  2378. @sa - @ref parse_error for exceptions indicating a parse error
  2379. @sa - @ref invalid_iterator for exceptions indicating errors with iterators
  2380. @sa - @ref type_error for exceptions indicating executing a member function with
  2381. a wrong type
  2382. @sa - @ref other_error for exceptions indicating other library errors
  2383. @since version 3.0.0
  2384. */
  2385. class out_of_range : public exception
  2386. {
  2387. public:
  2388. static out_of_range create(int id_, const std::string& what_arg)
  2389. {
  2390. std::string w = exception::name("out_of_range", id_) + what_arg;
  2391. return out_of_range(id_, w.c_str());
  2392. }
  2393. private:
  2394. JSON_HEDLEY_NON_NULL(3)
  2395. out_of_range(int id_, const char* what_arg) : exception(id_, what_arg) {}
  2396. };
  2397. /*!
  2398. @brief exception indicating other library errors
  2399. This exception is thrown in case of errors that cannot be classified with the
  2400. other exception types.
  2401. Exceptions have ids 5xx.
  2402. name / id | example message | description
  2403. ------------------------------ | --------------- | -------------------------
  2404. json.exception.other_error.501 | unsuccessful: {"op":"test","path":"/baz", "value":"bar"} | A JSON Patch operation 'test' failed. The unsuccessful operation is also printed.
  2405. @sa - @ref exception for the base class of the library exceptions
  2406. @sa - @ref parse_error for exceptions indicating a parse error
  2407. @sa - @ref invalid_iterator for exceptions indicating errors with iterators
  2408. @sa - @ref type_error for exceptions indicating executing a member function with
  2409. a wrong type
  2410. @sa - @ref out_of_range for exceptions indicating access out of the defined range
  2411. @liveexample{The following code shows how an `other_error` exception can be
  2412. caught.,other_error}
  2413. @since version 3.0.0
  2414. */
  2415. class other_error : public exception
  2416. {
  2417. public:
  2418. static other_error create(int id_, const std::string& what_arg)
  2419. {
  2420. std::string w = exception::name("other_error", id_) + what_arg;
  2421. return other_error(id_, w.c_str());
  2422. }
  2423. private:
  2424. JSON_HEDLEY_NON_NULL(3)
  2425. other_error(int id_, const char* what_arg) : exception(id_, what_arg) {}
  2426. };
  2427. } // namespace detail
  2428. } // namespace nlohmann
  2429. // #include <nlohmann/detail/macro_scope.hpp>
  2430. // #include <nlohmann/detail/meta/cpp_future.hpp>
  2431. #include <cstddef> // size_t
  2432. #include <type_traits> // conditional, enable_if, false_type, integral_constant, is_constructible, is_integral, is_same, remove_cv, remove_reference, true_type
  2433. namespace nlohmann
  2434. {
  2435. namespace detail
  2436. {
  2437. // alias templates to reduce boilerplate
  2438. template<bool B, typename T = void>
  2439. using enable_if_t = typename std::enable_if<B, T>::type;
  2440. template<typename T>
  2441. using uncvref_t = typename std::remove_cv<typename std::remove_reference<T>::type>::type;
  2442. // implementation of C++14 index_sequence and affiliates
  2443. // source: https://stackoverflow.com/a/32223343
  2444. template<std::size_t... Ints>
  2445. struct index_sequence
  2446. {
  2447. using type = index_sequence;
  2448. using value_type = std::size_t;
  2449. static constexpr std::size_t size() noexcept
  2450. {
  2451. return sizeof...(Ints);
  2452. }
  2453. };
  2454. template<class Sequence1, class Sequence2>
  2455. struct merge_and_renumber;
  2456. template<std::size_t... I1, std::size_t... I2>
  2457. struct merge_and_renumber<index_sequence<I1...>, index_sequence<I2...>>
  2458. : index_sequence < I1..., (sizeof...(I1) + I2)... > {};
  2459. template<std::size_t N>
  2460. struct make_index_sequence
  2461. : merge_and_renumber < typename make_index_sequence < N / 2 >::type,
  2462. typename make_index_sequence < N - N / 2 >::type > {};
  2463. template<> struct make_index_sequence<0> : index_sequence<> {};
  2464. template<> struct make_index_sequence<1> : index_sequence<0> {};
  2465. template<typename... Ts>
  2466. using index_sequence_for = make_index_sequence<sizeof...(Ts)>;
  2467. // dispatch utility (taken from ranges-v3)
  2468. template<unsigned N> struct priority_tag : priority_tag < N - 1 > {};
  2469. template<> struct priority_tag<0> {};
  2470. // taken from ranges-v3
  2471. template<typename T>
  2472. struct static_const
  2473. {
  2474. static constexpr T value{};
  2475. };
  2476. template<typename T>
  2477. constexpr T static_const<T>::value;
  2478. } // namespace detail
  2479. } // namespace nlohmann
  2480. // #include <nlohmann/detail/meta/type_traits.hpp>
  2481. #include <limits> // numeric_limits
  2482. #include <type_traits> // false_type, is_constructible, is_integral, is_same, true_type
  2483. #include <utility> // declval
  2484. // #include <nlohmann/detail/iterators/iterator_traits.hpp>
  2485. #include <iterator> // random_access_iterator_tag
  2486. // #include <nlohmann/detail/meta/void_t.hpp>
  2487. namespace nlohmann
  2488. {
  2489. namespace detail
  2490. {
  2491. template<typename ...Ts> struct make_void
  2492. {
  2493. using type = void;
  2494. };
  2495. template<typename ...Ts> using void_t = typename make_void<Ts...>::type;
  2496. } // namespace detail
  2497. } // namespace nlohmann
  2498. // #include <nlohmann/detail/meta/cpp_future.hpp>
  2499. namespace nlohmann
  2500. {
  2501. namespace detail
  2502. {
  2503. template<typename It, typename = void>
  2504. struct iterator_types {};
  2505. template<typename It>
  2506. struct iterator_types <
  2507. It,
  2508. void_t<typename It::difference_type, typename It::value_type, typename It::pointer,
  2509. typename It::reference, typename It::iterator_category >>
  2510. {
  2511. using difference_type = typename It::difference_type;
  2512. using value_type = typename It::value_type;
  2513. using pointer = typename It::pointer;
  2514. using reference = typename It::reference;
  2515. using iterator_category = typename It::iterator_category;
  2516. };
  2517. // This is required as some compilers implement std::iterator_traits in a way that
  2518. // doesn't work with SFINAE. See https://github.com/nlohmann/json/issues/1341.
  2519. template<typename T, typename = void>
  2520. struct iterator_traits
  2521. {
  2522. };
  2523. template<typename T>
  2524. struct iterator_traits < T, enable_if_t < !std::is_pointer<T>::value >>
  2525. : iterator_types<T>
  2526. {
  2527. };
  2528. template<typename T>
  2529. struct iterator_traits<T*, enable_if_t<std::is_object<T>::value>>
  2530. {
  2531. using iterator_category = std::random_access_iterator_tag;
  2532. using value_type = T;
  2533. using difference_type = ptrdiff_t;
  2534. using pointer = T*;
  2535. using reference = T&;
  2536. };
  2537. } // namespace detail
  2538. } // namespace nlohmann
  2539. // #include <nlohmann/detail/macro_scope.hpp>
  2540. // #include <nlohmann/detail/meta/cpp_future.hpp>
  2541. // #include <nlohmann/detail/meta/detected.hpp>
  2542. #include <type_traits>
  2543. // #include <nlohmann/detail/meta/void_t.hpp>
  2544. // https://en.cppreference.com/w/cpp/experimental/is_detected
  2545. namespace nlohmann
  2546. {
  2547. namespace detail
  2548. {
  2549. struct nonesuch
  2550. {
  2551. nonesuch() = delete;
  2552. ~nonesuch() = delete;
  2553. nonesuch(nonesuch const&) = delete;
  2554. nonesuch(nonesuch const&&) = delete;
  2555. void operator=(nonesuch const&) = delete;
  2556. void operator=(nonesuch&&) = delete;
  2557. };
  2558. template<class Default,
  2559. class AlwaysVoid,
  2560. template<class...> class Op,
  2561. class... Args>
  2562. struct detector
  2563. {
  2564. using value_t = std::false_type;
  2565. using type = Default;
  2566. };
  2567. template<class Default, template<class...> class Op, class... Args>
  2568. struct detector<Default, void_t<Op<Args...>>, Op, Args...>
  2569. {
  2570. using value_t = std::true_type;
  2571. using type = Op<Args...>;
  2572. };
  2573. template<template<class...> class Op, class... Args>
  2574. using is_detected = typename detector<nonesuch, void, Op, Args...>::value_t;
  2575. template<template<class...> class Op, class... Args>
  2576. using detected_t = typename detector<nonesuch, void, Op, Args...>::type;
  2577. template<class Default, template<class...> class Op, class... Args>
  2578. using detected_or = detector<Default, void, Op, Args...>;
  2579. template<class Default, template<class...> class Op, class... Args>
  2580. using detected_or_t = typename detected_or<Default, Op, Args...>::type;
  2581. template<class Expected, template<class...> class Op, class... Args>
  2582. using is_detected_exact = std::is_same<Expected, detected_t<Op, Args...>>;
  2583. template<class To, template<class...> class Op, class... Args>
  2584. using is_detected_convertible =
  2585. std::is_convertible<detected_t<Op, Args...>, To>;
  2586. } // namespace detail
  2587. } // namespace nlohmann
  2588. // #include <nlohmann/json_fwd.hpp>
  2589. #ifndef INCLUDE_NLOHMANN_JSON_FWD_HPP_
  2590. #define INCLUDE_NLOHMANN_JSON_FWD_HPP_
  2591. #include <cstdint> // int64_t, uint64_t
  2592. #include <map> // map
  2593. #include <memory> // allocator
  2594. #include <string> // string
  2595. #include <vector> // vector
  2596. /*!
  2597. @brief namespace for Niels Lohmann
  2598. @see https://github.com/nlohmann
  2599. @since version 1.0.0
  2600. */
  2601. namespace nlohmann
  2602. {
  2603. /*!
  2604. @brief default JSONSerializer template argument
  2605. This serializer ignores the template arguments and uses ADL
  2606. ([argument-dependent lookup](https://en.cppreference.com/w/cpp/language/adl))
  2607. for serialization.
  2608. */
  2609. template<typename T = void, typename SFINAE = void>
  2610. struct adl_serializer;
  2611. template<template<typename U, typename V, typename... Args> class ObjectType =
  2612. std::map,
  2613. template<typename U, typename... Args> class ArrayType = std::vector,
  2614. class StringType = std::string, class BooleanType = bool,
  2615. class NumberIntegerType = std::int64_t,
  2616. class NumberUnsignedType = std::uint64_t,
  2617. class NumberFloatType = double,
  2618. template<typename U> class AllocatorType = std::allocator,
  2619. template<typename T, typename SFINAE = void> class JSONSerializer =
  2620. adl_serializer,
  2621. class BinaryType = std::vector<std::uint8_t>>
  2622. class basic_json;
  2623. /*!
  2624. @brief JSON Pointer
  2625. A JSON pointer defines a string syntax for identifying a specific value
  2626. within a JSON document. It can be used with functions `at` and
  2627. `operator[]`. Furthermore, JSON pointers are the base for JSON patches.
  2628. @sa [RFC 6901](https://tools.ietf.org/html/rfc6901)
  2629. @since version 2.0.0
  2630. */
  2631. template<typename BasicJsonType>
  2632. class json_pointer;
  2633. /*!
  2634. @brief default JSON class
  2635. This type is the default specialization of the @ref basic_json class which
  2636. uses the standard template types.
  2637. @since version 1.0.0
  2638. */
  2639. using json = basic_json<>;
  2640. template<class Key, class T, class IgnoredLess, class Allocator>
  2641. struct ordered_map;
  2642. /*!
  2643. @brief ordered JSON class
  2644. This type preserves the insertion order of object keys.
  2645. @since version 3.9.0
  2646. */
  2647. using ordered_json = basic_json<nlohmann::ordered_map>;
  2648. } // namespace nlohmann
  2649. #endif // INCLUDE_NLOHMANN_JSON_FWD_HPP_
  2650. namespace nlohmann
  2651. {
  2652. /*!
  2653. @brief detail namespace with internal helper functions
  2654. This namespace collects functions that should not be exposed,
  2655. implementations of some @ref basic_json methods, and meta-programming helpers.
  2656. @since version 2.1.0
  2657. */
  2658. namespace detail
  2659. {
  2660. /////////////
  2661. // helpers //
  2662. /////////////
  2663. // Note to maintainers:
  2664. //
  2665. // Every trait in this file expects a non CV-qualified type.
  2666. // The only exceptions are in the 'aliases for detected' section
  2667. // (i.e. those of the form: decltype(T::member_function(std::declval<T>())))
  2668. //
  2669. // In this case, T has to be properly CV-qualified to constraint the function arguments
  2670. // (e.g. to_json(BasicJsonType&, const T&))
  2671. template<typename> struct is_basic_json : std::false_type {};
  2672. NLOHMANN_BASIC_JSON_TPL_DECLARATION
  2673. struct is_basic_json<NLOHMANN_BASIC_JSON_TPL> : std::true_type {};
  2674. //////////////////////
  2675. // json_ref helpers //
  2676. //////////////////////
  2677. template<typename>
  2678. class json_ref;
  2679. template<typename>
  2680. struct is_json_ref : std::false_type {};
  2681. template<typename T>
  2682. struct is_json_ref<json_ref<T>> : std::true_type {};
  2683. //////////////////////////
  2684. // aliases for detected //
  2685. //////////////////////////
  2686. template<typename T>
  2687. using mapped_type_t = typename T::mapped_type;
  2688. template<typename T>
  2689. using key_type_t = typename T::key_type;
  2690. template<typename T>
  2691. using value_type_t = typename T::value_type;
  2692. template<typename T>
  2693. using difference_type_t = typename T::difference_type;
  2694. template<typename T>
  2695. using pointer_t = typename T::pointer;
  2696. template<typename T>
  2697. using reference_t = typename T::reference;
  2698. template<typename T>
  2699. using iterator_category_t = typename T::iterator_category;
  2700. template<typename T>
  2701. using iterator_t = typename T::iterator;
  2702. template<typename T, typename... Args>
  2703. using to_json_function = decltype(T::to_json(std::declval<Args>()...));
  2704. template<typename T, typename... Args>
  2705. using from_json_function = decltype(T::from_json(std::declval<Args>()...));
  2706. template<typename T, typename U>
  2707. using get_template_function = decltype(std::declval<T>().template get<U>());
  2708. // trait checking if JSONSerializer<T>::from_json(json const&, udt&) exists
  2709. template<typename BasicJsonType, typename T, typename = void>
  2710. struct has_from_json : std::false_type {};
  2711. // trait checking if j.get<T> is valid
  2712. // use this trait instead of std::is_constructible or std::is_convertible,
  2713. // both rely on, or make use of implicit conversions, and thus fail when T
  2714. // has several constructors/operator= (see https://github.com/nlohmann/json/issues/958)
  2715. template <typename BasicJsonType, typename T>
  2716. struct is_getable
  2717. {
  2718. static constexpr bool value = is_detected<get_template_function, const BasicJsonType&, T>::value;
  2719. };
  2720. template<typename BasicJsonType, typename T>
  2721. struct has_from_json < BasicJsonType, T,
  2722. enable_if_t < !is_basic_json<T>::value >>
  2723. {
  2724. using serializer = typename BasicJsonType::template json_serializer<T, void>;
  2725. static constexpr bool value =
  2726. is_detected_exact<void, from_json_function, serializer,
  2727. const BasicJsonType&, T&>::value;
  2728. };
  2729. // This trait checks if JSONSerializer<T>::from_json(json const&) exists
  2730. // this overload is used for non-default-constructible user-defined-types
  2731. template<typename BasicJsonType, typename T, typename = void>
  2732. struct has_non_default_from_json : std::false_type {};
  2733. template<typename BasicJsonType, typename T>
  2734. struct has_non_default_from_json < BasicJsonType, T, enable_if_t < !is_basic_json<T>::value >>
  2735. {
  2736. using serializer = typename BasicJsonType::template json_serializer<T, void>;
  2737. static constexpr bool value =
  2738. is_detected_exact<T, from_json_function, serializer,
  2739. const BasicJsonType&>::value;
  2740. };
  2741. // This trait checks if BasicJsonType::json_serializer<T>::to_json exists
  2742. // Do not evaluate the trait when T is a basic_json type, to avoid template instantiation infinite recursion.
  2743. template<typename BasicJsonType, typename T, typename = void>
  2744. struct has_to_json : std::false_type {};
  2745. template<typename BasicJsonType, typename T>
  2746. struct has_to_json < BasicJsonType, T, enable_if_t < !is_basic_json<T>::value >>
  2747. {
  2748. using serializer = typename BasicJsonType::template json_serializer<T, void>;
  2749. static constexpr bool value =
  2750. is_detected_exact<void, to_json_function, serializer, BasicJsonType&,
  2751. T>::value;
  2752. };
  2753. ///////////////////
  2754. // is_ functions //
  2755. ///////////////////
  2756. template<typename T, typename = void>
  2757. struct is_iterator_traits : std::false_type {};
  2758. template<typename T>
  2759. struct is_iterator_traits<iterator_traits<T>>
  2760. {
  2761. private:
  2762. using traits = iterator_traits<T>;
  2763. public:
  2764. static constexpr auto value =
  2765. is_detected<value_type_t, traits>::value &&
  2766. is_detected<difference_type_t, traits>::value &&
  2767. is_detected<pointer_t, traits>::value &&
  2768. is_detected<iterator_category_t, traits>::value &&
  2769. is_detected<reference_t, traits>::value;
  2770. };
  2771. // source: https://stackoverflow.com/a/37193089/4116453
  2772. template<typename T, typename = void>
  2773. struct is_complete_type : std::false_type {};
  2774. template<typename T>
  2775. struct is_complete_type<T, decltype(void(sizeof(T)))> : std::true_type {};
  2776. template<typename BasicJsonType, typename CompatibleObjectType,
  2777. typename = void>
  2778. struct is_compatible_object_type_impl : std::false_type {};
  2779. template<typename BasicJsonType, typename CompatibleObjectType>
  2780. struct is_compatible_object_type_impl <
  2781. BasicJsonType, CompatibleObjectType,
  2782. enable_if_t < is_detected<mapped_type_t, CompatibleObjectType>::value&&
  2783. is_detected<key_type_t, CompatibleObjectType>::value >>
  2784. {
  2785. using object_t = typename BasicJsonType::object_t;
  2786. // macOS's is_constructible does not play well with nonesuch...
  2787. static constexpr bool value =
  2788. std::is_constructible<typename object_t::key_type,
  2789. typename CompatibleObjectType::key_type>::value &&
  2790. std::is_constructible<typename object_t::mapped_type,
  2791. typename CompatibleObjectType::mapped_type>::value;
  2792. };
  2793. template<typename BasicJsonType, typename CompatibleObjectType>
  2794. struct is_compatible_object_type
  2795. : is_compatible_object_type_impl<BasicJsonType, CompatibleObjectType> {};
  2796. template<typename BasicJsonType, typename ConstructibleObjectType,
  2797. typename = void>
  2798. struct is_constructible_object_type_impl : std::false_type {};
  2799. template<typename BasicJsonType, typename ConstructibleObjectType>
  2800. struct is_constructible_object_type_impl <
  2801. BasicJsonType, ConstructibleObjectType,
  2802. enable_if_t < is_detected<mapped_type_t, ConstructibleObjectType>::value&&
  2803. is_detected<key_type_t, ConstructibleObjectType>::value >>
  2804. {
  2805. using object_t = typename BasicJsonType::object_t;
  2806. static constexpr bool value =
  2807. (std::is_default_constructible<ConstructibleObjectType>::value &&
  2808. (std::is_move_assignable<ConstructibleObjectType>::value ||
  2809. std::is_copy_assignable<ConstructibleObjectType>::value) &&
  2810. (std::is_constructible<typename ConstructibleObjectType::key_type,
  2811. typename object_t::key_type>::value &&
  2812. std::is_same <
  2813. typename object_t::mapped_type,
  2814. typename ConstructibleObjectType::mapped_type >::value)) ||
  2815. (has_from_json<BasicJsonType,
  2816. typename ConstructibleObjectType::mapped_type>::value ||
  2817. has_non_default_from_json <
  2818. BasicJsonType,
  2819. typename ConstructibleObjectType::mapped_type >::value);
  2820. };
  2821. template<typename BasicJsonType, typename ConstructibleObjectType>
  2822. struct is_constructible_object_type
  2823. : is_constructible_object_type_impl<BasicJsonType,
  2824. ConstructibleObjectType> {};
  2825. template<typename BasicJsonType, typename CompatibleStringType,
  2826. typename = void>
  2827. struct is_compatible_string_type_impl : std::false_type {};
  2828. template<typename BasicJsonType, typename CompatibleStringType>
  2829. struct is_compatible_string_type_impl <
  2830. BasicJsonType, CompatibleStringType,
  2831. enable_if_t<is_detected_exact<typename BasicJsonType::string_t::value_type,
  2832. value_type_t, CompatibleStringType>::value >>
  2833. {
  2834. static constexpr auto value =
  2835. std::is_constructible<typename BasicJsonType::string_t, CompatibleStringType>::value;
  2836. };
  2837. template<typename BasicJsonType, typename ConstructibleStringType>
  2838. struct is_compatible_string_type
  2839. : is_compatible_string_type_impl<BasicJsonType, ConstructibleStringType> {};
  2840. template<typename BasicJsonType, typename ConstructibleStringType,
  2841. typename = void>
  2842. struct is_constructible_string_type_impl : std::false_type {};
  2843. template<typename BasicJsonType, typename ConstructibleStringType>
  2844. struct is_constructible_string_type_impl <
  2845. BasicJsonType, ConstructibleStringType,
  2846. enable_if_t<is_detected_exact<typename BasicJsonType::string_t::value_type,
  2847. value_type_t, ConstructibleStringType>::value >>
  2848. {
  2849. static constexpr auto value =
  2850. std::is_constructible<ConstructibleStringType,
  2851. typename BasicJsonType::string_t>::value;
  2852. };
  2853. template<typename BasicJsonType, typename ConstructibleStringType>
  2854. struct is_constructible_string_type
  2855. : is_constructible_string_type_impl<BasicJsonType, ConstructibleStringType> {};
  2856. template<typename BasicJsonType, typename CompatibleArrayType, typename = void>
  2857. struct is_compatible_array_type_impl : std::false_type {};
  2858. template<typename BasicJsonType, typename CompatibleArrayType>
  2859. struct is_compatible_array_type_impl <
  2860. BasicJsonType, CompatibleArrayType,
  2861. enable_if_t < is_detected<value_type_t, CompatibleArrayType>::value&&
  2862. is_detected<iterator_t, CompatibleArrayType>::value&&
  2863. // This is needed because json_reverse_iterator has a ::iterator type...
  2864. // Therefore it is detected as a CompatibleArrayType.
  2865. // The real fix would be to have an Iterable concept.
  2866. !is_iterator_traits <
  2867. iterator_traits<CompatibleArrayType >>::value >>
  2868. {
  2869. static constexpr bool value =
  2870. std::is_constructible<BasicJsonType,
  2871. typename CompatibleArrayType::value_type>::value;
  2872. };
  2873. template<typename BasicJsonType, typename CompatibleArrayType>
  2874. struct is_compatible_array_type
  2875. : is_compatible_array_type_impl<BasicJsonType, CompatibleArrayType> {};
  2876. template<typename BasicJsonType, typename ConstructibleArrayType, typename = void>
  2877. struct is_constructible_array_type_impl : std::false_type {};
  2878. template<typename BasicJsonType, typename ConstructibleArrayType>
  2879. struct is_constructible_array_type_impl <
  2880. BasicJsonType, ConstructibleArrayType,
  2881. enable_if_t<std::is_same<ConstructibleArrayType,
  2882. typename BasicJsonType::value_type>::value >>
  2883. : std::true_type {};
  2884. template<typename BasicJsonType, typename ConstructibleArrayType>
  2885. struct is_constructible_array_type_impl <
  2886. BasicJsonType, ConstructibleArrayType,
  2887. enable_if_t < !std::is_same<ConstructibleArrayType,
  2888. typename BasicJsonType::value_type>::value&&
  2889. std::is_default_constructible<ConstructibleArrayType>::value&&
  2890. (std::is_move_assignable<ConstructibleArrayType>::value ||
  2891. std::is_copy_assignable<ConstructibleArrayType>::value)&&
  2892. is_detected<value_type_t, ConstructibleArrayType>::value&&
  2893. is_detected<iterator_t, ConstructibleArrayType>::value&&
  2894. is_complete_type <
  2895. detected_t<value_type_t, ConstructibleArrayType >>::value >>
  2896. {
  2897. static constexpr bool value =
  2898. // This is needed because json_reverse_iterator has a ::iterator type,
  2899. // furthermore, std::back_insert_iterator (and other iterators) have a
  2900. // base class `iterator`... Therefore it is detected as a
  2901. // ConstructibleArrayType. The real fix would be to have an Iterable
  2902. // concept.
  2903. !is_iterator_traits<iterator_traits<ConstructibleArrayType>>::value &&
  2904. (std::is_same<typename ConstructibleArrayType::value_type,
  2905. typename BasicJsonType::array_t::value_type>::value ||
  2906. has_from_json<BasicJsonType,
  2907. typename ConstructibleArrayType::value_type>::value ||
  2908. has_non_default_from_json <
  2909. BasicJsonType, typename ConstructibleArrayType::value_type >::value);
  2910. };
  2911. template<typename BasicJsonType, typename ConstructibleArrayType>
  2912. struct is_constructible_array_type
  2913. : is_constructible_array_type_impl<BasicJsonType, ConstructibleArrayType> {};
  2914. template<typename RealIntegerType, typename CompatibleNumberIntegerType,
  2915. typename = void>
  2916. struct is_compatible_integer_type_impl : std::false_type {};
  2917. template<typename RealIntegerType, typename CompatibleNumberIntegerType>
  2918. struct is_compatible_integer_type_impl <
  2919. RealIntegerType, CompatibleNumberIntegerType,
  2920. enable_if_t < std::is_integral<RealIntegerType>::value&&
  2921. std::is_integral<CompatibleNumberIntegerType>::value&&
  2922. !std::is_same<bool, CompatibleNumberIntegerType>::value >>
  2923. {
  2924. // is there an assert somewhere on overflows?
  2925. using RealLimits = std::numeric_limits<RealIntegerType>;
  2926. using CompatibleLimits = std::numeric_limits<CompatibleNumberIntegerType>;
  2927. static constexpr auto value =
  2928. std::is_constructible<RealIntegerType,
  2929. CompatibleNumberIntegerType>::value &&
  2930. CompatibleLimits::is_integer &&
  2931. RealLimits::is_signed == CompatibleLimits::is_signed;
  2932. };
  2933. template<typename RealIntegerType, typename CompatibleNumberIntegerType>
  2934. struct is_compatible_integer_type
  2935. : is_compatible_integer_type_impl<RealIntegerType,
  2936. CompatibleNumberIntegerType> {};
  2937. template<typename BasicJsonType, typename CompatibleType, typename = void>
  2938. struct is_compatible_type_impl: std::false_type {};
  2939. template<typename BasicJsonType, typename CompatibleType>
  2940. struct is_compatible_type_impl <
  2941. BasicJsonType, CompatibleType,
  2942. enable_if_t<is_complete_type<CompatibleType>::value >>
  2943. {
  2944. static constexpr bool value =
  2945. has_to_json<BasicJsonType, CompatibleType>::value;
  2946. };
  2947. template<typename BasicJsonType, typename CompatibleType>
  2948. struct is_compatible_type
  2949. : is_compatible_type_impl<BasicJsonType, CompatibleType> {};
  2950. // https://en.cppreference.com/w/cpp/types/conjunction
  2951. template<class...> struct conjunction : std::true_type { };
  2952. template<class B1> struct conjunction<B1> : B1 { };
  2953. template<class B1, class... Bn>
  2954. struct conjunction<B1, Bn...>
  2955. : std::conditional<bool(B1::value), conjunction<Bn...>, B1>::type {};
  2956. template<typename T1, typename T2>
  2957. struct is_constructible_tuple : std::false_type {};
  2958. template<typename T1, typename... Args>
  2959. struct is_constructible_tuple<T1, std::tuple<Args...>> : conjunction<std::is_constructible<T1, Args>...> {};
  2960. } // namespace detail
  2961. } // namespace nlohmann
  2962. // #include <nlohmann/detail/value_t.hpp>
  2963. #include <array> // array
  2964. #include <cstddef> // size_t
  2965. #include <cstdint> // uint8_t
  2966. #include <string> // string
  2967. namespace nlohmann
  2968. {
  2969. namespace detail
  2970. {
  2971. ///////////////////////////
  2972. // JSON type enumeration //
  2973. ///////////////////////////
  2974. /*!
  2975. @brief the JSON type enumeration
  2976. This enumeration collects the different JSON types. It is internally used to
  2977. distinguish the stored values, and the functions @ref basic_json::is_null(),
  2978. @ref basic_json::is_object(), @ref basic_json::is_array(),
  2979. @ref basic_json::is_string(), @ref basic_json::is_boolean(),
  2980. @ref basic_json::is_number() (with @ref basic_json::is_number_integer(),
  2981. @ref basic_json::is_number_unsigned(), and @ref basic_json::is_number_float()),
  2982. @ref basic_json::is_discarded(), @ref basic_json::is_primitive(), and
  2983. @ref basic_json::is_structured() rely on it.
  2984. @note There are three enumeration entries (number_integer, number_unsigned, and
  2985. number_float), because the library distinguishes these three types for numbers:
  2986. @ref basic_json::number_unsigned_t is used for unsigned integers,
  2987. @ref basic_json::number_integer_t is used for signed integers, and
  2988. @ref basic_json::number_float_t is used for floating-point numbers or to
  2989. approximate integers which do not fit in the limits of their respective type.
  2990. @sa @ref basic_json::basic_json(const value_t value_type) -- create a JSON
  2991. value with the default value for a given type
  2992. @since version 1.0.0
  2993. */
  2994. enum class value_t : std::uint8_t
  2995. {
  2996. null, ///< null value
  2997. object, ///< object (unordered set of name/value pairs)
  2998. array, ///< array (ordered collection of values)
  2999. string, ///< string value
  3000. boolean, ///< boolean value
  3001. number_integer, ///< number value (signed integer)
  3002. number_unsigned, ///< number value (unsigned integer)
  3003. number_float, ///< number value (floating-point)
  3004. binary, ///< binary array (ordered collection of bytes)
  3005. discarded ///< discarded by the parser callback function
  3006. };
  3007. /*!
  3008. @brief comparison operator for JSON types
  3009. Returns an ordering that is similar to Python:
  3010. - order: null < boolean < number < object < array < string < binary
  3011. - furthermore, each type is not smaller than itself
  3012. - discarded values are not comparable
  3013. - binary is represented as a b"" string in python and directly comparable to a
  3014. string; however, making a binary array directly comparable with a string would
  3015. be surprising behavior in a JSON file.
  3016. @since version 1.0.0
  3017. */
  3018. inline bool operator<(const value_t lhs, const value_t rhs) noexcept
  3019. {
  3020. static constexpr std::array<std::uint8_t, 9> order = {{
  3021. 0 /* null */, 3 /* object */, 4 /* array */, 5 /* string */,
  3022. 1 /* boolean */, 2 /* integer */, 2 /* unsigned */, 2 /* float */,
  3023. 6 /* binary */
  3024. }
  3025. };
  3026. const auto l_index = static_cast<std::size_t>(lhs);
  3027. const auto r_index = static_cast<std::size_t>(rhs);
  3028. return l_index < order.size() && r_index < order.size() && order[l_index] < order[r_index];
  3029. }
  3030. } // namespace detail
  3031. } // namespace nlohmann
  3032. namespace nlohmann
  3033. {
  3034. namespace detail
  3035. {
  3036. template<typename BasicJsonType>
  3037. void from_json(const BasicJsonType& j, typename std::nullptr_t& n)
  3038. {
  3039. if (JSON_HEDLEY_UNLIKELY(!j.is_null()))
  3040. {
  3041. JSON_THROW(type_error::create(302, "type must be null, but is " + std::string(j.type_name())));
  3042. }
  3043. n = nullptr;
  3044. }
  3045. // overloads for basic_json template parameters
  3046. template < typename BasicJsonType, typename ArithmeticType,
  3047. enable_if_t < std::is_arithmetic<ArithmeticType>::value&&
  3048. !std::is_same<ArithmeticType, typename BasicJsonType::boolean_t>::value,
  3049. int > = 0 >
  3050. void get_arithmetic_value(const BasicJsonType& j, ArithmeticType& val)
  3051. {
  3052. switch (static_cast<value_t>(j))
  3053. {
  3054. case value_t::number_unsigned:
  3055. {
  3056. val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::number_unsigned_t*>());
  3057. break;
  3058. }
  3059. case value_t::number_integer:
  3060. {
  3061. val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::number_integer_t*>());
  3062. break;
  3063. }
  3064. case value_t::number_float:
  3065. {
  3066. val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::number_float_t*>());
  3067. break;
  3068. }
  3069. default:
  3070. JSON_THROW(type_error::create(302, "type must be number, but is " + std::string(j.type_name())));
  3071. }
  3072. }
  3073. template<typename BasicJsonType>
  3074. void from_json(const BasicJsonType& j, typename BasicJsonType::boolean_t& b)
  3075. {
  3076. if (JSON_HEDLEY_UNLIKELY(!j.is_boolean()))
  3077. {
  3078. JSON_THROW(type_error::create(302, "type must be boolean, but is " + std::string(j.type_name())));
  3079. }
  3080. b = *j.template get_ptr<const typename BasicJsonType::boolean_t*>();
  3081. }
  3082. template<typename BasicJsonType>
  3083. void from_json(const BasicJsonType& j, typename BasicJsonType::string_t& s)
  3084. {
  3085. if (JSON_HEDLEY_UNLIKELY(!j.is_string()))
  3086. {
  3087. JSON_THROW(type_error::create(302, "type must be string, but is " + std::string(j.type_name())));
  3088. }
  3089. s = *j.template get_ptr<const typename BasicJsonType::string_t*>();
  3090. }
  3091. template <
  3092. typename BasicJsonType, typename ConstructibleStringType,
  3093. enable_if_t <
  3094. is_constructible_string_type<BasicJsonType, ConstructibleStringType>::value&&
  3095. !std::is_same<typename BasicJsonType::string_t,
  3096. ConstructibleStringType>::value,
  3097. int > = 0 >
  3098. void from_json(const BasicJsonType& j, ConstructibleStringType& s)
  3099. {
  3100. if (JSON_HEDLEY_UNLIKELY(!j.is_string()))
  3101. {
  3102. JSON_THROW(type_error::create(302, "type must be string, but is " + std::string(j.type_name())));
  3103. }
  3104. s = *j.template get_ptr<const typename BasicJsonType::string_t*>();
  3105. }
  3106. template<typename BasicJsonType>
  3107. void from_json(const BasicJsonType& j, typename BasicJsonType::number_float_t& val)
  3108. {
  3109. get_arithmetic_value(j, val);
  3110. }
  3111. template<typename BasicJsonType>
  3112. void from_json(const BasicJsonType& j, typename BasicJsonType::number_unsigned_t& val)
  3113. {
  3114. get_arithmetic_value(j, val);
  3115. }
  3116. template<typename BasicJsonType>
  3117. void from_json(const BasicJsonType& j, typename BasicJsonType::number_integer_t& val)
  3118. {
  3119. get_arithmetic_value(j, val);
  3120. }
  3121. template<typename BasicJsonType, typename EnumType,
  3122. enable_if_t<std::is_enum<EnumType>::value, int> = 0>
  3123. void from_json(const BasicJsonType& j, EnumType& e)
  3124. {
  3125. typename std::underlying_type<EnumType>::type val;
  3126. get_arithmetic_value(j, val);
  3127. e = static_cast<EnumType>(val);
  3128. }
  3129. // forward_list doesn't have an insert method
  3130. template<typename BasicJsonType, typename T, typename Allocator,
  3131. enable_if_t<is_getable<BasicJsonType, T>::value, int> = 0>
  3132. void from_json(const BasicJsonType& j, std::forward_list<T, Allocator>& l)
  3133. {
  3134. if (JSON_HEDLEY_UNLIKELY(!j.is_array()))
  3135. {
  3136. JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(j.type_name())));
  3137. }
  3138. l.clear();
  3139. std::transform(j.rbegin(), j.rend(),
  3140. std::front_inserter(l), [](const BasicJsonType & i)
  3141. {
  3142. return i.template get<T>();
  3143. });
  3144. }
  3145. // valarray doesn't have an insert method
  3146. template<typename BasicJsonType, typename T,
  3147. enable_if_t<is_getable<BasicJsonType, T>::value, int> = 0>
  3148. void from_json(const BasicJsonType& j, std::valarray<T>& l)
  3149. {
  3150. if (JSON_HEDLEY_UNLIKELY(!j.is_array()))
  3151. {
  3152. JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(j.type_name())));
  3153. }
  3154. l.resize(j.size());
  3155. std::transform(j.begin(), j.end(), std::begin(l),
  3156. [](const BasicJsonType & elem)
  3157. {
  3158. return elem.template get<T>();
  3159. });
  3160. }
  3161. template<typename BasicJsonType, typename T, std::size_t N>
  3162. auto from_json(const BasicJsonType& j, T (&arr)[N])
  3163. -> decltype(j.template get<T>(), void())
  3164. {
  3165. for (std::size_t i = 0; i < N; ++i)
  3166. {
  3167. arr[i] = j.at(i).template get<T>();
  3168. }
  3169. }
  3170. template<typename BasicJsonType>
  3171. void from_json_array_impl(const BasicJsonType& j, typename BasicJsonType::array_t& arr, priority_tag<3> /*unused*/)
  3172. {
  3173. arr = *j.template get_ptr<const typename BasicJsonType::array_t*>();
  3174. }
  3175. template<typename BasicJsonType, typename T, std::size_t N>
  3176. auto from_json_array_impl(const BasicJsonType& j, std::array<T, N>& arr,
  3177. priority_tag<2> /*unused*/)
  3178. -> decltype(j.template get<T>(), void())
  3179. {
  3180. for (std::size_t i = 0; i < N; ++i)
  3181. {
  3182. arr[i] = j.at(i).template get<T>();
  3183. }
  3184. }
  3185. template<typename BasicJsonType, typename ConstructibleArrayType>
  3186. auto from_json_array_impl(const BasicJsonType& j, ConstructibleArrayType& arr, priority_tag<1> /*unused*/)
  3187. -> decltype(
  3188. arr.reserve(std::declval<typename ConstructibleArrayType::size_type>()),
  3189. j.template get<typename ConstructibleArrayType::value_type>(),
  3190. void())
  3191. {
  3192. using std::end;
  3193. ConstructibleArrayType ret;
  3194. ret.reserve(j.size());
  3195. std::transform(j.begin(), j.end(),
  3196. std::inserter(ret, end(ret)), [](const BasicJsonType & i)
  3197. {
  3198. // get<BasicJsonType>() returns *this, this won't call a from_json
  3199. // method when value_type is BasicJsonType
  3200. return i.template get<typename ConstructibleArrayType::value_type>();
  3201. });
  3202. arr = std::move(ret);
  3203. }
  3204. template<typename BasicJsonType, typename ConstructibleArrayType>
  3205. void from_json_array_impl(const BasicJsonType& j, ConstructibleArrayType& arr,
  3206. priority_tag<0> /*unused*/)
  3207. {
  3208. using std::end;
  3209. ConstructibleArrayType ret;
  3210. std::transform(
  3211. j.begin(), j.end(), std::inserter(ret, end(ret)),
  3212. [](const BasicJsonType & i)
  3213. {
  3214. // get<BasicJsonType>() returns *this, this won't call a from_json
  3215. // method when value_type is BasicJsonType
  3216. return i.template get<typename ConstructibleArrayType::value_type>();
  3217. });
  3218. arr = std::move(ret);
  3219. }
  3220. template < typename BasicJsonType, typename ConstructibleArrayType,
  3221. enable_if_t <
  3222. is_constructible_array_type<BasicJsonType, ConstructibleArrayType>::value&&
  3223. !is_constructible_object_type<BasicJsonType, ConstructibleArrayType>::value&&
  3224. !is_constructible_string_type<BasicJsonType, ConstructibleArrayType>::value&&
  3225. !std::is_same<ConstructibleArrayType, typename BasicJsonType::binary_t>::value&&
  3226. !is_basic_json<ConstructibleArrayType>::value,
  3227. int > = 0 >
  3228. auto from_json(const BasicJsonType& j, ConstructibleArrayType& arr)
  3229. -> decltype(from_json_array_impl(j, arr, priority_tag<3> {}),
  3230. j.template get<typename ConstructibleArrayType::value_type>(),
  3231. void())
  3232. {
  3233. if (JSON_HEDLEY_UNLIKELY(!j.is_array()))
  3234. {
  3235. JSON_THROW(type_error::create(302, "type must be array, but is " +
  3236. std::string(j.type_name())));
  3237. }
  3238. from_json_array_impl(j, arr, priority_tag<3> {});
  3239. }
  3240. template<typename BasicJsonType>
  3241. void from_json(const BasicJsonType& j, typename BasicJsonType::binary_t& bin)
  3242. {
  3243. if (JSON_HEDLEY_UNLIKELY(!j.is_binary()))
  3244. {
  3245. JSON_THROW(type_error::create(302, "type must be binary, but is " + std::string(j.type_name())));
  3246. }
  3247. bin = *j.template get_ptr<const typename BasicJsonType::binary_t*>();
  3248. }
  3249. template<typename BasicJsonType, typename ConstructibleObjectType,
  3250. enable_if_t<is_constructible_object_type<BasicJsonType, ConstructibleObjectType>::value, int> = 0>
  3251. void from_json(const BasicJsonType& j, ConstructibleObjectType& obj)
  3252. {
  3253. if (JSON_HEDLEY_UNLIKELY(!j.is_object()))
  3254. {
  3255. JSON_THROW(type_error::create(302, "type must be object, but is " + std::string(j.type_name())));
  3256. }
  3257. ConstructibleObjectType ret;
  3258. auto inner_object = j.template get_ptr<const typename BasicJsonType::object_t*>();
  3259. using value_type = typename ConstructibleObjectType::value_type;
  3260. std::transform(
  3261. inner_object->begin(), inner_object->end(),
  3262. std::inserter(ret, ret.begin()),
  3263. [](typename BasicJsonType::object_t::value_type const & p)
  3264. {
  3265. return value_type(p.first, p.second.template get<typename ConstructibleObjectType::mapped_type>());
  3266. });
  3267. obj = std::move(ret);
  3268. }
  3269. // overload for arithmetic types, not chosen for basic_json template arguments
  3270. // (BooleanType, etc..); note: Is it really necessary to provide explicit
  3271. // overloads for boolean_t etc. in case of a custom BooleanType which is not
  3272. // an arithmetic type?
  3273. template < typename BasicJsonType, typename ArithmeticType,
  3274. enable_if_t <
  3275. std::is_arithmetic<ArithmeticType>::value&&
  3276. !std::is_same<ArithmeticType, typename BasicJsonType::number_unsigned_t>::value&&
  3277. !std::is_same<ArithmeticType, typename BasicJsonType::number_integer_t>::value&&
  3278. !std::is_same<ArithmeticType, typename BasicJsonType::number_float_t>::value&&
  3279. !std::is_same<ArithmeticType, typename BasicJsonType::boolean_t>::value,
  3280. int > = 0 >
  3281. void from_json(const BasicJsonType& j, ArithmeticType& val)
  3282. {
  3283. switch (static_cast<value_t>(j))
  3284. {
  3285. case value_t::number_unsigned:
  3286. {
  3287. val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::number_unsigned_t*>());
  3288. break;
  3289. }
  3290. case value_t::number_integer:
  3291. {
  3292. val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::number_integer_t*>());
  3293. break;
  3294. }
  3295. case value_t::number_float:
  3296. {
  3297. val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::number_float_t*>());
  3298. break;
  3299. }
  3300. case value_t::boolean:
  3301. {
  3302. val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::boolean_t*>());
  3303. break;
  3304. }
  3305. default:
  3306. JSON_THROW(type_error::create(302, "type must be number, but is " + std::string(j.type_name())));
  3307. }
  3308. }
  3309. template<typename BasicJsonType, typename A1, typename A2>
  3310. void from_json(const BasicJsonType& j, std::pair<A1, A2>& p)
  3311. {
  3312. p = {j.at(0).template get<A1>(), j.at(1).template get<A2>()};
  3313. }
  3314. template<typename BasicJsonType, typename Tuple, std::size_t... Idx>
  3315. void from_json_tuple_impl(const BasicJsonType& j, Tuple& t, index_sequence<Idx...> /*unused*/)
  3316. {
  3317. t = std::make_tuple(j.at(Idx).template get<typename std::tuple_element<Idx, Tuple>::type>()...);
  3318. }
  3319. template<typename BasicJsonType, typename... Args>
  3320. void from_json(const BasicJsonType& j, std::tuple<Args...>& t)
  3321. {
  3322. from_json_tuple_impl(j, t, index_sequence_for<Args...> {});
  3323. }
  3324. template < typename BasicJsonType, typename Key, typename Value, typename Compare, typename Allocator,
  3325. typename = enable_if_t < !std::is_constructible <
  3326. typename BasicJsonType::string_t, Key >::value >>
  3327. void from_json(const BasicJsonType& j, std::map<Key, Value, Compare, Allocator>& m)
  3328. {
  3329. if (JSON_HEDLEY_UNLIKELY(!j.is_array()))
  3330. {
  3331. JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(j.type_name())));
  3332. }
  3333. m.clear();
  3334. for (const auto& p : j)
  3335. {
  3336. if (JSON_HEDLEY_UNLIKELY(!p.is_array()))
  3337. {
  3338. JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(p.type_name())));
  3339. }
  3340. m.emplace(p.at(0).template get<Key>(), p.at(1).template get<Value>());
  3341. }
  3342. }
  3343. template < typename BasicJsonType, typename Key, typename Value, typename Hash, typename KeyEqual, typename Allocator,
  3344. typename = enable_if_t < !std::is_constructible <
  3345. typename BasicJsonType::string_t, Key >::value >>
  3346. void from_json(const BasicJsonType& j, std::unordered_map<Key, Value, Hash, KeyEqual, Allocator>& m)
  3347. {
  3348. if (JSON_HEDLEY_UNLIKELY(!j.is_array()))
  3349. {
  3350. JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(j.type_name())));
  3351. }
  3352. m.clear();
  3353. for (const auto& p : j)
  3354. {
  3355. if (JSON_HEDLEY_UNLIKELY(!p.is_array()))
  3356. {
  3357. JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(p.type_name())));
  3358. }
  3359. m.emplace(p.at(0).template get<Key>(), p.at(1).template get<Value>());
  3360. }
  3361. }
  3362. struct from_json_fn
  3363. {
  3364. template<typename BasicJsonType, typename T>
  3365. auto operator()(const BasicJsonType& j, T& val) const
  3366. noexcept(noexcept(from_json(j, val)))
  3367. -> decltype(from_json(j, val), void())
  3368. {
  3369. return from_json(j, val);
  3370. }
  3371. };
  3372. } // namespace detail
  3373. /// namespace to hold default `from_json` function
  3374. /// to see why this is required:
  3375. /// http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2015/n4381.html
  3376. namespace
  3377. {
  3378. constexpr const auto& from_json = detail::static_const<detail::from_json_fn>::value;
  3379. } // namespace
  3380. } // namespace nlohmann
  3381. // #include <nlohmann/detail/conversions/to_json.hpp>
  3382. #include <algorithm> // copy
  3383. #include <iterator> // begin, end
  3384. #include <string> // string
  3385. #include <tuple> // tuple, get
  3386. #include <type_traits> // is_same, is_constructible, is_floating_point, is_enum, underlying_type
  3387. #include <utility> // move, forward, declval, pair
  3388. #include <valarray> // valarray
  3389. #include <vector> // vector
  3390. // #include <nlohmann/detail/iterators/iteration_proxy.hpp>
  3391. #include <cstddef> // size_t
  3392. #include <iterator> // input_iterator_tag
  3393. #include <string> // string, to_string
  3394. #include <tuple> // tuple_size, get, tuple_element
  3395. // #include <nlohmann/detail/meta/type_traits.hpp>
  3396. // #include <nlohmann/detail/value_t.hpp>
  3397. namespace nlohmann
  3398. {
  3399. namespace detail
  3400. {
  3401. template<typename string_type>
  3402. void int_to_string( string_type& target, std::size_t value )
  3403. {
  3404. // For ADL
  3405. using std::to_string;
  3406. target = to_string(value);
  3407. }
  3408. template<typename IteratorType> class iteration_proxy_value
  3409. {
  3410. public:
  3411. using difference_type = std::ptrdiff_t;
  3412. using value_type = iteration_proxy_value;
  3413. using pointer = value_type * ;
  3414. using reference = value_type & ;
  3415. using iterator_category = std::input_iterator_tag;
  3416. using string_type = typename std::remove_cv< typename std::remove_reference<decltype( std::declval<IteratorType>().key() ) >::type >::type;
  3417. private:
  3418. /// the iterator
  3419. IteratorType anchor;
  3420. /// an index for arrays (used to create key names)
  3421. std::size_t array_index = 0;
  3422. /// last stringified array index
  3423. mutable std::size_t array_index_last = 0;
  3424. /// a string representation of the array index
  3425. mutable string_type array_index_str = "0";
  3426. /// an empty string (to return a reference for primitive values)
  3427. const string_type empty_str = "";
  3428. public:
  3429. explicit iteration_proxy_value(IteratorType it) noexcept : anchor(it) {}
  3430. /// dereference operator (needed for range-based for)
  3431. iteration_proxy_value& operator*()
  3432. {
  3433. return *this;
  3434. }
  3435. /// increment operator (needed for range-based for)
  3436. iteration_proxy_value& operator++()
  3437. {
  3438. ++anchor;
  3439. ++array_index;
  3440. return *this;
  3441. }
  3442. /// equality operator (needed for InputIterator)
  3443. bool operator==(const iteration_proxy_value& o) const
  3444. {
  3445. return anchor == o.anchor;
  3446. }
  3447. /// inequality operator (needed for range-based for)
  3448. bool operator!=(const iteration_proxy_value& o) const
  3449. {
  3450. return anchor != o.anchor;
  3451. }
  3452. /// return key of the iterator
  3453. const string_type& key() const
  3454. {
  3455. JSON_ASSERT(anchor.m_object != nullptr);
  3456. switch (anchor.m_object->type())
  3457. {
  3458. // use integer array index as key
  3459. case value_t::array:
  3460. {
  3461. if (array_index != array_index_last)
  3462. {
  3463. int_to_string( array_index_str, array_index );
  3464. array_index_last = array_index;
  3465. }
  3466. return array_index_str;
  3467. }
  3468. // use key from the object
  3469. case value_t::object:
  3470. return anchor.key();
  3471. // use an empty key for all primitive types
  3472. default:
  3473. return empty_str;
  3474. }
  3475. }
  3476. /// return value of the iterator
  3477. typename IteratorType::reference value() const
  3478. {
  3479. return anchor.value();
  3480. }
  3481. };
  3482. /// proxy class for the items() function
  3483. template<typename IteratorType> class iteration_proxy
  3484. {
  3485. private:
  3486. /// the container to iterate
  3487. typename IteratorType::reference container;
  3488. public:
  3489. /// construct iteration proxy from a container
  3490. explicit iteration_proxy(typename IteratorType::reference cont) noexcept
  3491. : container(cont) {}
  3492. /// return iterator begin (needed for range-based for)
  3493. iteration_proxy_value<IteratorType> begin() noexcept
  3494. {
  3495. return iteration_proxy_value<IteratorType>(container.begin());
  3496. }
  3497. /// return iterator end (needed for range-based for)
  3498. iteration_proxy_value<IteratorType> end() noexcept
  3499. {
  3500. return iteration_proxy_value<IteratorType>(container.end());
  3501. }
  3502. };
  3503. // Structured Bindings Support
  3504. // For further reference see https://blog.tartanllama.xyz/structured-bindings/
  3505. // And see https://github.com/nlohmann/json/pull/1391
  3506. template<std::size_t N, typename IteratorType, enable_if_t<N == 0, int> = 0>
  3507. auto get(const nlohmann::detail::iteration_proxy_value<IteratorType>& i) -> decltype(i.key())
  3508. {
  3509. return i.key();
  3510. }
  3511. // Structured Bindings Support
  3512. // For further reference see https://blog.tartanllama.xyz/structured-bindings/
  3513. // And see https://github.com/nlohmann/json/pull/1391
  3514. template<std::size_t N, typename IteratorType, enable_if_t<N == 1, int> = 0>
  3515. auto get(const nlohmann::detail::iteration_proxy_value<IteratorType>& i) -> decltype(i.value())
  3516. {
  3517. return i.value();
  3518. }
  3519. } // namespace detail
  3520. } // namespace nlohmann
  3521. // The Addition to the STD Namespace is required to add
  3522. // Structured Bindings Support to the iteration_proxy_value class
  3523. // For further reference see https://blog.tartanllama.xyz/structured-bindings/
  3524. // And see https://github.com/nlohmann/json/pull/1391
  3525. namespace std
  3526. {
  3527. #if defined(__clang__)
  3528. // Fix: https://github.com/nlohmann/json/issues/1401
  3529. #pragma clang diagnostic push
  3530. #pragma clang diagnostic ignored "-Wmismatched-tags"
  3531. #endif
  3532. template<typename IteratorType>
  3533. class tuple_size<::nlohmann::detail::iteration_proxy_value<IteratorType>>
  3534. : public std::integral_constant<std::size_t, 2> {};
  3535. template<std::size_t N, typename IteratorType>
  3536. class tuple_element<N, ::nlohmann::detail::iteration_proxy_value<IteratorType >>
  3537. {
  3538. public:
  3539. using type = decltype(
  3540. get<N>(std::declval <
  3541. ::nlohmann::detail::iteration_proxy_value<IteratorType >> ()));
  3542. };
  3543. #if defined(__clang__)
  3544. #pragma clang diagnostic pop
  3545. #endif
  3546. } // namespace std
  3547. // #include <nlohmann/detail/meta/cpp_future.hpp>
  3548. // #include <nlohmann/detail/meta/type_traits.hpp>
  3549. // #include <nlohmann/detail/value_t.hpp>
  3550. namespace nlohmann
  3551. {
  3552. namespace detail
  3553. {
  3554. //////////////////
  3555. // constructors //
  3556. //////////////////
  3557. template<value_t> struct external_constructor;
  3558. template<>
  3559. struct external_constructor<value_t::boolean>
  3560. {
  3561. template<typename BasicJsonType>
  3562. static void construct(BasicJsonType& j, typename BasicJsonType::boolean_t b) noexcept
  3563. {
  3564. j.m_type = value_t::boolean;
  3565. j.m_value = b;
  3566. j.assert_invariant();
  3567. }
  3568. };
  3569. template<>
  3570. struct external_constructor<value_t::string>
  3571. {
  3572. template<typename BasicJsonType>
  3573. static void construct(BasicJsonType& j, const typename BasicJsonType::string_t& s)
  3574. {
  3575. j.m_type = value_t::string;
  3576. j.m_value = s;
  3577. j.assert_invariant();
  3578. }
  3579. template<typename BasicJsonType>
  3580. static void construct(BasicJsonType& j, typename BasicJsonType::string_t&& s)
  3581. {
  3582. j.m_type = value_t::string;
  3583. j.m_value = std::move(s);
  3584. j.assert_invariant();
  3585. }
  3586. template < typename BasicJsonType, typename CompatibleStringType,
  3587. enable_if_t < !std::is_same<CompatibleStringType, typename BasicJsonType::string_t>::value,
  3588. int > = 0 >
  3589. static void construct(BasicJsonType& j, const CompatibleStringType& str)
  3590. {
  3591. j.m_type = value_t::string;
  3592. j.m_value.string = j.template create<typename BasicJsonType::string_t>(str);
  3593. j.assert_invariant();
  3594. }
  3595. };
  3596. template<>
  3597. struct external_constructor<value_t::binary>
  3598. {
  3599. template<typename BasicJsonType>
  3600. static void construct(BasicJsonType& j, const typename BasicJsonType::binary_t& b)
  3601. {
  3602. j.m_type = value_t::binary;
  3603. typename BasicJsonType::binary_t value{b};
  3604. j.m_value = value;
  3605. j.assert_invariant();
  3606. }
  3607. template<typename BasicJsonType>
  3608. static void construct(BasicJsonType& j, typename BasicJsonType::binary_t&& b)
  3609. {
  3610. j.m_type = value_t::binary;
  3611. typename BasicJsonType::binary_t value{std::move(b)};
  3612. j.m_value = value;
  3613. j.assert_invariant();
  3614. }
  3615. };
  3616. template<>
  3617. struct external_constructor<value_t::number_float>
  3618. {
  3619. template<typename BasicJsonType>
  3620. static void construct(BasicJsonType& j, typename BasicJsonType::number_float_t val) noexcept
  3621. {
  3622. j.m_type = value_t::number_float;
  3623. j.m_value = val;
  3624. j.assert_invariant();
  3625. }
  3626. };
  3627. template<>
  3628. struct external_constructor<value_t::number_unsigned>
  3629. {
  3630. template<typename BasicJsonType>
  3631. static void construct(BasicJsonType& j, typename BasicJsonType::number_unsigned_t val) noexcept
  3632. {
  3633. j.m_type = value_t::number_unsigned;
  3634. j.m_value = val;
  3635. j.assert_invariant();
  3636. }
  3637. };
  3638. template<>
  3639. struct external_constructor<value_t::number_integer>
  3640. {
  3641. template<typename BasicJsonType>
  3642. static void construct(BasicJsonType& j, typename BasicJsonType::number_integer_t val) noexcept
  3643. {
  3644. j.m_type = value_t::number_integer;
  3645. j.m_value = val;
  3646. j.assert_invariant();
  3647. }
  3648. };
  3649. template<>
  3650. struct external_constructor<value_t::array>
  3651. {
  3652. template<typename BasicJsonType>
  3653. static void construct(BasicJsonType& j, const typename BasicJsonType::array_t& arr)
  3654. {
  3655. j.m_type = value_t::array;
  3656. j.m_value = arr;
  3657. j.assert_invariant();
  3658. }
  3659. template<typename BasicJsonType>
  3660. static void construct(BasicJsonType& j, typename BasicJsonType::array_t&& arr)
  3661. {
  3662. j.m_type = value_t::array;
  3663. j.m_value = std::move(arr);
  3664. j.assert_invariant();
  3665. }
  3666. template < typename BasicJsonType, typename CompatibleArrayType,
  3667. enable_if_t < !std::is_same<CompatibleArrayType, typename BasicJsonType::array_t>::value,
  3668. int > = 0 >
  3669. static void construct(BasicJsonType& j, const CompatibleArrayType& arr)
  3670. {
  3671. using std::begin;
  3672. using std::end;
  3673. j.m_type = value_t::array;
  3674. j.m_value.array = j.template create<typename BasicJsonType::array_t>(begin(arr), end(arr));
  3675. j.assert_invariant();
  3676. }
  3677. template<typename BasicJsonType>
  3678. static void construct(BasicJsonType& j, const std::vector<bool>& arr)
  3679. {
  3680. j.m_type = value_t::array;
  3681. j.m_value = value_t::array;
  3682. j.m_value.array->reserve(arr.size());
  3683. for (const bool x : arr)
  3684. {
  3685. j.m_value.array->push_back(x);
  3686. }
  3687. j.assert_invariant();
  3688. }
  3689. template<typename BasicJsonType, typename T,
  3690. enable_if_t<std::is_convertible<T, BasicJsonType>::value, int> = 0>
  3691. static void construct(BasicJsonType& j, const std::valarray<T>& arr)
  3692. {
  3693. j.m_type = value_t::array;
  3694. j.m_value = value_t::array;
  3695. j.m_value.array->resize(arr.size());
  3696. if (arr.size() > 0)
  3697. {
  3698. std::copy(std::begin(arr), std::end(arr), j.m_value.array->begin());
  3699. }
  3700. j.assert_invariant();
  3701. }
  3702. };
  3703. template<>
  3704. struct external_constructor<value_t::object>
  3705. {
  3706. template<typename BasicJsonType>
  3707. static void construct(BasicJsonType& j, const typename BasicJsonType::object_t& obj)
  3708. {
  3709. j.m_type = value_t::object;
  3710. j.m_value = obj;
  3711. j.assert_invariant();
  3712. }
  3713. template<typename BasicJsonType>
  3714. static void construct(BasicJsonType& j, typename BasicJsonType::object_t&& obj)
  3715. {
  3716. j.m_type = value_t::object;
  3717. j.m_value = std::move(obj);
  3718. j.assert_invariant();
  3719. }
  3720. template < typename BasicJsonType, typename CompatibleObjectType,
  3721. enable_if_t < !std::is_same<CompatibleObjectType, typename BasicJsonType::object_t>::value, int > = 0 >
  3722. static void construct(BasicJsonType& j, const CompatibleObjectType& obj)
  3723. {
  3724. using std::begin;
  3725. using std::end;
  3726. j.m_type = value_t::object;
  3727. j.m_value.object = j.template create<typename BasicJsonType::object_t>(begin(obj), end(obj));
  3728. j.assert_invariant();
  3729. }
  3730. };
  3731. /////////////
  3732. // to_json //
  3733. /////////////
  3734. template<typename BasicJsonType, typename T,
  3735. enable_if_t<std::is_same<T, typename BasicJsonType::boolean_t>::value, int> = 0>
  3736. void to_json(BasicJsonType& j, T b) noexcept
  3737. {
  3738. external_constructor<value_t::boolean>::construct(j, b);
  3739. }
  3740. template<typename BasicJsonType, typename CompatibleString,
  3741. enable_if_t<std::is_constructible<typename BasicJsonType::string_t, CompatibleString>::value, int> = 0>
  3742. void to_json(BasicJsonType& j, const CompatibleString& s)
  3743. {
  3744. external_constructor<value_t::string>::construct(j, s);
  3745. }
  3746. template<typename BasicJsonType>
  3747. void to_json(BasicJsonType& j, typename BasicJsonType::string_t&& s)
  3748. {
  3749. external_constructor<value_t::string>::construct(j, std::move(s));
  3750. }
  3751. template<typename BasicJsonType, typename FloatType,
  3752. enable_if_t<std::is_floating_point<FloatType>::value, int> = 0>
  3753. void to_json(BasicJsonType& j, FloatType val) noexcept
  3754. {
  3755. external_constructor<value_t::number_float>::construct(j, static_cast<typename BasicJsonType::number_float_t>(val));
  3756. }
  3757. template<typename BasicJsonType, typename CompatibleNumberUnsignedType,
  3758. enable_if_t<is_compatible_integer_type<typename BasicJsonType::number_unsigned_t, CompatibleNumberUnsignedType>::value, int> = 0>
  3759. void to_json(BasicJsonType& j, CompatibleNumberUnsignedType val) noexcept
  3760. {
  3761. external_constructor<value_t::number_unsigned>::construct(j, static_cast<typename BasicJsonType::number_unsigned_t>(val));
  3762. }
  3763. template<typename BasicJsonType, typename CompatibleNumberIntegerType,
  3764. enable_if_t<is_compatible_integer_type<typename BasicJsonType::number_integer_t, CompatibleNumberIntegerType>::value, int> = 0>
  3765. void to_json(BasicJsonType& j, CompatibleNumberIntegerType val) noexcept
  3766. {
  3767. external_constructor<value_t::number_integer>::construct(j, static_cast<typename BasicJsonType::number_integer_t>(val));
  3768. }
  3769. template<typename BasicJsonType, typename EnumType,
  3770. enable_if_t<std::is_enum<EnumType>::value, int> = 0>
  3771. void to_json(BasicJsonType& j, EnumType e) noexcept
  3772. {
  3773. using underlying_type = typename std::underlying_type<EnumType>::type;
  3774. external_constructor<value_t::number_integer>::construct(j, static_cast<underlying_type>(e));
  3775. }
  3776. template<typename BasicJsonType>
  3777. void to_json(BasicJsonType& j, const std::vector<bool>& e)
  3778. {
  3779. external_constructor<value_t::array>::construct(j, e);
  3780. }
  3781. template < typename BasicJsonType, typename CompatibleArrayType,
  3782. enable_if_t < is_compatible_array_type<BasicJsonType,
  3783. CompatibleArrayType>::value&&
  3784. !is_compatible_object_type<BasicJsonType, CompatibleArrayType>::value&&
  3785. !is_compatible_string_type<BasicJsonType, CompatibleArrayType>::value&&
  3786. !std::is_same<typename BasicJsonType::binary_t, CompatibleArrayType>::value&&
  3787. !is_basic_json<CompatibleArrayType>::value,
  3788. int > = 0 >
  3789. void to_json(BasicJsonType& j, const CompatibleArrayType& arr)
  3790. {
  3791. external_constructor<value_t::array>::construct(j, arr);
  3792. }
  3793. template<typename BasicJsonType>
  3794. void to_json(BasicJsonType& j, const typename BasicJsonType::binary_t& bin)
  3795. {
  3796. external_constructor<value_t::binary>::construct(j, bin);
  3797. }
  3798. template<typename BasicJsonType, typename T,
  3799. enable_if_t<std::is_convertible<T, BasicJsonType>::value, int> = 0>
  3800. void to_json(BasicJsonType& j, const std::valarray<T>& arr)
  3801. {
  3802. external_constructor<value_t::array>::construct(j, std::move(arr));
  3803. }
  3804. template<typename BasicJsonType>
  3805. void to_json(BasicJsonType& j, typename BasicJsonType::array_t&& arr)
  3806. {
  3807. external_constructor<value_t::array>::construct(j, std::move(arr));
  3808. }
  3809. template < typename BasicJsonType, typename CompatibleObjectType,
  3810. enable_if_t < is_compatible_object_type<BasicJsonType, CompatibleObjectType>::value&& !is_basic_json<CompatibleObjectType>::value, int > = 0 >
  3811. void to_json(BasicJsonType& j, const CompatibleObjectType& obj)
  3812. {
  3813. external_constructor<value_t::object>::construct(j, obj);
  3814. }
  3815. template<typename BasicJsonType>
  3816. void to_json(BasicJsonType& j, typename BasicJsonType::object_t&& obj)
  3817. {
  3818. external_constructor<value_t::object>::construct(j, std::move(obj));
  3819. }
  3820. template <
  3821. typename BasicJsonType, typename T, std::size_t N,
  3822. enable_if_t < !std::is_constructible<typename BasicJsonType::string_t,
  3823. const T(&)[N]>::value,
  3824. int > = 0 >
  3825. void to_json(BasicJsonType& j, const T(&arr)[N])
  3826. {
  3827. external_constructor<value_t::array>::construct(j, arr);
  3828. }
  3829. template < typename BasicJsonType, typename T1, typename T2, enable_if_t < std::is_constructible<BasicJsonType, T1>::value&& std::is_constructible<BasicJsonType, T2>::value, int > = 0 >
  3830. void to_json(BasicJsonType& j, const std::pair<T1, T2>& p)
  3831. {
  3832. j = { p.first, p.second };
  3833. }
  3834. // for https://github.com/nlohmann/json/pull/1134
  3835. template<typename BasicJsonType, typename T,
  3836. enable_if_t<std::is_same<T, iteration_proxy_value<typename BasicJsonType::iterator>>::value, int> = 0>
  3837. void to_json(BasicJsonType& j, const T& b)
  3838. {
  3839. j = { {b.key(), b.value()} };
  3840. }
  3841. template<typename BasicJsonType, typename Tuple, std::size_t... Idx>
  3842. void to_json_tuple_impl(BasicJsonType& j, const Tuple& t, index_sequence<Idx...> /*unused*/)
  3843. {
  3844. j = { std::get<Idx>(t)... };
  3845. }
  3846. template<typename BasicJsonType, typename T, enable_if_t<is_constructible_tuple<BasicJsonType, T>::value, int > = 0>
  3847. void to_json(BasicJsonType& j, const T& t)
  3848. {
  3849. to_json_tuple_impl(j, t, make_index_sequence<std::tuple_size<T>::value> {});
  3850. }
  3851. struct to_json_fn
  3852. {
  3853. template<typename BasicJsonType, typename T>
  3854. auto operator()(BasicJsonType& j, T&& val) const noexcept(noexcept(to_json(j, std::forward<T>(val))))
  3855. -> decltype(to_json(j, std::forward<T>(val)), void())
  3856. {
  3857. return to_json(j, std::forward<T>(val));
  3858. }
  3859. };
  3860. } // namespace detail
  3861. /// namespace to hold default `to_json` function
  3862. namespace
  3863. {
  3864. constexpr const auto& to_json = detail::static_const<detail::to_json_fn>::value;
  3865. } // namespace
  3866. } // namespace nlohmann
  3867. namespace nlohmann
  3868. {
  3869. template<typename, typename>
  3870. struct adl_serializer
  3871. {
  3872. /*!
  3873. @brief convert a JSON value to any value type
  3874. This function is usually called by the `get()` function of the
  3875. @ref basic_json class (either explicit or via conversion operators).
  3876. @param[in] j JSON value to read from
  3877. @param[in,out] val value to write to
  3878. */
  3879. template<typename BasicJsonType, typename ValueType>
  3880. static auto from_json(BasicJsonType&& j, ValueType& val) noexcept(
  3881. noexcept(::nlohmann::from_json(std::forward<BasicJsonType>(j), val)))
  3882. -> decltype(::nlohmann::from_json(std::forward<BasicJsonType>(j), val), void())
  3883. {
  3884. ::nlohmann::from_json(std::forward<BasicJsonType>(j), val);
  3885. }
  3886. /*!
  3887. @brief convert any value type to a JSON value
  3888. This function is usually called by the constructors of the @ref basic_json
  3889. class.
  3890. @param[in,out] j JSON value to write to
  3891. @param[in] val value to read from
  3892. */
  3893. template<typename BasicJsonType, typename ValueType>
  3894. static auto to_json(BasicJsonType& j, ValueType&& val) noexcept(
  3895. noexcept(::nlohmann::to_json(j, std::forward<ValueType>(val))))
  3896. -> decltype(::nlohmann::to_json(j, std::forward<ValueType>(val)), void())
  3897. {
  3898. ::nlohmann::to_json(j, std::forward<ValueType>(val));
  3899. }
  3900. };
  3901. } // namespace nlohmann
  3902. // #include <nlohmann/byte_container_with_subtype.hpp>
  3903. #include <cstdint> // uint8_t
  3904. #include <tuple> // tie
  3905. #include <utility> // move
  3906. namespace nlohmann
  3907. {
  3908. /*!
  3909. @brief an internal type for a backed binary type
  3910. This type extends the template parameter @a BinaryType provided to `basic_json`
  3911. with a subtype used by BSON and MessagePack. This type exists so that the user
  3912. does not have to specify a type themselves with a specific naming scheme in
  3913. order to override the binary type.
  3914. @tparam BinaryType container to store bytes (`std::vector<std::uint8_t>` by
  3915. default)
  3916. @since version 3.8.0
  3917. */
  3918. template<typename BinaryType>
  3919. class byte_container_with_subtype : public BinaryType
  3920. {
  3921. public:
  3922. /// the type of the underlying container
  3923. using container_type = BinaryType;
  3924. byte_container_with_subtype() noexcept(noexcept(container_type()))
  3925. : container_type()
  3926. {}
  3927. byte_container_with_subtype(const container_type& b) noexcept(noexcept(container_type(b)))
  3928. : container_type(b)
  3929. {}
  3930. byte_container_with_subtype(container_type&& b) noexcept(noexcept(container_type(std::move(b))))
  3931. : container_type(std::move(b))
  3932. {}
  3933. byte_container_with_subtype(const container_type& b, std::uint8_t subtype) noexcept(noexcept(container_type(b)))
  3934. : container_type(b)
  3935. , m_subtype(subtype)
  3936. , m_has_subtype(true)
  3937. {}
  3938. byte_container_with_subtype(container_type&& b, std::uint8_t subtype) noexcept(noexcept(container_type(std::move(b))))
  3939. : container_type(std::move(b))
  3940. , m_subtype(subtype)
  3941. , m_has_subtype(true)
  3942. {}
  3943. bool operator==(const byte_container_with_subtype& rhs) const
  3944. {
  3945. return std::tie(static_cast<const BinaryType&>(*this), m_subtype, m_has_subtype) ==
  3946. std::tie(static_cast<const BinaryType&>(rhs), rhs.m_subtype, rhs.m_has_subtype);
  3947. }
  3948. bool operator!=(const byte_container_with_subtype& rhs) const
  3949. {
  3950. return !(rhs == *this);
  3951. }
  3952. /*!
  3953. @brief sets the binary subtype
  3954. Sets the binary subtype of the value, also flags a binary JSON value as
  3955. having a subtype, which has implications for serialization.
  3956. @complexity Constant.
  3957. @exceptionsafety No-throw guarantee: this member function never throws
  3958. exceptions.
  3959. @sa @ref subtype() -- return the binary subtype
  3960. @sa @ref clear_subtype() -- clears the binary subtype
  3961. @sa @ref has_subtype() -- returns whether or not the binary value has a
  3962. subtype
  3963. @since version 3.8.0
  3964. */
  3965. void set_subtype(std::uint8_t subtype) noexcept
  3966. {
  3967. m_subtype = subtype;
  3968. m_has_subtype = true;
  3969. }
  3970. /*!
  3971. @brief return the binary subtype
  3972. Returns the numerical subtype of the value if it has a subtype. If it does
  3973. not have a subtype, this function will return size_t(-1) as a sentinel
  3974. value.
  3975. @return the numerical subtype of the binary value
  3976. @complexity Constant.
  3977. @exceptionsafety No-throw guarantee: this member function never throws
  3978. exceptions.
  3979. @sa @ref set_subtype() -- sets the binary subtype
  3980. @sa @ref clear_subtype() -- clears the binary subtype
  3981. @sa @ref has_subtype() -- returns whether or not the binary value has a
  3982. subtype
  3983. @since version 3.8.0
  3984. */
  3985. constexpr std::uint8_t subtype() const noexcept
  3986. {
  3987. return m_subtype;
  3988. }
  3989. /*!
  3990. @brief return whether the value has a subtype
  3991. @return whether the value has a subtype
  3992. @complexity Constant.
  3993. @exceptionsafety No-throw guarantee: this member function never throws
  3994. exceptions.
  3995. @sa @ref subtype() -- return the binary subtype
  3996. @sa @ref set_subtype() -- sets the binary subtype
  3997. @sa @ref clear_subtype() -- clears the binary subtype
  3998. @since version 3.8.0
  3999. */
  4000. constexpr bool has_subtype() const noexcept
  4001. {
  4002. return m_has_subtype;
  4003. }
  4004. /*!
  4005. @brief clears the binary subtype
  4006. Clears the binary subtype and flags the value as not having a subtype, which
  4007. has implications for serialization; for instance MessagePack will prefer the
  4008. bin family over the ext family.
  4009. @complexity Constant.
  4010. @exceptionsafety No-throw guarantee: this member function never throws
  4011. exceptions.
  4012. @sa @ref subtype() -- return the binary subtype
  4013. @sa @ref set_subtype() -- sets the binary subtype
  4014. @sa @ref has_subtype() -- returns whether or not the binary value has a
  4015. subtype
  4016. @since version 3.8.0
  4017. */
  4018. void clear_subtype() noexcept
  4019. {
  4020. m_subtype = 0;
  4021. m_has_subtype = false;
  4022. }
  4023. private:
  4024. std::uint8_t m_subtype = 0;
  4025. bool m_has_subtype = false;
  4026. };
  4027. } // namespace nlohmann
  4028. // #include <nlohmann/detail/conversions/from_json.hpp>
  4029. // #include <nlohmann/detail/conversions/to_json.hpp>
  4030. // #include <nlohmann/detail/exceptions.hpp>
  4031. // #include <nlohmann/detail/hash.hpp>
  4032. #include <cstddef> // size_t, uint8_t
  4033. #include <functional> // hash
  4034. namespace nlohmann
  4035. {
  4036. namespace detail
  4037. {
  4038. // boost::hash_combine
  4039. inline std::size_t combine(std::size_t seed, std::size_t h) noexcept
  4040. {
  4041. seed ^= h + 0x9e3779b9 + (seed << 6U) + (seed >> 2U);
  4042. return seed;
  4043. }
  4044. /*!
  4045. @brief hash a JSON value
  4046. The hash function tries to rely on std::hash where possible. Furthermore, the
  4047. type of the JSON value is taken into account to have different hash values for
  4048. null, 0, 0U, and false, etc.
  4049. @tparam BasicJsonType basic_json specialization
  4050. @param j JSON value to hash
  4051. @return hash value of j
  4052. */
  4053. template<typename BasicJsonType>
  4054. std::size_t hash(const BasicJsonType& j)
  4055. {
  4056. using string_t = typename BasicJsonType::string_t;
  4057. using number_integer_t = typename BasicJsonType::number_integer_t;
  4058. using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
  4059. using number_float_t = typename BasicJsonType::number_float_t;
  4060. const auto type = static_cast<std::size_t>(j.type());
  4061. switch (j.type())
  4062. {
  4063. case BasicJsonType::value_t::null:
  4064. case BasicJsonType::value_t::discarded:
  4065. {
  4066. return combine(type, 0);
  4067. }
  4068. case BasicJsonType::value_t::object:
  4069. {
  4070. auto seed = combine(type, j.size());
  4071. for (const auto& element : j.items())
  4072. {
  4073. const auto h = std::hash<string_t> {}(element.key());
  4074. seed = combine(seed, h);
  4075. seed = combine(seed, hash(element.value()));
  4076. }
  4077. return seed;
  4078. }
  4079. case BasicJsonType::value_t::array:
  4080. {
  4081. auto seed = combine(type, j.size());
  4082. for (const auto& element : j)
  4083. {
  4084. seed = combine(seed, hash(element));
  4085. }
  4086. return seed;
  4087. }
  4088. case BasicJsonType::value_t::string:
  4089. {
  4090. const auto h = std::hash<string_t> {}(j.template get_ref<const string_t&>());
  4091. return combine(type, h);
  4092. }
  4093. case BasicJsonType::value_t::boolean:
  4094. {
  4095. const auto h = std::hash<bool> {}(j.template get<bool>());
  4096. return combine(type, h);
  4097. }
  4098. case BasicJsonType::value_t::number_integer:
  4099. {
  4100. const auto h = std::hash<number_integer_t> {}(j.template get<number_integer_t>());
  4101. return combine(type, h);
  4102. }
  4103. case nlohmann::detail::value_t::number_unsigned:
  4104. {
  4105. const auto h = std::hash<number_unsigned_t> {}(j.template get<number_unsigned_t>());
  4106. return combine(type, h);
  4107. }
  4108. case nlohmann::detail::value_t::number_float:
  4109. {
  4110. const auto h = std::hash<number_float_t> {}(j.template get<number_float_t>());
  4111. return combine(type, h);
  4112. }
  4113. case nlohmann::detail::value_t::binary:
  4114. {
  4115. auto seed = combine(type, j.get_binary().size());
  4116. const auto h = std::hash<bool> {}(j.get_binary().has_subtype());
  4117. seed = combine(seed, h);
  4118. seed = combine(seed, j.get_binary().subtype());
  4119. for (const auto byte : j.get_binary())
  4120. {
  4121. seed = combine(seed, std::hash<std::uint8_t> {}(byte));
  4122. }
  4123. return seed;
  4124. }
  4125. default: // LCOV_EXCL_LINE
  4126. JSON_ASSERT(false); // LCOV_EXCL_LINE
  4127. }
  4128. }
  4129. } // namespace detail
  4130. } // namespace nlohmann
  4131. // #include <nlohmann/detail/input/binary_reader.hpp>
  4132. #include <algorithm> // generate_n
  4133. #include <array> // array
  4134. #include <cmath> // ldexp
  4135. #include <cstddef> // size_t
  4136. #include <cstdint> // uint8_t, uint16_t, uint32_t, uint64_t
  4137. #include <cstdio> // snprintf
  4138. #include <cstring> // memcpy
  4139. #include <iterator> // back_inserter
  4140. #include <limits> // numeric_limits
  4141. #include <string> // char_traits, string
  4142. #include <utility> // make_pair, move
  4143. // #include <nlohmann/detail/exceptions.hpp>
  4144. // #include <nlohmann/detail/input/input_adapters.hpp>
  4145. #include <array> // array
  4146. #include <cstddef> // size_t
  4147. #include <cstdio> //FILE *
  4148. #include <cstring> // strlen
  4149. #include <istream> // istream
  4150. #include <iterator> // begin, end, iterator_traits, random_access_iterator_tag, distance, next
  4151. #include <memory> // shared_ptr, make_shared, addressof
  4152. #include <numeric> // accumulate
  4153. #include <string> // string, char_traits
  4154. #include <type_traits> // enable_if, is_base_of, is_pointer, is_integral, remove_pointer
  4155. #include <utility> // pair, declval
  4156. // #include <nlohmann/detail/iterators/iterator_traits.hpp>
  4157. // #include <nlohmann/detail/macro_scope.hpp>
  4158. namespace nlohmann
  4159. {
  4160. namespace detail
  4161. {
  4162. /// the supported input formats
  4163. enum class input_format_t { json, cbor, msgpack, ubjson, bson };
  4164. ////////////////////
  4165. // input adapters //
  4166. ////////////////////
  4167. /*!
  4168. Input adapter for stdio file access. This adapter read only 1 byte and do not use any
  4169. buffer. This adapter is a very low level adapter.
  4170. */
  4171. class file_input_adapter
  4172. {
  4173. public:
  4174. using char_type = char;
  4175. JSON_HEDLEY_NON_NULL(2)
  4176. explicit file_input_adapter(std::FILE* f) noexcept
  4177. : m_file(f)
  4178. {}
  4179. // make class move-only
  4180. file_input_adapter(const file_input_adapter&) = delete;
  4181. file_input_adapter(file_input_adapter&&) = default;
  4182. file_input_adapter& operator=(const file_input_adapter&) = delete;
  4183. file_input_adapter& operator=(file_input_adapter&&) = delete;
  4184. std::char_traits<char>::int_type get_character() noexcept
  4185. {
  4186. return std::fgetc(m_file);
  4187. }
  4188. private:
  4189. /// the file pointer to read from
  4190. std::FILE* m_file;
  4191. };
  4192. /*!
  4193. Input adapter for a (caching) istream. Ignores a UFT Byte Order Mark at
  4194. beginning of input. Does not support changing the underlying std::streambuf
  4195. in mid-input. Maintains underlying std::istream and std::streambuf to support
  4196. subsequent use of standard std::istream operations to process any input
  4197. characters following those used in parsing the JSON input. Clears the
  4198. std::istream flags; any input errors (e.g., EOF) will be detected by the first
  4199. subsequent call for input from the std::istream.
  4200. */
  4201. class input_stream_adapter
  4202. {
  4203. public:
  4204. using char_type = char;
  4205. ~input_stream_adapter()
  4206. {
  4207. // clear stream flags; we use underlying streambuf I/O, do not
  4208. // maintain ifstream flags, except eof
  4209. if (is != nullptr)
  4210. {
  4211. is->clear(is->rdstate() & std::ios::eofbit);
  4212. }
  4213. }
  4214. explicit input_stream_adapter(std::istream& i)
  4215. : is(&i), sb(i.rdbuf())
  4216. {}
  4217. // delete because of pointer members
  4218. input_stream_adapter(const input_stream_adapter&) = delete;
  4219. input_stream_adapter& operator=(input_stream_adapter&) = delete;
  4220. input_stream_adapter& operator=(input_stream_adapter&& rhs) = delete;
  4221. input_stream_adapter(input_stream_adapter&& rhs) noexcept : is(rhs.is), sb(rhs.sb)
  4222. {
  4223. rhs.is = nullptr;
  4224. rhs.sb = nullptr;
  4225. }
  4226. // std::istream/std::streambuf use std::char_traits<char>::to_int_type, to
  4227. // ensure that std::char_traits<char>::eof() and the character 0xFF do not
  4228. // end up as the same value, eg. 0xFFFFFFFF.
  4229. std::char_traits<char>::int_type get_character()
  4230. {
  4231. auto res = sb->sbumpc();
  4232. // set eof manually, as we don't use the istream interface.
  4233. if (JSON_HEDLEY_UNLIKELY(res == EOF))
  4234. {
  4235. is->clear(is->rdstate() | std::ios::eofbit);
  4236. }
  4237. return res;
  4238. }
  4239. private:
  4240. /// the associated input stream
  4241. std::istream* is = nullptr;
  4242. std::streambuf* sb = nullptr;
  4243. };
  4244. // General-purpose iterator-based adapter. It might not be as fast as
  4245. // theoretically possible for some containers, but it is extremely versatile.
  4246. template<typename IteratorType>
  4247. class iterator_input_adapter
  4248. {
  4249. public:
  4250. using char_type = typename std::iterator_traits<IteratorType>::value_type;
  4251. iterator_input_adapter(IteratorType first, IteratorType last)
  4252. : current(std::move(first)), end(std::move(last)) {}
  4253. typename std::char_traits<char_type>::int_type get_character()
  4254. {
  4255. if (JSON_HEDLEY_LIKELY(current != end))
  4256. {
  4257. auto result = std::char_traits<char_type>::to_int_type(*current);
  4258. std::advance(current, 1);
  4259. return result;
  4260. }
  4261. else
  4262. {
  4263. return std::char_traits<char_type>::eof();
  4264. }
  4265. }
  4266. private:
  4267. IteratorType current;
  4268. IteratorType end;
  4269. template<typename BaseInputAdapter, size_t T>
  4270. friend struct wide_string_input_helper;
  4271. bool empty() const
  4272. {
  4273. return current == end;
  4274. }
  4275. };
  4276. template<typename BaseInputAdapter, size_t T>
  4277. struct wide_string_input_helper;
  4278. template<typename BaseInputAdapter>
  4279. struct wide_string_input_helper<BaseInputAdapter, 4>
  4280. {
  4281. // UTF-32
  4282. static void fill_buffer(BaseInputAdapter& input,
  4283. std::array<std::char_traits<char>::int_type, 4>& utf8_bytes,
  4284. size_t& utf8_bytes_index,
  4285. size_t& utf8_bytes_filled)
  4286. {
  4287. utf8_bytes_index = 0;
  4288. if (JSON_HEDLEY_UNLIKELY(input.empty()))
  4289. {
  4290. utf8_bytes[0] = std::char_traits<char>::eof();
  4291. utf8_bytes_filled = 1;
  4292. }
  4293. else
  4294. {
  4295. // get the current character
  4296. const auto wc = input.get_character();
  4297. // UTF-32 to UTF-8 encoding
  4298. if (wc < 0x80)
  4299. {
  4300. utf8_bytes[0] = static_cast<std::char_traits<char>::int_type>(wc);
  4301. utf8_bytes_filled = 1;
  4302. }
  4303. else if (wc <= 0x7FF)
  4304. {
  4305. utf8_bytes[0] = static_cast<std::char_traits<char>::int_type>(0xC0u | ((static_cast<unsigned int>(wc) >> 6u) & 0x1Fu));
  4306. utf8_bytes[1] = static_cast<std::char_traits<char>::int_type>(0x80u | (static_cast<unsigned int>(wc) & 0x3Fu));
  4307. utf8_bytes_filled = 2;
  4308. }
  4309. else if (wc <= 0xFFFF)
  4310. {
  4311. utf8_bytes[0] = static_cast<std::char_traits<char>::int_type>(0xE0u | ((static_cast<unsigned int>(wc) >> 12u) & 0x0Fu));
  4312. utf8_bytes[1] = static_cast<std::char_traits<char>::int_type>(0x80u | ((static_cast<unsigned int>(wc) >> 6u) & 0x3Fu));
  4313. utf8_bytes[2] = static_cast<std::char_traits<char>::int_type>(0x80u | (static_cast<unsigned int>(wc) & 0x3Fu));
  4314. utf8_bytes_filled = 3;
  4315. }
  4316. else if (wc <= 0x10FFFF)
  4317. {
  4318. utf8_bytes[0] = static_cast<std::char_traits<char>::int_type>(0xF0u | ((static_cast<unsigned int>(wc) >> 18u) & 0x07u));
  4319. utf8_bytes[1] = static_cast<std::char_traits<char>::int_type>(0x80u | ((static_cast<unsigned int>(wc) >> 12u) & 0x3Fu));
  4320. utf8_bytes[2] = static_cast<std::char_traits<char>::int_type>(0x80u | ((static_cast<unsigned int>(wc) >> 6u) & 0x3Fu));
  4321. utf8_bytes[3] = static_cast<std::char_traits<char>::int_type>(0x80u | (static_cast<unsigned int>(wc) & 0x3Fu));
  4322. utf8_bytes_filled = 4;
  4323. }
  4324. else
  4325. {
  4326. // unknown character
  4327. utf8_bytes[0] = static_cast<std::char_traits<char>::int_type>(wc);
  4328. utf8_bytes_filled = 1;
  4329. }
  4330. }
  4331. }
  4332. };
  4333. template<typename BaseInputAdapter>
  4334. struct wide_string_input_helper<BaseInputAdapter, 2>
  4335. {
  4336. // UTF-16
  4337. static void fill_buffer(BaseInputAdapter& input,
  4338. std::array<std::char_traits<char>::int_type, 4>& utf8_bytes,
  4339. size_t& utf8_bytes_index,
  4340. size_t& utf8_bytes_filled)
  4341. {
  4342. utf8_bytes_index = 0;
  4343. if (JSON_HEDLEY_UNLIKELY(input.empty()))
  4344. {
  4345. utf8_bytes[0] = std::char_traits<char>::eof();
  4346. utf8_bytes_filled = 1;
  4347. }
  4348. else
  4349. {
  4350. // get the current character
  4351. const auto wc = input.get_character();
  4352. // UTF-16 to UTF-8 encoding
  4353. if (wc < 0x80)
  4354. {
  4355. utf8_bytes[0] = static_cast<std::char_traits<char>::int_type>(wc);
  4356. utf8_bytes_filled = 1;
  4357. }
  4358. else if (wc <= 0x7FF)
  4359. {
  4360. utf8_bytes[0] = static_cast<std::char_traits<char>::int_type>(0xC0u | ((static_cast<unsigned int>(wc) >> 6u)));
  4361. utf8_bytes[1] = static_cast<std::char_traits<char>::int_type>(0x80u | (static_cast<unsigned int>(wc) & 0x3Fu));
  4362. utf8_bytes_filled = 2;
  4363. }
  4364. else if (0xD800 > wc || wc >= 0xE000)
  4365. {
  4366. utf8_bytes[0] = static_cast<std::char_traits<char>::int_type>(0xE0u | ((static_cast<unsigned int>(wc) >> 12u)));
  4367. utf8_bytes[1] = static_cast<std::char_traits<char>::int_type>(0x80u | ((static_cast<unsigned int>(wc) >> 6u) & 0x3Fu));
  4368. utf8_bytes[2] = static_cast<std::char_traits<char>::int_type>(0x80u | (static_cast<unsigned int>(wc) & 0x3Fu));
  4369. utf8_bytes_filled = 3;
  4370. }
  4371. else
  4372. {
  4373. if (JSON_HEDLEY_UNLIKELY(!input.empty()))
  4374. {
  4375. const auto wc2 = static_cast<unsigned int>(input.get_character());
  4376. const auto charcode = 0x10000u + (((static_cast<unsigned int>(wc) & 0x3FFu) << 10u) | (wc2 & 0x3FFu));
  4377. utf8_bytes[0] = static_cast<std::char_traits<char>::int_type>(0xF0u | (charcode >> 18u));
  4378. utf8_bytes[1] = static_cast<std::char_traits<char>::int_type>(0x80u | ((charcode >> 12u) & 0x3Fu));
  4379. utf8_bytes[2] = static_cast<std::char_traits<char>::int_type>(0x80u | ((charcode >> 6u) & 0x3Fu));
  4380. utf8_bytes[3] = static_cast<std::char_traits<char>::int_type>(0x80u | (charcode & 0x3Fu));
  4381. utf8_bytes_filled = 4;
  4382. }
  4383. else
  4384. {
  4385. utf8_bytes[0] = static_cast<std::char_traits<char>::int_type>(wc);
  4386. utf8_bytes_filled = 1;
  4387. }
  4388. }
  4389. }
  4390. }
  4391. };
  4392. // Wraps another input apdater to convert wide character types into individual bytes.
  4393. template<typename BaseInputAdapter, typename WideCharType>
  4394. class wide_string_input_adapter
  4395. {
  4396. public:
  4397. using char_type = char;
  4398. wide_string_input_adapter(BaseInputAdapter base)
  4399. : base_adapter(base) {}
  4400. typename std::char_traits<char>::int_type get_character() noexcept
  4401. {
  4402. // check if buffer needs to be filled
  4403. if (utf8_bytes_index == utf8_bytes_filled)
  4404. {
  4405. fill_buffer<sizeof(WideCharType)>();
  4406. JSON_ASSERT(utf8_bytes_filled > 0);
  4407. JSON_ASSERT(utf8_bytes_index == 0);
  4408. }
  4409. // use buffer
  4410. JSON_ASSERT(utf8_bytes_filled > 0);
  4411. JSON_ASSERT(utf8_bytes_index < utf8_bytes_filled);
  4412. return utf8_bytes[utf8_bytes_index++];
  4413. }
  4414. private:
  4415. BaseInputAdapter base_adapter;
  4416. template<size_t T>
  4417. void fill_buffer()
  4418. {
  4419. wide_string_input_helper<BaseInputAdapter, T>::fill_buffer(base_adapter, utf8_bytes, utf8_bytes_index, utf8_bytes_filled);
  4420. }
  4421. /// a buffer for UTF-8 bytes
  4422. std::array<std::char_traits<char>::int_type, 4> utf8_bytes = {{0, 0, 0, 0}};
  4423. /// index to the utf8_codes array for the next valid byte
  4424. std::size_t utf8_bytes_index = 0;
  4425. /// number of valid bytes in the utf8_codes array
  4426. std::size_t utf8_bytes_filled = 0;
  4427. };
  4428. template<typename IteratorType, typename Enable = void>
  4429. struct iterator_input_adapter_factory
  4430. {
  4431. using iterator_type = IteratorType;
  4432. using char_type = typename std::iterator_traits<iterator_type>::value_type;
  4433. using adapter_type = iterator_input_adapter<iterator_type>;
  4434. static adapter_type create(IteratorType first, IteratorType last)
  4435. {
  4436. return adapter_type(std::move(first), std::move(last));
  4437. }
  4438. };
  4439. template<typename T>
  4440. struct is_iterator_of_multibyte
  4441. {
  4442. using value_type = typename std::iterator_traits<T>::value_type;
  4443. enum
  4444. {
  4445. value = sizeof(value_type) > 1
  4446. };
  4447. };
  4448. template<typename IteratorType>
  4449. struct iterator_input_adapter_factory<IteratorType, enable_if_t<is_iterator_of_multibyte<IteratorType>::value>>
  4450. {
  4451. using iterator_type = IteratorType;
  4452. using char_type = typename std::iterator_traits<iterator_type>::value_type;
  4453. using base_adapter_type = iterator_input_adapter<iterator_type>;
  4454. using adapter_type = wide_string_input_adapter<base_adapter_type, char_type>;
  4455. static adapter_type create(IteratorType first, IteratorType last)
  4456. {
  4457. return adapter_type(base_adapter_type(std::move(first), std::move(last)));
  4458. }
  4459. };
  4460. // General purpose iterator-based input
  4461. template<typename IteratorType>
  4462. typename iterator_input_adapter_factory<IteratorType>::adapter_type input_adapter(IteratorType first, IteratorType last)
  4463. {
  4464. using factory_type = iterator_input_adapter_factory<IteratorType>;
  4465. return factory_type::create(first, last);
  4466. }
  4467. // Convenience shorthand from container to iterator
  4468. template<typename ContainerType>
  4469. auto input_adapter(const ContainerType& container) -> decltype(input_adapter(begin(container), end(container)))
  4470. {
  4471. // Enable ADL
  4472. using std::begin;
  4473. using std::end;
  4474. return input_adapter(begin(container), end(container));
  4475. }
  4476. // Special cases with fast paths
  4477. inline file_input_adapter input_adapter(std::FILE* file)
  4478. {
  4479. return file_input_adapter(file);
  4480. }
  4481. inline input_stream_adapter input_adapter(std::istream& stream)
  4482. {
  4483. return input_stream_adapter(stream);
  4484. }
  4485. inline input_stream_adapter input_adapter(std::istream&& stream)
  4486. {
  4487. return input_stream_adapter(stream);
  4488. }
  4489. using contiguous_bytes_input_adapter = decltype(input_adapter(std::declval<const char*>(), std::declval<const char*>()));
  4490. // Null-delimited strings, and the like.
  4491. template < typename CharT,
  4492. typename std::enable_if <
  4493. std::is_pointer<CharT>::value&&
  4494. !std::is_array<CharT>::value&&
  4495. std::is_integral<typename std::remove_pointer<CharT>::type>::value&&
  4496. sizeof(typename std::remove_pointer<CharT>::type) == 1,
  4497. int >::type = 0 >
  4498. contiguous_bytes_input_adapter input_adapter(CharT b)
  4499. {
  4500. auto length = std::strlen(reinterpret_cast<const char*>(b));
  4501. const auto* ptr = reinterpret_cast<const char*>(b);
  4502. return input_adapter(ptr, ptr + length);
  4503. }
  4504. template<typename T, std::size_t N>
  4505. auto input_adapter(T (&array)[N]) -> decltype(input_adapter(array, array + N))
  4506. {
  4507. return input_adapter(array, array + N);
  4508. }
  4509. // This class only handles inputs of input_buffer_adapter type.
  4510. // It's required so that expressions like {ptr, len} can be implicitely casted
  4511. // to the correct adapter.
  4512. class span_input_adapter
  4513. {
  4514. public:
  4515. template < typename CharT,
  4516. typename std::enable_if <
  4517. std::is_pointer<CharT>::value&&
  4518. std::is_integral<typename std::remove_pointer<CharT>::type>::value&&
  4519. sizeof(typename std::remove_pointer<CharT>::type) == 1,
  4520. int >::type = 0 >
  4521. span_input_adapter(CharT b, std::size_t l)
  4522. : ia(reinterpret_cast<const char*>(b), reinterpret_cast<const char*>(b) + l) {}
  4523. template<class IteratorType,
  4524. typename std::enable_if<
  4525. std::is_same<typename iterator_traits<IteratorType>::iterator_category, std::random_access_iterator_tag>::value,
  4526. int>::type = 0>
  4527. span_input_adapter(IteratorType first, IteratorType last)
  4528. : ia(input_adapter(first, last)) {}
  4529. contiguous_bytes_input_adapter&& get()
  4530. {
  4531. return std::move(ia);
  4532. }
  4533. private:
  4534. contiguous_bytes_input_adapter ia;
  4535. };
  4536. } // namespace detail
  4537. } // namespace nlohmann
  4538. // #include <nlohmann/detail/input/json_sax.hpp>
  4539. #include <cstddef>
  4540. #include <string> // string
  4541. #include <utility> // move
  4542. #include <vector> // vector
  4543. // #include <nlohmann/detail/exceptions.hpp>
  4544. // #include <nlohmann/detail/macro_scope.hpp>
  4545. namespace nlohmann
  4546. {
  4547. /*!
  4548. @brief SAX interface
  4549. This class describes the SAX interface used by @ref nlohmann::json::sax_parse.
  4550. Each function is called in different situations while the input is parsed. The
  4551. boolean return value informs the parser whether to continue processing the
  4552. input.
  4553. */
  4554. template<typename BasicJsonType>
  4555. struct json_sax
  4556. {
  4557. using number_integer_t = typename BasicJsonType::number_integer_t;
  4558. using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
  4559. using number_float_t = typename BasicJsonType::number_float_t;
  4560. using string_t = typename BasicJsonType::string_t;
  4561. using binary_t = typename BasicJsonType::binary_t;
  4562. /*!
  4563. @brief a null value was read
  4564. @return whether parsing should proceed
  4565. */
  4566. virtual bool null() = 0;
  4567. /*!
  4568. @brief a boolean value was read
  4569. @param[in] val boolean value
  4570. @return whether parsing should proceed
  4571. */
  4572. virtual bool boolean(bool val) = 0;
  4573. /*!
  4574. @brief an integer number was read
  4575. @param[in] val integer value
  4576. @return whether parsing should proceed
  4577. */
  4578. virtual bool number_integer(number_integer_t val) = 0;
  4579. /*!
  4580. @brief an unsigned integer number was read
  4581. @param[in] val unsigned integer value
  4582. @return whether parsing should proceed
  4583. */
  4584. virtual bool number_unsigned(number_unsigned_t val) = 0;
  4585. /*!
  4586. @brief an floating-point number was read
  4587. @param[in] val floating-point value
  4588. @param[in] s raw token value
  4589. @return whether parsing should proceed
  4590. */
  4591. virtual bool number_float(number_float_t val, const string_t& s) = 0;
  4592. /*!
  4593. @brief a string was read
  4594. @param[in] val string value
  4595. @return whether parsing should proceed
  4596. @note It is safe to move the passed string.
  4597. */
  4598. virtual bool string(string_t& val) = 0;
  4599. /*!
  4600. @brief a binary string was read
  4601. @param[in] val binary value
  4602. @return whether parsing should proceed
  4603. @note It is safe to move the passed binary.
  4604. */
  4605. virtual bool binary(binary_t& val) = 0;
  4606. /*!
  4607. @brief the beginning of an object was read
  4608. @param[in] elements number of object elements or -1 if unknown
  4609. @return whether parsing should proceed
  4610. @note binary formats may report the number of elements
  4611. */
  4612. virtual bool start_object(std::size_t elements) = 0;
  4613. /*!
  4614. @brief an object key was read
  4615. @param[in] val object key
  4616. @return whether parsing should proceed
  4617. @note It is safe to move the passed string.
  4618. */
  4619. virtual bool key(string_t& val) = 0;
  4620. /*!
  4621. @brief the end of an object was read
  4622. @return whether parsing should proceed
  4623. */
  4624. virtual bool end_object() = 0;
  4625. /*!
  4626. @brief the beginning of an array was read
  4627. @param[in] elements number of array elements or -1 if unknown
  4628. @return whether parsing should proceed
  4629. @note binary formats may report the number of elements
  4630. */
  4631. virtual bool start_array(std::size_t elements) = 0;
  4632. /*!
  4633. @brief the end of an array was read
  4634. @return whether parsing should proceed
  4635. */
  4636. virtual bool end_array() = 0;
  4637. /*!
  4638. @brief a parse error occurred
  4639. @param[in] position the position in the input where the error occurs
  4640. @param[in] last_token the last read token
  4641. @param[in] ex an exception object describing the error
  4642. @return whether parsing should proceed (must return false)
  4643. */
  4644. virtual bool parse_error(std::size_t position,
  4645. const std::string& last_token,
  4646. const detail::exception& ex) = 0;
  4647. virtual ~json_sax() = default;
  4648. };
  4649. namespace detail
  4650. {
  4651. /*!
  4652. @brief SAX implementation to create a JSON value from SAX events
  4653. This class implements the @ref json_sax interface and processes the SAX events
  4654. to create a JSON value which makes it basically a DOM parser. The structure or
  4655. hierarchy of the JSON value is managed by the stack `ref_stack` which contains
  4656. a pointer to the respective array or object for each recursion depth.
  4657. After successful parsing, the value that is passed by reference to the
  4658. constructor contains the parsed value.
  4659. @tparam BasicJsonType the JSON type
  4660. */
  4661. template<typename BasicJsonType>
  4662. class json_sax_dom_parser
  4663. {
  4664. public:
  4665. using number_integer_t = typename BasicJsonType::number_integer_t;
  4666. using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
  4667. using number_float_t = typename BasicJsonType::number_float_t;
  4668. using string_t = typename BasicJsonType::string_t;
  4669. using binary_t = typename BasicJsonType::binary_t;
  4670. /*!
  4671. @param[in, out] r reference to a JSON value that is manipulated while
  4672. parsing
  4673. @param[in] allow_exceptions_ whether parse errors yield exceptions
  4674. */
  4675. explicit json_sax_dom_parser(BasicJsonType& r, const bool allow_exceptions_ = true)
  4676. : root(r), allow_exceptions(allow_exceptions_)
  4677. {}
  4678. // make class move-only
  4679. json_sax_dom_parser(const json_sax_dom_parser&) = delete;
  4680. json_sax_dom_parser(json_sax_dom_parser&&) = default;
  4681. json_sax_dom_parser& operator=(const json_sax_dom_parser&) = delete;
  4682. json_sax_dom_parser& operator=(json_sax_dom_parser&&) = default;
  4683. ~json_sax_dom_parser() = default;
  4684. bool null()
  4685. {
  4686. handle_value(nullptr);
  4687. return true;
  4688. }
  4689. bool boolean(bool val)
  4690. {
  4691. handle_value(val);
  4692. return true;
  4693. }
  4694. bool number_integer(number_integer_t val)
  4695. {
  4696. handle_value(val);
  4697. return true;
  4698. }
  4699. bool number_unsigned(number_unsigned_t val)
  4700. {
  4701. handle_value(val);
  4702. return true;
  4703. }
  4704. bool number_float(number_float_t val, const string_t& /*unused*/)
  4705. {
  4706. handle_value(val);
  4707. return true;
  4708. }
  4709. bool string(string_t& val)
  4710. {
  4711. handle_value(val);
  4712. return true;
  4713. }
  4714. bool binary(binary_t& val)
  4715. {
  4716. handle_value(std::move(val));
  4717. return true;
  4718. }
  4719. bool start_object(std::size_t len)
  4720. {
  4721. ref_stack.push_back(handle_value(BasicJsonType::value_t::object));
  4722. if (JSON_HEDLEY_UNLIKELY(len != std::size_t(-1) && len > ref_stack.back()->max_size()))
  4723. {
  4724. JSON_THROW(out_of_range::create(408,
  4725. "excessive object size: " + std::to_string(len)));
  4726. }
  4727. return true;
  4728. }
  4729. bool key(string_t& val)
  4730. {
  4731. // add null at given key and store the reference for later
  4732. object_element = &(ref_stack.back()->m_value.object->operator[](val));
  4733. return true;
  4734. }
  4735. bool end_object()
  4736. {
  4737. ref_stack.pop_back();
  4738. return true;
  4739. }
  4740. bool start_array(std::size_t len)
  4741. {
  4742. ref_stack.push_back(handle_value(BasicJsonType::value_t::array));
  4743. if (JSON_HEDLEY_UNLIKELY(len != std::size_t(-1) && len > ref_stack.back()->max_size()))
  4744. {
  4745. JSON_THROW(out_of_range::create(408,
  4746. "excessive array size: " + std::to_string(len)));
  4747. }
  4748. return true;
  4749. }
  4750. bool end_array()
  4751. {
  4752. ref_stack.pop_back();
  4753. return true;
  4754. }
  4755. template<class Exception>
  4756. bool parse_error(std::size_t /*unused*/, const std::string& /*unused*/,
  4757. const Exception& ex)
  4758. {
  4759. errored = true;
  4760. static_cast<void>(ex);
  4761. if (allow_exceptions)
  4762. {
  4763. JSON_THROW(ex);
  4764. }
  4765. return false;
  4766. }
  4767. constexpr bool is_errored() const
  4768. {
  4769. return errored;
  4770. }
  4771. private:
  4772. /*!
  4773. @invariant If the ref stack is empty, then the passed value will be the new
  4774. root.
  4775. @invariant If the ref stack contains a value, then it is an array or an
  4776. object to which we can add elements
  4777. */
  4778. template<typename Value>
  4779. JSON_HEDLEY_RETURNS_NON_NULL
  4780. BasicJsonType* handle_value(Value&& v)
  4781. {
  4782. if (ref_stack.empty())
  4783. {
  4784. root = BasicJsonType(std::forward<Value>(v));
  4785. return &root;
  4786. }
  4787. JSON_ASSERT(ref_stack.back()->is_array() || ref_stack.back()->is_object());
  4788. if (ref_stack.back()->is_array())
  4789. {
  4790. ref_stack.back()->m_value.array->emplace_back(std::forward<Value>(v));
  4791. return &(ref_stack.back()->m_value.array->back());
  4792. }
  4793. JSON_ASSERT(ref_stack.back()->is_object());
  4794. JSON_ASSERT(object_element);
  4795. *object_element = BasicJsonType(std::forward<Value>(v));
  4796. return object_element;
  4797. }
  4798. /// the parsed JSON value
  4799. BasicJsonType& root;
  4800. /// stack to model hierarchy of values
  4801. std::vector<BasicJsonType*> ref_stack {};
  4802. /// helper to hold the reference for the next object element
  4803. BasicJsonType* object_element = nullptr;
  4804. /// whether a syntax error occurred
  4805. bool errored = false;
  4806. /// whether to throw exceptions in case of errors
  4807. const bool allow_exceptions = true;
  4808. };
  4809. template<typename BasicJsonType>
  4810. class json_sax_dom_callback_parser
  4811. {
  4812. public:
  4813. using number_integer_t = typename BasicJsonType::number_integer_t;
  4814. using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
  4815. using number_float_t = typename BasicJsonType::number_float_t;
  4816. using string_t = typename BasicJsonType::string_t;
  4817. using binary_t = typename BasicJsonType::binary_t;
  4818. using parser_callback_t = typename BasicJsonType::parser_callback_t;
  4819. using parse_event_t = typename BasicJsonType::parse_event_t;
  4820. json_sax_dom_callback_parser(BasicJsonType& r,
  4821. const parser_callback_t cb,
  4822. const bool allow_exceptions_ = true)
  4823. : root(r), callback(cb), allow_exceptions(allow_exceptions_)
  4824. {
  4825. keep_stack.push_back(true);
  4826. }
  4827. // make class move-only
  4828. json_sax_dom_callback_parser(const json_sax_dom_callback_parser&) = delete;
  4829. json_sax_dom_callback_parser(json_sax_dom_callback_parser&&) = default;
  4830. json_sax_dom_callback_parser& operator=(const json_sax_dom_callback_parser&) = delete;
  4831. json_sax_dom_callback_parser& operator=(json_sax_dom_callback_parser&&) = default;
  4832. ~json_sax_dom_callback_parser() = default;
  4833. bool null()
  4834. {
  4835. handle_value(nullptr);
  4836. return true;
  4837. }
  4838. bool boolean(bool val)
  4839. {
  4840. handle_value(val);
  4841. return true;
  4842. }
  4843. bool number_integer(number_integer_t val)
  4844. {
  4845. handle_value(val);
  4846. return true;
  4847. }
  4848. bool number_unsigned(number_unsigned_t val)
  4849. {
  4850. handle_value(val);
  4851. return true;
  4852. }
  4853. bool number_float(number_float_t val, const string_t& /*unused*/)
  4854. {
  4855. handle_value(val);
  4856. return true;
  4857. }
  4858. bool string(string_t& val)
  4859. {
  4860. handle_value(val);
  4861. return true;
  4862. }
  4863. bool binary(binary_t& val)
  4864. {
  4865. handle_value(std::move(val));
  4866. return true;
  4867. }
  4868. bool start_object(std::size_t len)
  4869. {
  4870. // check callback for object start
  4871. const bool keep = callback(static_cast<int>(ref_stack.size()), parse_event_t::object_start, discarded);
  4872. keep_stack.push_back(keep);
  4873. auto val = handle_value(BasicJsonType::value_t::object, true);
  4874. ref_stack.push_back(val.second);
  4875. // check object limit
  4876. if (ref_stack.back() && JSON_HEDLEY_UNLIKELY(len != std::size_t(-1) && len > ref_stack.back()->max_size()))
  4877. {
  4878. JSON_THROW(out_of_range::create(408, "excessive object size: " + std::to_string(len)));
  4879. }
  4880. return true;
  4881. }
  4882. bool key(string_t& val)
  4883. {
  4884. BasicJsonType k = BasicJsonType(val);
  4885. // check callback for key
  4886. const bool keep = callback(static_cast<int>(ref_stack.size()), parse_event_t::key, k);
  4887. key_keep_stack.push_back(keep);
  4888. // add discarded value at given key and store the reference for later
  4889. if (keep && ref_stack.back())
  4890. {
  4891. object_element = &(ref_stack.back()->m_value.object->operator[](val) = discarded);
  4892. }
  4893. return true;
  4894. }
  4895. bool end_object()
  4896. {
  4897. if (ref_stack.back() && !callback(static_cast<int>(ref_stack.size()) - 1, parse_event_t::object_end, *ref_stack.back()))
  4898. {
  4899. // discard object
  4900. *ref_stack.back() = discarded;
  4901. }
  4902. JSON_ASSERT(!ref_stack.empty());
  4903. JSON_ASSERT(!keep_stack.empty());
  4904. ref_stack.pop_back();
  4905. keep_stack.pop_back();
  4906. if (!ref_stack.empty() && ref_stack.back() && ref_stack.back()->is_structured())
  4907. {
  4908. // remove discarded value
  4909. for (auto it = ref_stack.back()->begin(); it != ref_stack.back()->end(); ++it)
  4910. {
  4911. if (it->is_discarded())
  4912. {
  4913. ref_stack.back()->erase(it);
  4914. break;
  4915. }
  4916. }
  4917. }
  4918. return true;
  4919. }
  4920. bool start_array(std::size_t len)
  4921. {
  4922. const bool keep = callback(static_cast<int>(ref_stack.size()), parse_event_t::array_start, discarded);
  4923. keep_stack.push_back(keep);
  4924. auto val = handle_value(BasicJsonType::value_t::array, true);
  4925. ref_stack.push_back(val.second);
  4926. // check array limit
  4927. if (ref_stack.back() && JSON_HEDLEY_UNLIKELY(len != std::size_t(-1) && len > ref_stack.back()->max_size()))
  4928. {
  4929. JSON_THROW(out_of_range::create(408, "excessive array size: " + std::to_string(len)));
  4930. }
  4931. return true;
  4932. }
  4933. bool end_array()
  4934. {
  4935. bool keep = true;
  4936. if (ref_stack.back())
  4937. {
  4938. keep = callback(static_cast<int>(ref_stack.size()) - 1, parse_event_t::array_end, *ref_stack.back());
  4939. if (!keep)
  4940. {
  4941. // discard array
  4942. *ref_stack.back() = discarded;
  4943. }
  4944. }
  4945. JSON_ASSERT(!ref_stack.empty());
  4946. JSON_ASSERT(!keep_stack.empty());
  4947. ref_stack.pop_back();
  4948. keep_stack.pop_back();
  4949. // remove discarded value
  4950. if (!keep && !ref_stack.empty() && ref_stack.back()->is_array())
  4951. {
  4952. ref_stack.back()->m_value.array->pop_back();
  4953. }
  4954. return true;
  4955. }
  4956. template<class Exception>
  4957. bool parse_error(std::size_t /*unused*/, const std::string& /*unused*/,
  4958. const Exception& ex)
  4959. {
  4960. errored = true;
  4961. static_cast<void>(ex);
  4962. if (allow_exceptions)
  4963. {
  4964. JSON_THROW(ex);
  4965. }
  4966. return false;
  4967. }
  4968. constexpr bool is_errored() const
  4969. {
  4970. return errored;
  4971. }
  4972. private:
  4973. /*!
  4974. @param[in] v value to add to the JSON value we build during parsing
  4975. @param[in] skip_callback whether we should skip calling the callback
  4976. function; this is required after start_array() and
  4977. start_object() SAX events, because otherwise we would call the
  4978. callback function with an empty array or object, respectively.
  4979. @invariant If the ref stack is empty, then the passed value will be the new
  4980. root.
  4981. @invariant If the ref stack contains a value, then it is an array or an
  4982. object to which we can add elements
  4983. @return pair of boolean (whether value should be kept) and pointer (to the
  4984. passed value in the ref_stack hierarchy; nullptr if not kept)
  4985. */
  4986. template<typename Value>
  4987. std::pair<bool, BasicJsonType*> handle_value(Value&& v, const bool skip_callback = false)
  4988. {
  4989. JSON_ASSERT(!keep_stack.empty());
  4990. // do not handle this value if we know it would be added to a discarded
  4991. // container
  4992. if (!keep_stack.back())
  4993. {
  4994. return {false, nullptr};
  4995. }
  4996. // create value
  4997. auto value = BasicJsonType(std::forward<Value>(v));
  4998. // check callback
  4999. const bool keep = skip_callback || callback(static_cast<int>(ref_stack.size()), parse_event_t::value, value);
  5000. // do not handle this value if we just learnt it shall be discarded
  5001. if (!keep)
  5002. {
  5003. return {false, nullptr};
  5004. }
  5005. if (ref_stack.empty())
  5006. {
  5007. root = std::move(value);
  5008. return {true, &root};
  5009. }
  5010. // skip this value if we already decided to skip the parent
  5011. // (https://github.com/nlohmann/json/issues/971#issuecomment-413678360)
  5012. if (!ref_stack.back())
  5013. {
  5014. return {false, nullptr};
  5015. }
  5016. // we now only expect arrays and objects
  5017. JSON_ASSERT(ref_stack.back()->is_array() || ref_stack.back()->is_object());
  5018. // array
  5019. if (ref_stack.back()->is_array())
  5020. {
  5021. ref_stack.back()->m_value.array->push_back(std::move(value));
  5022. return {true, &(ref_stack.back()->m_value.array->back())};
  5023. }
  5024. // object
  5025. JSON_ASSERT(ref_stack.back()->is_object());
  5026. // check if we should store an element for the current key
  5027. JSON_ASSERT(!key_keep_stack.empty());
  5028. const bool store_element = key_keep_stack.back();
  5029. key_keep_stack.pop_back();
  5030. if (!store_element)
  5031. {
  5032. return {false, nullptr};
  5033. }
  5034. JSON_ASSERT(object_element);
  5035. *object_element = std::move(value);
  5036. return {true, object_element};
  5037. }
  5038. /// the parsed JSON value
  5039. BasicJsonType& root;
  5040. /// stack to model hierarchy of values
  5041. std::vector<BasicJsonType*> ref_stack {};
  5042. /// stack to manage which values to keep
  5043. std::vector<bool> keep_stack {};
  5044. /// stack to manage which object keys to keep
  5045. std::vector<bool> key_keep_stack {};
  5046. /// helper to hold the reference for the next object element
  5047. BasicJsonType* object_element = nullptr;
  5048. /// whether a syntax error occurred
  5049. bool errored = false;
  5050. /// callback function
  5051. const parser_callback_t callback = nullptr;
  5052. /// whether to throw exceptions in case of errors
  5053. const bool allow_exceptions = true;
  5054. /// a discarded value for the callback
  5055. BasicJsonType discarded = BasicJsonType::value_t::discarded;
  5056. };
  5057. template<typename BasicJsonType>
  5058. class json_sax_acceptor
  5059. {
  5060. public:
  5061. using number_integer_t = typename BasicJsonType::number_integer_t;
  5062. using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
  5063. using number_float_t = typename BasicJsonType::number_float_t;
  5064. using string_t = typename BasicJsonType::string_t;
  5065. using binary_t = typename BasicJsonType::binary_t;
  5066. bool null()
  5067. {
  5068. return true;
  5069. }
  5070. bool boolean(bool /*unused*/)
  5071. {
  5072. return true;
  5073. }
  5074. bool number_integer(number_integer_t /*unused*/)
  5075. {
  5076. return true;
  5077. }
  5078. bool number_unsigned(number_unsigned_t /*unused*/)
  5079. {
  5080. return true;
  5081. }
  5082. bool number_float(number_float_t /*unused*/, const string_t& /*unused*/)
  5083. {
  5084. return true;
  5085. }
  5086. bool string(string_t& /*unused*/)
  5087. {
  5088. return true;
  5089. }
  5090. bool binary(binary_t& /*unused*/)
  5091. {
  5092. return true;
  5093. }
  5094. bool start_object(std::size_t /*unused*/ = std::size_t(-1))
  5095. {
  5096. return true;
  5097. }
  5098. bool key(string_t& /*unused*/)
  5099. {
  5100. return true;
  5101. }
  5102. bool end_object()
  5103. {
  5104. return true;
  5105. }
  5106. bool start_array(std::size_t /*unused*/ = std::size_t(-1))
  5107. {
  5108. return true;
  5109. }
  5110. bool end_array()
  5111. {
  5112. return true;
  5113. }
  5114. bool parse_error(std::size_t /*unused*/, const std::string& /*unused*/, const detail::exception& /*unused*/)
  5115. {
  5116. return false;
  5117. }
  5118. };
  5119. } // namespace detail
  5120. } // namespace nlohmann
  5121. // #include <nlohmann/detail/input/lexer.hpp>
  5122. #include <array> // array
  5123. #include <clocale> // localeconv
  5124. #include <cstddef> // size_t
  5125. #include <cstdio> // snprintf
  5126. #include <cstdlib> // strtof, strtod, strtold, strtoll, strtoull
  5127. #include <initializer_list> // initializer_list
  5128. #include <string> // char_traits, string
  5129. #include <utility> // move
  5130. #include <vector> // vector
  5131. // #include <nlohmann/detail/input/input_adapters.hpp>
  5132. // #include <nlohmann/detail/input/position_t.hpp>
  5133. // #include <nlohmann/detail/macro_scope.hpp>
  5134. namespace nlohmann
  5135. {
  5136. namespace detail
  5137. {
  5138. ///////////
  5139. // lexer //
  5140. ///////////
  5141. template<typename BasicJsonType>
  5142. class lexer_base
  5143. {
  5144. public:
  5145. /// token types for the parser
  5146. enum class token_type
  5147. {
  5148. uninitialized, ///< indicating the scanner is uninitialized
  5149. literal_true, ///< the `true` literal
  5150. literal_false, ///< the `false` literal
  5151. literal_null, ///< the `null` literal
  5152. value_string, ///< a string -- use get_string() for actual value
  5153. value_unsigned, ///< an unsigned integer -- use get_number_unsigned() for actual value
  5154. value_integer, ///< a signed integer -- use get_number_integer() for actual value
  5155. value_float, ///< an floating point number -- use get_number_float() for actual value
  5156. begin_array, ///< the character for array begin `[`
  5157. begin_object, ///< the character for object begin `{`
  5158. end_array, ///< the character for array end `]`
  5159. end_object, ///< the character for object end `}`
  5160. name_separator, ///< the name separator `:`
  5161. value_separator, ///< the value separator `,`
  5162. parse_error, ///< indicating a parse error
  5163. end_of_input, ///< indicating the end of the input buffer
  5164. literal_or_value ///< a literal or the begin of a value (only for diagnostics)
  5165. };
  5166. /// return name of values of type token_type (only used for errors)
  5167. JSON_HEDLEY_RETURNS_NON_NULL
  5168. JSON_HEDLEY_CONST
  5169. static const char* token_type_name(const token_type t) noexcept
  5170. {
  5171. switch (t)
  5172. {
  5173. case token_type::uninitialized:
  5174. return "<uninitialized>";
  5175. case token_type::literal_true:
  5176. return "true literal";
  5177. case token_type::literal_false:
  5178. return "false literal";
  5179. case token_type::literal_null:
  5180. return "null literal";
  5181. case token_type::value_string:
  5182. return "string literal";
  5183. case token_type::value_unsigned:
  5184. case token_type::value_integer:
  5185. case token_type::value_float:
  5186. return "number literal";
  5187. case token_type::begin_array:
  5188. return "'['";
  5189. case token_type::begin_object:
  5190. return "'{'";
  5191. case token_type::end_array:
  5192. return "']'";
  5193. case token_type::end_object:
  5194. return "'}'";
  5195. case token_type::name_separator:
  5196. return "':'";
  5197. case token_type::value_separator:
  5198. return "','";
  5199. case token_type::parse_error:
  5200. return "<parse error>";
  5201. case token_type::end_of_input:
  5202. return "end of input";
  5203. case token_type::literal_or_value:
  5204. return "'[', '{', or a literal";
  5205. // LCOV_EXCL_START
  5206. default: // catch non-enum values
  5207. return "unknown token";
  5208. // LCOV_EXCL_STOP
  5209. }
  5210. }
  5211. };
  5212. /*!
  5213. @brief lexical analysis
  5214. This class organizes the lexical analysis during JSON deserialization.
  5215. */
  5216. template<typename BasicJsonType, typename InputAdapterType>
  5217. class lexer : public lexer_base<BasicJsonType>
  5218. {
  5219. using number_integer_t = typename BasicJsonType::number_integer_t;
  5220. using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
  5221. using number_float_t = typename BasicJsonType::number_float_t;
  5222. using string_t = typename BasicJsonType::string_t;
  5223. using char_type = typename InputAdapterType::char_type;
  5224. using char_int_type = typename std::char_traits<char_type>::int_type;
  5225. public:
  5226. using token_type = typename lexer_base<BasicJsonType>::token_type;
  5227. explicit lexer(InputAdapterType&& adapter, bool ignore_comments_ = false)
  5228. : ia(std::move(adapter))
  5229. , ignore_comments(ignore_comments_)
  5230. , decimal_point_char(static_cast<char_int_type>(get_decimal_point()))
  5231. {}
  5232. // delete because of pointer members
  5233. lexer(const lexer&) = delete;
  5234. lexer(lexer&&) = default;
  5235. lexer& operator=(lexer&) = delete;
  5236. lexer& operator=(lexer&&) = default;
  5237. ~lexer() = default;
  5238. private:
  5239. /////////////////////
  5240. // locales
  5241. /////////////////////
  5242. /// return the locale-dependent decimal point
  5243. JSON_HEDLEY_PURE
  5244. static char get_decimal_point() noexcept
  5245. {
  5246. const auto* loc = localeconv();
  5247. JSON_ASSERT(loc != nullptr);
  5248. return (loc->decimal_point == nullptr) ? '.' : *(loc->decimal_point);
  5249. }
  5250. /////////////////////
  5251. // scan functions
  5252. /////////////////////
  5253. /*!
  5254. @brief get codepoint from 4 hex characters following `\u`
  5255. For input "\u c1 c2 c3 c4" the codepoint is:
  5256. (c1 * 0x1000) + (c2 * 0x0100) + (c3 * 0x0010) + c4
  5257. = (c1 << 12) + (c2 << 8) + (c3 << 4) + (c4 << 0)
  5258. Furthermore, the possible characters '0'..'9', 'A'..'F', and 'a'..'f'
  5259. must be converted to the integers 0x0..0x9, 0xA..0xF, 0xA..0xF, resp. The
  5260. conversion is done by subtracting the offset (0x30, 0x37, and 0x57)
  5261. between the ASCII value of the character and the desired integer value.
  5262. @return codepoint (0x0000..0xFFFF) or -1 in case of an error (e.g. EOF or
  5263. non-hex character)
  5264. */
  5265. int get_codepoint()
  5266. {
  5267. // this function only makes sense after reading `\u`
  5268. JSON_ASSERT(current == 'u');
  5269. int codepoint = 0;
  5270. const auto factors = { 12u, 8u, 4u, 0u };
  5271. for (const auto factor : factors)
  5272. {
  5273. get();
  5274. if (current >= '0' && current <= '9')
  5275. {
  5276. codepoint += static_cast<int>((static_cast<unsigned int>(current) - 0x30u) << factor);
  5277. }
  5278. else if (current >= 'A' && current <= 'F')
  5279. {
  5280. codepoint += static_cast<int>((static_cast<unsigned int>(current) - 0x37u) << factor);
  5281. }
  5282. else if (current >= 'a' && current <= 'f')
  5283. {
  5284. codepoint += static_cast<int>((static_cast<unsigned int>(current) - 0x57u) << factor);
  5285. }
  5286. else
  5287. {
  5288. return -1;
  5289. }
  5290. }
  5291. JSON_ASSERT(0x0000 <= codepoint && codepoint <= 0xFFFF);
  5292. return codepoint;
  5293. }
  5294. /*!
  5295. @brief check if the next byte(s) are inside a given range
  5296. Adds the current byte and, for each passed range, reads a new byte and
  5297. checks if it is inside the range. If a violation was detected, set up an
  5298. error message and return false. Otherwise, return true.
  5299. @param[in] ranges list of integers; interpreted as list of pairs of
  5300. inclusive lower and upper bound, respectively
  5301. @pre The passed list @a ranges must have 2, 4, or 6 elements; that is,
  5302. 1, 2, or 3 pairs. This precondition is enforced by an assertion.
  5303. @return true if and only if no range violation was detected
  5304. */
  5305. bool next_byte_in_range(std::initializer_list<char_int_type> ranges)
  5306. {
  5307. JSON_ASSERT(ranges.size() == 2 || ranges.size() == 4 || ranges.size() == 6);
  5308. add(current);
  5309. for (auto range = ranges.begin(); range != ranges.end(); ++range)
  5310. {
  5311. get();
  5312. if (JSON_HEDLEY_LIKELY(*range <= current && current <= *(++range)))
  5313. {
  5314. add(current);
  5315. }
  5316. else
  5317. {
  5318. error_message = "invalid string: ill-formed UTF-8 byte";
  5319. return false;
  5320. }
  5321. }
  5322. return true;
  5323. }
  5324. /*!
  5325. @brief scan a string literal
  5326. This function scans a string according to Sect. 7 of RFC 7159. While
  5327. scanning, bytes are escaped and copied into buffer token_buffer. Then the
  5328. function returns successfully, token_buffer is *not* null-terminated (as it
  5329. may contain \0 bytes), and token_buffer.size() is the number of bytes in the
  5330. string.
  5331. @return token_type::value_string if string could be successfully scanned,
  5332. token_type::parse_error otherwise
  5333. @note In case of errors, variable error_message contains a textual
  5334. description.
  5335. */
  5336. token_type scan_string()
  5337. {
  5338. // reset token_buffer (ignore opening quote)
  5339. reset();
  5340. // we entered the function by reading an open quote
  5341. JSON_ASSERT(current == '\"');
  5342. while (true)
  5343. {
  5344. // get next character
  5345. switch (get())
  5346. {
  5347. // end of file while parsing string
  5348. case std::char_traits<char_type>::eof():
  5349. {
  5350. error_message = "invalid string: missing closing quote";
  5351. return token_type::parse_error;
  5352. }
  5353. // closing quote
  5354. case '\"':
  5355. {
  5356. return token_type::value_string;
  5357. }
  5358. // escapes
  5359. case '\\':
  5360. {
  5361. switch (get())
  5362. {
  5363. // quotation mark
  5364. case '\"':
  5365. add('\"');
  5366. break;
  5367. // reverse solidus
  5368. case '\\':
  5369. add('\\');
  5370. break;
  5371. // solidus
  5372. case '/':
  5373. add('/');
  5374. break;
  5375. // backspace
  5376. case 'b':
  5377. add('\b');
  5378. break;
  5379. // form feed
  5380. case 'f':
  5381. add('\f');
  5382. break;
  5383. // line feed
  5384. case 'n':
  5385. add('\n');
  5386. break;
  5387. // carriage return
  5388. case 'r':
  5389. add('\r');
  5390. break;
  5391. // tab
  5392. case 't':
  5393. add('\t');
  5394. break;
  5395. // unicode escapes
  5396. case 'u':
  5397. {
  5398. const int codepoint1 = get_codepoint();
  5399. int codepoint = codepoint1; // start with codepoint1
  5400. if (JSON_HEDLEY_UNLIKELY(codepoint1 == -1))
  5401. {
  5402. error_message = "invalid string: '\\u' must be followed by 4 hex digits";
  5403. return token_type::parse_error;
  5404. }
  5405. // check if code point is a high surrogate
  5406. if (0xD800 <= codepoint1 && codepoint1 <= 0xDBFF)
  5407. {
  5408. // expect next \uxxxx entry
  5409. if (JSON_HEDLEY_LIKELY(get() == '\\' && get() == 'u'))
  5410. {
  5411. const int codepoint2 = get_codepoint();
  5412. if (JSON_HEDLEY_UNLIKELY(codepoint2 == -1))
  5413. {
  5414. error_message = "invalid string: '\\u' must be followed by 4 hex digits";
  5415. return token_type::parse_error;
  5416. }
  5417. // check if codepoint2 is a low surrogate
  5418. if (JSON_HEDLEY_LIKELY(0xDC00 <= codepoint2 && codepoint2 <= 0xDFFF))
  5419. {
  5420. // overwrite codepoint
  5421. codepoint = static_cast<int>(
  5422. // high surrogate occupies the most significant 22 bits
  5423. (static_cast<unsigned int>(codepoint1) << 10u)
  5424. // low surrogate occupies the least significant 15 bits
  5425. + static_cast<unsigned int>(codepoint2)
  5426. // there is still the 0xD800, 0xDC00 and 0x10000 noise
  5427. // in the result so we have to subtract with:
  5428. // (0xD800 << 10) + DC00 - 0x10000 = 0x35FDC00
  5429. - 0x35FDC00u);
  5430. }
  5431. else
  5432. {
  5433. error_message = "invalid string: surrogate U+D800..U+DBFF must be followed by U+DC00..U+DFFF";
  5434. return token_type::parse_error;
  5435. }
  5436. }
  5437. else
  5438. {
  5439. error_message = "invalid string: surrogate U+D800..U+DBFF must be followed by U+DC00..U+DFFF";
  5440. return token_type::parse_error;
  5441. }
  5442. }
  5443. else
  5444. {
  5445. if (JSON_HEDLEY_UNLIKELY(0xDC00 <= codepoint1 && codepoint1 <= 0xDFFF))
  5446. {
  5447. error_message = "invalid string: surrogate U+DC00..U+DFFF must follow U+D800..U+DBFF";
  5448. return token_type::parse_error;
  5449. }
  5450. }
  5451. // result of the above calculation yields a proper codepoint
  5452. JSON_ASSERT(0x00 <= codepoint && codepoint <= 0x10FFFF);
  5453. // translate codepoint into bytes
  5454. if (codepoint < 0x80)
  5455. {
  5456. // 1-byte characters: 0xxxxxxx (ASCII)
  5457. add(static_cast<char_int_type>(codepoint));
  5458. }
  5459. else if (codepoint <= 0x7FF)
  5460. {
  5461. // 2-byte characters: 110xxxxx 10xxxxxx
  5462. add(static_cast<char_int_type>(0xC0u | (static_cast<unsigned int>(codepoint) >> 6u)));
  5463. add(static_cast<char_int_type>(0x80u | (static_cast<unsigned int>(codepoint) & 0x3Fu)));
  5464. }
  5465. else if (codepoint <= 0xFFFF)
  5466. {
  5467. // 3-byte characters: 1110xxxx 10xxxxxx 10xxxxxx
  5468. add(static_cast<char_int_type>(0xE0u | (static_cast<unsigned int>(codepoint) >> 12u)));
  5469. add(static_cast<char_int_type>(0x80u | ((static_cast<unsigned int>(codepoint) >> 6u) & 0x3Fu)));
  5470. add(static_cast<char_int_type>(0x80u | (static_cast<unsigned int>(codepoint) & 0x3Fu)));
  5471. }
  5472. else
  5473. {
  5474. // 4-byte characters: 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
  5475. add(static_cast<char_int_type>(0xF0u | (static_cast<unsigned int>(codepoint) >> 18u)));
  5476. add(static_cast<char_int_type>(0x80u | ((static_cast<unsigned int>(codepoint) >> 12u) & 0x3Fu)));
  5477. add(static_cast<char_int_type>(0x80u | ((static_cast<unsigned int>(codepoint) >> 6u) & 0x3Fu)));
  5478. add(static_cast<char_int_type>(0x80u | (static_cast<unsigned int>(codepoint) & 0x3Fu)));
  5479. }
  5480. break;
  5481. }
  5482. // other characters after escape
  5483. default:
  5484. error_message = "invalid string: forbidden character after backslash";
  5485. return token_type::parse_error;
  5486. }
  5487. break;
  5488. }
  5489. // invalid control characters
  5490. case 0x00:
  5491. {
  5492. error_message = "invalid string: control character U+0000 (NUL) must be escaped to \\u0000";
  5493. return token_type::parse_error;
  5494. }
  5495. case 0x01:
  5496. {
  5497. error_message = "invalid string: control character U+0001 (SOH) must be escaped to \\u0001";
  5498. return token_type::parse_error;
  5499. }
  5500. case 0x02:
  5501. {
  5502. error_message = "invalid string: control character U+0002 (STX) must be escaped to \\u0002";
  5503. return token_type::parse_error;
  5504. }
  5505. case 0x03:
  5506. {
  5507. error_message = "invalid string: control character U+0003 (ETX) must be escaped to \\u0003";
  5508. return token_type::parse_error;
  5509. }
  5510. case 0x04:
  5511. {
  5512. error_message = "invalid string: control character U+0004 (EOT) must be escaped to \\u0004";
  5513. return token_type::parse_error;
  5514. }
  5515. case 0x05:
  5516. {
  5517. error_message = "invalid string: control character U+0005 (ENQ) must be escaped to \\u0005";
  5518. return token_type::parse_error;
  5519. }
  5520. case 0x06:
  5521. {
  5522. error_message = "invalid string: control character U+0006 (ACK) must be escaped to \\u0006";
  5523. return token_type::parse_error;
  5524. }
  5525. case 0x07:
  5526. {
  5527. error_message = "invalid string: control character U+0007 (BEL) must be escaped to \\u0007";
  5528. return token_type::parse_error;
  5529. }
  5530. case 0x08:
  5531. {
  5532. error_message = "invalid string: control character U+0008 (BS) must be escaped to \\u0008 or \\b";
  5533. return token_type::parse_error;
  5534. }
  5535. case 0x09:
  5536. {
  5537. error_message = "invalid string: control character U+0009 (HT) must be escaped to \\u0009 or \\t";
  5538. return token_type::parse_error;
  5539. }
  5540. case 0x0A:
  5541. {
  5542. error_message = "invalid string: control character U+000A (LF) must be escaped to \\u000A or \\n";
  5543. return token_type::parse_error;
  5544. }
  5545. case 0x0B:
  5546. {
  5547. error_message = "invalid string: control character U+000B (VT) must be escaped to \\u000B";
  5548. return token_type::parse_error;
  5549. }
  5550. case 0x0C:
  5551. {
  5552. error_message = "invalid string: control character U+000C (FF) must be escaped to \\u000C or \\f";
  5553. return token_type::parse_error;
  5554. }
  5555. case 0x0D:
  5556. {
  5557. error_message = "invalid string: control character U+000D (CR) must be escaped to \\u000D or \\r";
  5558. return token_type::parse_error;
  5559. }
  5560. case 0x0E:
  5561. {
  5562. error_message = "invalid string: control character U+000E (SO) must be escaped to \\u000E";
  5563. return token_type::parse_error;
  5564. }
  5565. case 0x0F:
  5566. {
  5567. error_message = "invalid string: control character U+000F (SI) must be escaped to \\u000F";
  5568. return token_type::parse_error;
  5569. }
  5570. case 0x10:
  5571. {
  5572. error_message = "invalid string: control character U+0010 (DLE) must be escaped to \\u0010";
  5573. return token_type::parse_error;
  5574. }
  5575. case 0x11:
  5576. {
  5577. error_message = "invalid string: control character U+0011 (DC1) must be escaped to \\u0011";
  5578. return token_type::parse_error;
  5579. }
  5580. case 0x12:
  5581. {
  5582. error_message = "invalid string: control character U+0012 (DC2) must be escaped to \\u0012";
  5583. return token_type::parse_error;
  5584. }
  5585. case 0x13:
  5586. {
  5587. error_message = "invalid string: control character U+0013 (DC3) must be escaped to \\u0013";
  5588. return token_type::parse_error;
  5589. }
  5590. case 0x14:
  5591. {
  5592. error_message = "invalid string: control character U+0014 (DC4) must be escaped to \\u0014";
  5593. return token_type::parse_error;
  5594. }
  5595. case 0x15:
  5596. {
  5597. error_message = "invalid string: control character U+0015 (NAK) must be escaped to \\u0015";
  5598. return token_type::parse_error;
  5599. }
  5600. case 0x16:
  5601. {
  5602. error_message = "invalid string: control character U+0016 (SYN) must be escaped to \\u0016";
  5603. return token_type::parse_error;
  5604. }
  5605. case 0x17:
  5606. {
  5607. error_message = "invalid string: control character U+0017 (ETB) must be escaped to \\u0017";
  5608. return token_type::parse_error;
  5609. }
  5610. case 0x18:
  5611. {
  5612. error_message = "invalid string: control character U+0018 (CAN) must be escaped to \\u0018";
  5613. return token_type::parse_error;
  5614. }
  5615. case 0x19:
  5616. {
  5617. error_message = "invalid string: control character U+0019 (EM) must be escaped to \\u0019";
  5618. return token_type::parse_error;
  5619. }
  5620. case 0x1A:
  5621. {
  5622. error_message = "invalid string: control character U+001A (SUB) must be escaped to \\u001A";
  5623. return token_type::parse_error;
  5624. }
  5625. case 0x1B:
  5626. {
  5627. error_message = "invalid string: control character U+001B (ESC) must be escaped to \\u001B";
  5628. return token_type::parse_error;
  5629. }
  5630. case 0x1C:
  5631. {
  5632. error_message = "invalid string: control character U+001C (FS) must be escaped to \\u001C";
  5633. return token_type::parse_error;
  5634. }
  5635. case 0x1D:
  5636. {
  5637. error_message = "invalid string: control character U+001D (GS) must be escaped to \\u001D";
  5638. return token_type::parse_error;
  5639. }
  5640. case 0x1E:
  5641. {
  5642. error_message = "invalid string: control character U+001E (RS) must be escaped to \\u001E";
  5643. return token_type::parse_error;
  5644. }
  5645. case 0x1F:
  5646. {
  5647. error_message = "invalid string: control character U+001F (US) must be escaped to \\u001F";
  5648. return token_type::parse_error;
  5649. }
  5650. // U+0020..U+007F (except U+0022 (quote) and U+005C (backspace))
  5651. case 0x20:
  5652. case 0x21:
  5653. case 0x23:
  5654. case 0x24:
  5655. case 0x25:
  5656. case 0x26:
  5657. case 0x27:
  5658. case 0x28:
  5659. case 0x29:
  5660. case 0x2A:
  5661. case 0x2B:
  5662. case 0x2C:
  5663. case 0x2D:
  5664. case 0x2E:
  5665. case 0x2F:
  5666. case 0x30:
  5667. case 0x31:
  5668. case 0x32:
  5669. case 0x33:
  5670. case 0x34:
  5671. case 0x35:
  5672. case 0x36:
  5673. case 0x37:
  5674. case 0x38:
  5675. case 0x39:
  5676. case 0x3A:
  5677. case 0x3B:
  5678. case 0x3C:
  5679. case 0x3D:
  5680. case 0x3E:
  5681. case 0x3F:
  5682. case 0x40:
  5683. case 0x41:
  5684. case 0x42:
  5685. case 0x43:
  5686. case 0x44:
  5687. case 0x45:
  5688. case 0x46:
  5689. case 0x47:
  5690. case 0x48:
  5691. case 0x49:
  5692. case 0x4A:
  5693. case 0x4B:
  5694. case 0x4C:
  5695. case 0x4D:
  5696. case 0x4E:
  5697. case 0x4F:
  5698. case 0x50:
  5699. case 0x51:
  5700. case 0x52:
  5701. case 0x53:
  5702. case 0x54:
  5703. case 0x55:
  5704. case 0x56:
  5705. case 0x57:
  5706. case 0x58:
  5707. case 0x59:
  5708. case 0x5A:
  5709. case 0x5B:
  5710. case 0x5D:
  5711. case 0x5E:
  5712. case 0x5F:
  5713. case 0x60:
  5714. case 0x61:
  5715. case 0x62:
  5716. case 0x63:
  5717. case 0x64:
  5718. case 0x65:
  5719. case 0x66:
  5720. case 0x67:
  5721. case 0x68:
  5722. case 0x69:
  5723. case 0x6A:
  5724. case 0x6B:
  5725. case 0x6C:
  5726. case 0x6D:
  5727. case 0x6E:
  5728. case 0x6F:
  5729. case 0x70:
  5730. case 0x71:
  5731. case 0x72:
  5732. case 0x73:
  5733. case 0x74:
  5734. case 0x75:
  5735. case 0x76:
  5736. case 0x77:
  5737. case 0x78:
  5738. case 0x79:
  5739. case 0x7A:
  5740. case 0x7B:
  5741. case 0x7C:
  5742. case 0x7D:
  5743. case 0x7E:
  5744. case 0x7F:
  5745. {
  5746. add(current);
  5747. break;
  5748. }
  5749. // U+0080..U+07FF: bytes C2..DF 80..BF
  5750. case 0xC2:
  5751. case 0xC3:
  5752. case 0xC4:
  5753. case 0xC5:
  5754. case 0xC6:
  5755. case 0xC7:
  5756. case 0xC8:
  5757. case 0xC9:
  5758. case 0xCA:
  5759. case 0xCB:
  5760. case 0xCC:
  5761. case 0xCD:
  5762. case 0xCE:
  5763. case 0xCF:
  5764. case 0xD0:
  5765. case 0xD1:
  5766. case 0xD2:
  5767. case 0xD3:
  5768. case 0xD4:
  5769. case 0xD5:
  5770. case 0xD6:
  5771. case 0xD7:
  5772. case 0xD8:
  5773. case 0xD9:
  5774. case 0xDA:
  5775. case 0xDB:
  5776. case 0xDC:
  5777. case 0xDD:
  5778. case 0xDE:
  5779. case 0xDF:
  5780. {
  5781. if (JSON_HEDLEY_UNLIKELY(!next_byte_in_range({0x80, 0xBF})))
  5782. {
  5783. return token_type::parse_error;
  5784. }
  5785. break;
  5786. }
  5787. // U+0800..U+0FFF: bytes E0 A0..BF 80..BF
  5788. case 0xE0:
  5789. {
  5790. if (JSON_HEDLEY_UNLIKELY(!(next_byte_in_range({0xA0, 0xBF, 0x80, 0xBF}))))
  5791. {
  5792. return token_type::parse_error;
  5793. }
  5794. break;
  5795. }
  5796. // U+1000..U+CFFF: bytes E1..EC 80..BF 80..BF
  5797. // U+E000..U+FFFF: bytes EE..EF 80..BF 80..BF
  5798. case 0xE1:
  5799. case 0xE2:
  5800. case 0xE3:
  5801. case 0xE4:
  5802. case 0xE5:
  5803. case 0xE6:
  5804. case 0xE7:
  5805. case 0xE8:
  5806. case 0xE9:
  5807. case 0xEA:
  5808. case 0xEB:
  5809. case 0xEC:
  5810. case 0xEE:
  5811. case 0xEF:
  5812. {
  5813. if (JSON_HEDLEY_UNLIKELY(!(next_byte_in_range({0x80, 0xBF, 0x80, 0xBF}))))
  5814. {
  5815. return token_type::parse_error;
  5816. }
  5817. break;
  5818. }
  5819. // U+D000..U+D7FF: bytes ED 80..9F 80..BF
  5820. case 0xED:
  5821. {
  5822. if (JSON_HEDLEY_UNLIKELY(!(next_byte_in_range({0x80, 0x9F, 0x80, 0xBF}))))
  5823. {
  5824. return token_type::parse_error;
  5825. }
  5826. break;
  5827. }
  5828. // U+10000..U+3FFFF F0 90..BF 80..BF 80..BF
  5829. case 0xF0:
  5830. {
  5831. if (JSON_HEDLEY_UNLIKELY(!(next_byte_in_range({0x90, 0xBF, 0x80, 0xBF, 0x80, 0xBF}))))
  5832. {
  5833. return token_type::parse_error;
  5834. }
  5835. break;
  5836. }
  5837. // U+40000..U+FFFFF F1..F3 80..BF 80..BF 80..BF
  5838. case 0xF1:
  5839. case 0xF2:
  5840. case 0xF3:
  5841. {
  5842. if (JSON_HEDLEY_UNLIKELY(!(next_byte_in_range({0x80, 0xBF, 0x80, 0xBF, 0x80, 0xBF}))))
  5843. {
  5844. return token_type::parse_error;
  5845. }
  5846. break;
  5847. }
  5848. // U+100000..U+10FFFF F4 80..8F 80..BF 80..BF
  5849. case 0xF4:
  5850. {
  5851. if (JSON_HEDLEY_UNLIKELY(!(next_byte_in_range({0x80, 0x8F, 0x80, 0xBF, 0x80, 0xBF}))))
  5852. {
  5853. return token_type::parse_error;
  5854. }
  5855. break;
  5856. }
  5857. // remaining bytes (80..C1 and F5..FF) are ill-formed
  5858. default:
  5859. {
  5860. error_message = "invalid string: ill-formed UTF-8 byte";
  5861. return token_type::parse_error;
  5862. }
  5863. }
  5864. }
  5865. }
  5866. /*!
  5867. * @brief scan a comment
  5868. * @return whether comment could be scanned successfully
  5869. */
  5870. bool scan_comment()
  5871. {
  5872. switch (get())
  5873. {
  5874. // single-line comments skip input until a newline or EOF is read
  5875. case '/':
  5876. {
  5877. while (true)
  5878. {
  5879. switch (get())
  5880. {
  5881. case '\n':
  5882. case '\r':
  5883. case std::char_traits<char_type>::eof():
  5884. case '\0':
  5885. return true;
  5886. default:
  5887. break;
  5888. }
  5889. }
  5890. }
  5891. // multi-line comments skip input until */ is read
  5892. case '*':
  5893. {
  5894. while (true)
  5895. {
  5896. switch (get())
  5897. {
  5898. case std::char_traits<char_type>::eof():
  5899. case '\0':
  5900. {
  5901. error_message = "invalid comment; missing closing '*/'";
  5902. return false;
  5903. }
  5904. case '*':
  5905. {
  5906. switch (get())
  5907. {
  5908. case '/':
  5909. return true;
  5910. default:
  5911. {
  5912. unget();
  5913. continue;
  5914. }
  5915. }
  5916. }
  5917. default:
  5918. continue;
  5919. }
  5920. }
  5921. }
  5922. // unexpected character after reading '/'
  5923. default:
  5924. {
  5925. error_message = "invalid comment; expecting '/' or '*' after '/'";
  5926. return false;
  5927. }
  5928. }
  5929. }
  5930. JSON_HEDLEY_NON_NULL(2)
  5931. static void strtof(float& f, const char* str, char** endptr) noexcept
  5932. {
  5933. f = std::strtof(str, endptr);
  5934. }
  5935. JSON_HEDLEY_NON_NULL(2)
  5936. static void strtof(double& f, const char* str, char** endptr) noexcept
  5937. {
  5938. f = std::strtod(str, endptr);
  5939. }
  5940. JSON_HEDLEY_NON_NULL(2)
  5941. static void strtof(long double& f, const char* str, char** endptr) noexcept
  5942. {
  5943. f = std::strtold(str, endptr);
  5944. }
  5945. /*!
  5946. @brief scan a number literal
  5947. This function scans a string according to Sect. 6 of RFC 7159.
  5948. The function is realized with a deterministic finite state machine derived
  5949. from the grammar described in RFC 7159. Starting in state "init", the
  5950. input is read and used to determined the next state. Only state "done"
  5951. accepts the number. State "error" is a trap state to model errors. In the
  5952. table below, "anything" means any character but the ones listed before.
  5953. state | 0 | 1-9 | e E | + | - | . | anything
  5954. ---------|----------|----------|----------|---------|---------|----------|-----------
  5955. init | zero | any1 | [error] | [error] | minus | [error] | [error]
  5956. minus | zero | any1 | [error] | [error] | [error] | [error] | [error]
  5957. zero | done | done | exponent | done | done | decimal1 | done
  5958. any1 | any1 | any1 | exponent | done | done | decimal1 | done
  5959. decimal1 | decimal2 | decimal2 | [error] | [error] | [error] | [error] | [error]
  5960. decimal2 | decimal2 | decimal2 | exponent | done | done | done | done
  5961. exponent | any2 | any2 | [error] | sign | sign | [error] | [error]
  5962. sign | any2 | any2 | [error] | [error] | [error] | [error] | [error]
  5963. any2 | any2 | any2 | done | done | done | done | done
  5964. The state machine is realized with one label per state (prefixed with
  5965. "scan_number_") and `goto` statements between them. The state machine
  5966. contains cycles, but any cycle can be left when EOF is read. Therefore,
  5967. the function is guaranteed to terminate.
  5968. During scanning, the read bytes are stored in token_buffer. This string is
  5969. then converted to a signed integer, an unsigned integer, or a
  5970. floating-point number.
  5971. @return token_type::value_unsigned, token_type::value_integer, or
  5972. token_type::value_float if number could be successfully scanned,
  5973. token_type::parse_error otherwise
  5974. @note The scanner is independent of the current locale. Internally, the
  5975. locale's decimal point is used instead of `.` to work with the
  5976. locale-dependent converters.
  5977. */
  5978. token_type scan_number() // lgtm [cpp/use-of-goto]
  5979. {
  5980. // reset token_buffer to store the number's bytes
  5981. reset();
  5982. // the type of the parsed number; initially set to unsigned; will be
  5983. // changed if minus sign, decimal point or exponent is read
  5984. token_type number_type = token_type::value_unsigned;
  5985. // state (init): we just found out we need to scan a number
  5986. switch (current)
  5987. {
  5988. case '-':
  5989. {
  5990. add(current);
  5991. goto scan_number_minus;
  5992. }
  5993. case '0':
  5994. {
  5995. add(current);
  5996. goto scan_number_zero;
  5997. }
  5998. case '1':
  5999. case '2':
  6000. case '3':
  6001. case '4':
  6002. case '5':
  6003. case '6':
  6004. case '7':
  6005. case '8':
  6006. case '9':
  6007. {
  6008. add(current);
  6009. goto scan_number_any1;
  6010. }
  6011. // all other characters are rejected outside scan_number()
  6012. default: // LCOV_EXCL_LINE
  6013. JSON_ASSERT(false); // LCOV_EXCL_LINE
  6014. }
  6015. scan_number_minus:
  6016. // state: we just parsed a leading minus sign
  6017. number_type = token_type::value_integer;
  6018. switch (get())
  6019. {
  6020. case '0':
  6021. {
  6022. add(current);
  6023. goto scan_number_zero;
  6024. }
  6025. case '1':
  6026. case '2':
  6027. case '3':
  6028. case '4':
  6029. case '5':
  6030. case '6':
  6031. case '7':
  6032. case '8':
  6033. case '9':
  6034. {
  6035. add(current);
  6036. goto scan_number_any1;
  6037. }
  6038. default:
  6039. {
  6040. error_message = "invalid number; expected digit after '-'";
  6041. return token_type::parse_error;
  6042. }
  6043. }
  6044. scan_number_zero:
  6045. // state: we just parse a zero (maybe with a leading minus sign)
  6046. switch (get())
  6047. {
  6048. case '.':
  6049. {
  6050. add(decimal_point_char);
  6051. goto scan_number_decimal1;
  6052. }
  6053. case 'e':
  6054. case 'E':
  6055. {
  6056. add(current);
  6057. goto scan_number_exponent;
  6058. }
  6059. default:
  6060. goto scan_number_done;
  6061. }
  6062. scan_number_any1:
  6063. // state: we just parsed a number 0-9 (maybe with a leading minus sign)
  6064. switch (get())
  6065. {
  6066. case '0':
  6067. case '1':
  6068. case '2':
  6069. case '3':
  6070. case '4':
  6071. case '5':
  6072. case '6':
  6073. case '7':
  6074. case '8':
  6075. case '9':
  6076. {
  6077. add(current);
  6078. goto scan_number_any1;
  6079. }
  6080. case '.':
  6081. {
  6082. add(decimal_point_char);
  6083. goto scan_number_decimal1;
  6084. }
  6085. case 'e':
  6086. case 'E':
  6087. {
  6088. add(current);
  6089. goto scan_number_exponent;
  6090. }
  6091. default:
  6092. goto scan_number_done;
  6093. }
  6094. scan_number_decimal1:
  6095. // state: we just parsed a decimal point
  6096. number_type = token_type::value_float;
  6097. switch (get())
  6098. {
  6099. case '0':
  6100. case '1':
  6101. case '2':
  6102. case '3':
  6103. case '4':
  6104. case '5':
  6105. case '6':
  6106. case '7':
  6107. case '8':
  6108. case '9':
  6109. {
  6110. add(current);
  6111. goto scan_number_decimal2;
  6112. }
  6113. default:
  6114. {
  6115. error_message = "invalid number; expected digit after '.'";
  6116. return token_type::parse_error;
  6117. }
  6118. }
  6119. scan_number_decimal2:
  6120. // we just parsed at least one number after a decimal point
  6121. switch (get())
  6122. {
  6123. case '0':
  6124. case '1':
  6125. case '2':
  6126. case '3':
  6127. case '4':
  6128. case '5':
  6129. case '6':
  6130. case '7':
  6131. case '8':
  6132. case '9':
  6133. {
  6134. add(current);
  6135. goto scan_number_decimal2;
  6136. }
  6137. case 'e':
  6138. case 'E':
  6139. {
  6140. add(current);
  6141. goto scan_number_exponent;
  6142. }
  6143. default:
  6144. goto scan_number_done;
  6145. }
  6146. scan_number_exponent:
  6147. // we just parsed an exponent
  6148. number_type = token_type::value_float;
  6149. switch (get())
  6150. {
  6151. case '+':
  6152. case '-':
  6153. {
  6154. add(current);
  6155. goto scan_number_sign;
  6156. }
  6157. case '0':
  6158. case '1':
  6159. case '2':
  6160. case '3':
  6161. case '4':
  6162. case '5':
  6163. case '6':
  6164. case '7':
  6165. case '8':
  6166. case '9':
  6167. {
  6168. add(current);
  6169. goto scan_number_any2;
  6170. }
  6171. default:
  6172. {
  6173. error_message =
  6174. "invalid number; expected '+', '-', or digit after exponent";
  6175. return token_type::parse_error;
  6176. }
  6177. }
  6178. scan_number_sign:
  6179. // we just parsed an exponent sign
  6180. switch (get())
  6181. {
  6182. case '0':
  6183. case '1':
  6184. case '2':
  6185. case '3':
  6186. case '4':
  6187. case '5':
  6188. case '6':
  6189. case '7':
  6190. case '8':
  6191. case '9':
  6192. {
  6193. add(current);
  6194. goto scan_number_any2;
  6195. }
  6196. default:
  6197. {
  6198. error_message = "invalid number; expected digit after exponent sign";
  6199. return token_type::parse_error;
  6200. }
  6201. }
  6202. scan_number_any2:
  6203. // we just parsed a number after the exponent or exponent sign
  6204. switch (get())
  6205. {
  6206. case '0':
  6207. case '1':
  6208. case '2':
  6209. case '3':
  6210. case '4':
  6211. case '5':
  6212. case '6':
  6213. case '7':
  6214. case '8':
  6215. case '9':
  6216. {
  6217. add(current);
  6218. goto scan_number_any2;
  6219. }
  6220. default:
  6221. goto scan_number_done;
  6222. }
  6223. scan_number_done:
  6224. // unget the character after the number (we only read it to know that
  6225. // we are done scanning a number)
  6226. unget();
  6227. char* endptr = nullptr;
  6228. errno = 0;
  6229. // try to parse integers first and fall back to floats
  6230. if (number_type == token_type::value_unsigned)
  6231. {
  6232. const auto x = std::strtoull(token_buffer.data(), &endptr, 10);
  6233. // we checked the number format before
  6234. JSON_ASSERT(endptr == token_buffer.data() + token_buffer.size());
  6235. if (errno == 0)
  6236. {
  6237. value_unsigned = static_cast<number_unsigned_t>(x);
  6238. if (value_unsigned == x)
  6239. {
  6240. return token_type::value_unsigned;
  6241. }
  6242. }
  6243. }
  6244. else if (number_type == token_type::value_integer)
  6245. {
  6246. const auto x = std::strtoll(token_buffer.data(), &endptr, 10);
  6247. // we checked the number format before
  6248. JSON_ASSERT(endptr == token_buffer.data() + token_buffer.size());
  6249. if (errno == 0)
  6250. {
  6251. value_integer = static_cast<number_integer_t>(x);
  6252. if (value_integer == x)
  6253. {
  6254. return token_type::value_integer;
  6255. }
  6256. }
  6257. }
  6258. // this code is reached if we parse a floating-point number or if an
  6259. // integer conversion above failed
  6260. strtof(value_float, token_buffer.data(), &endptr);
  6261. // we checked the number format before
  6262. JSON_ASSERT(endptr == token_buffer.data() + token_buffer.size());
  6263. return token_type::value_float;
  6264. }
  6265. /*!
  6266. @param[in] literal_text the literal text to expect
  6267. @param[in] length the length of the passed literal text
  6268. @param[in] return_type the token type to return on success
  6269. */
  6270. JSON_HEDLEY_NON_NULL(2)
  6271. token_type scan_literal(const char_type* literal_text, const std::size_t length,
  6272. token_type return_type)
  6273. {
  6274. JSON_ASSERT(std::char_traits<char_type>::to_char_type(current) == literal_text[0]);
  6275. for (std::size_t i = 1; i < length; ++i)
  6276. {
  6277. if (JSON_HEDLEY_UNLIKELY(std::char_traits<char_type>::to_char_type(get()) != literal_text[i]))
  6278. {
  6279. error_message = "invalid literal";
  6280. return token_type::parse_error;
  6281. }
  6282. }
  6283. return return_type;
  6284. }
  6285. /////////////////////
  6286. // input management
  6287. /////////////////////
  6288. /// reset token_buffer; current character is beginning of token
  6289. void reset() noexcept
  6290. {
  6291. token_buffer.clear();
  6292. token_string.clear();
  6293. token_string.push_back(std::char_traits<char_type>::to_char_type(current));
  6294. }
  6295. /*
  6296. @brief get next character from the input
  6297. This function provides the interface to the used input adapter. It does
  6298. not throw in case the input reached EOF, but returns a
  6299. `std::char_traits<char>::eof()` in that case. Stores the scanned characters
  6300. for use in error messages.
  6301. @return character read from the input
  6302. */
  6303. char_int_type get()
  6304. {
  6305. ++position.chars_read_total;
  6306. ++position.chars_read_current_line;
  6307. if (next_unget)
  6308. {
  6309. // just reset the next_unget variable and work with current
  6310. next_unget = false;
  6311. }
  6312. else
  6313. {
  6314. current = ia.get_character();
  6315. }
  6316. if (JSON_HEDLEY_LIKELY(current != std::char_traits<char_type>::eof()))
  6317. {
  6318. token_string.push_back(std::char_traits<char_type>::to_char_type(current));
  6319. }
  6320. if (current == '\n')
  6321. {
  6322. ++position.lines_read;
  6323. position.chars_read_current_line = 0;
  6324. }
  6325. return current;
  6326. }
  6327. /*!
  6328. @brief unget current character (read it again on next get)
  6329. We implement unget by setting variable next_unget to true. The input is not
  6330. changed - we just simulate ungetting by modifying chars_read_total,
  6331. chars_read_current_line, and token_string. The next call to get() will
  6332. behave as if the unget character is read again.
  6333. */
  6334. void unget()
  6335. {
  6336. next_unget = true;
  6337. --position.chars_read_total;
  6338. // in case we "unget" a newline, we have to also decrement the lines_read
  6339. if (position.chars_read_current_line == 0)
  6340. {
  6341. if (position.lines_read > 0)
  6342. {
  6343. --position.lines_read;
  6344. }
  6345. }
  6346. else
  6347. {
  6348. --position.chars_read_current_line;
  6349. }
  6350. if (JSON_HEDLEY_LIKELY(current != std::char_traits<char_type>::eof()))
  6351. {
  6352. JSON_ASSERT(!token_string.empty());
  6353. token_string.pop_back();
  6354. }
  6355. }
  6356. /// add a character to token_buffer
  6357. void add(char_int_type c)
  6358. {
  6359. token_buffer.push_back(static_cast<typename string_t::value_type>(c));
  6360. }
  6361. public:
  6362. /////////////////////
  6363. // value getters
  6364. /////////////////////
  6365. /// return integer value
  6366. constexpr number_integer_t get_number_integer() const noexcept
  6367. {
  6368. return value_integer;
  6369. }
  6370. /// return unsigned integer value
  6371. constexpr number_unsigned_t get_number_unsigned() const noexcept
  6372. {
  6373. return value_unsigned;
  6374. }
  6375. /// return floating-point value
  6376. constexpr number_float_t get_number_float() const noexcept
  6377. {
  6378. return value_float;
  6379. }
  6380. /// return current string value (implicitly resets the token; useful only once)
  6381. string_t& get_string()
  6382. {
  6383. return token_buffer;
  6384. }
  6385. /////////////////////
  6386. // diagnostics
  6387. /////////////////////
  6388. /// return position of last read token
  6389. constexpr position_t get_position() const noexcept
  6390. {
  6391. return position;
  6392. }
  6393. /// return the last read token (for errors only). Will never contain EOF
  6394. /// (an arbitrary value that is not a valid char value, often -1), because
  6395. /// 255 may legitimately occur. May contain NUL, which should be escaped.
  6396. std::string get_token_string() const
  6397. {
  6398. // escape control characters
  6399. std::string result;
  6400. for (const auto c : token_string)
  6401. {
  6402. if (static_cast<unsigned char>(c) <= '\x1F')
  6403. {
  6404. // escape control characters
  6405. std::array<char, 9> cs{{}};
  6406. (std::snprintf)(cs.data(), cs.size(), "<U+%.4X>", static_cast<unsigned char>(c));
  6407. result += cs.data();
  6408. }
  6409. else
  6410. {
  6411. // add character as is
  6412. result.push_back(static_cast<std::string::value_type>(c));
  6413. }
  6414. }
  6415. return result;
  6416. }
  6417. /// return syntax error message
  6418. JSON_HEDLEY_RETURNS_NON_NULL
  6419. constexpr const char* get_error_message() const noexcept
  6420. {
  6421. return error_message;
  6422. }
  6423. /////////////////////
  6424. // actual scanner
  6425. /////////////////////
  6426. /*!
  6427. @brief skip the UTF-8 byte order mark
  6428. @return true iff there is no BOM or the correct BOM has been skipped
  6429. */
  6430. bool skip_bom()
  6431. {
  6432. if (get() == 0xEF)
  6433. {
  6434. // check if we completely parse the BOM
  6435. return get() == 0xBB && get() == 0xBF;
  6436. }
  6437. // the first character is not the beginning of the BOM; unget it to
  6438. // process is later
  6439. unget();
  6440. return true;
  6441. }
  6442. void skip_whitespace()
  6443. {
  6444. do
  6445. {
  6446. get();
  6447. }
  6448. while (current == ' ' || current == '\t' || current == '\n' || current == '\r');
  6449. }
  6450. token_type scan()
  6451. {
  6452. // initially, skip the BOM
  6453. if (position.chars_read_total == 0 && !skip_bom())
  6454. {
  6455. error_message = "invalid BOM; must be 0xEF 0xBB 0xBF if given";
  6456. return token_type::parse_error;
  6457. }
  6458. // read next character and ignore whitespace
  6459. skip_whitespace();
  6460. // ignore comments
  6461. while (ignore_comments && current == '/')
  6462. {
  6463. if (!scan_comment())
  6464. {
  6465. return token_type::parse_error;
  6466. }
  6467. // skip following whitespace
  6468. skip_whitespace();
  6469. }
  6470. switch (current)
  6471. {
  6472. // structural characters
  6473. case '[':
  6474. return token_type::begin_array;
  6475. case ']':
  6476. return token_type::end_array;
  6477. case '{':
  6478. return token_type::begin_object;
  6479. case '}':
  6480. return token_type::end_object;
  6481. case ':':
  6482. return token_type::name_separator;
  6483. case ',':
  6484. return token_type::value_separator;
  6485. // literals
  6486. case 't':
  6487. {
  6488. std::array<char_type, 4> true_literal = {{'t', 'r', 'u', 'e'}};
  6489. return scan_literal(true_literal.data(), true_literal.size(), token_type::literal_true);
  6490. }
  6491. case 'f':
  6492. {
  6493. std::array<char_type, 5> false_literal = {{'f', 'a', 'l', 's', 'e'}};
  6494. return scan_literal(false_literal.data(), false_literal.size(), token_type::literal_false);
  6495. }
  6496. case 'n':
  6497. {
  6498. std::array<char_type, 4> null_literal = {{'n', 'u', 'l', 'l'}};
  6499. return scan_literal(null_literal.data(), null_literal.size(), token_type::literal_null);
  6500. }
  6501. // string
  6502. case '\"':
  6503. return scan_string();
  6504. // number
  6505. case '-':
  6506. case '0':
  6507. case '1':
  6508. case '2':
  6509. case '3':
  6510. case '4':
  6511. case '5':
  6512. case '6':
  6513. case '7':
  6514. case '8':
  6515. case '9':
  6516. return scan_number();
  6517. // end of input (the null byte is needed when parsing from
  6518. // string literals)
  6519. case '\0':
  6520. case std::char_traits<char_type>::eof():
  6521. return token_type::end_of_input;
  6522. // error
  6523. default:
  6524. error_message = "invalid literal";
  6525. return token_type::parse_error;
  6526. }
  6527. }
  6528. private:
  6529. /// input adapter
  6530. InputAdapterType ia;
  6531. /// whether comments should be ignored (true) or signaled as errors (false)
  6532. const bool ignore_comments = false;
  6533. /// the current character
  6534. char_int_type current = std::char_traits<char_type>::eof();
  6535. /// whether the next get() call should just return current
  6536. bool next_unget = false;
  6537. /// the start position of the current token
  6538. position_t position {};
  6539. /// raw input token string (for error messages)
  6540. std::vector<char_type> token_string {};
  6541. /// buffer for variable-length tokens (numbers, strings)
  6542. string_t token_buffer {};
  6543. /// a description of occurred lexer errors
  6544. const char* error_message = "";
  6545. // number values
  6546. number_integer_t value_integer = 0;
  6547. number_unsigned_t value_unsigned = 0;
  6548. number_float_t value_float = 0;
  6549. /// the decimal point
  6550. const char_int_type decimal_point_char = '.';
  6551. };
  6552. } // namespace detail
  6553. } // namespace nlohmann
  6554. // #include <nlohmann/detail/macro_scope.hpp>
  6555. // #include <nlohmann/detail/meta/is_sax.hpp>
  6556. #include <cstdint> // size_t
  6557. #include <utility> // declval
  6558. #include <string> // string
  6559. // #include <nlohmann/detail/meta/detected.hpp>
  6560. // #include <nlohmann/detail/meta/type_traits.hpp>
  6561. namespace nlohmann
  6562. {
  6563. namespace detail
  6564. {
  6565. template<typename T>
  6566. using null_function_t = decltype(std::declval<T&>().null());
  6567. template<typename T>
  6568. using boolean_function_t =
  6569. decltype(std::declval<T&>().boolean(std::declval<bool>()));
  6570. template<typename T, typename Integer>
  6571. using number_integer_function_t =
  6572. decltype(std::declval<T&>().number_integer(std::declval<Integer>()));
  6573. template<typename T, typename Unsigned>
  6574. using number_unsigned_function_t =
  6575. decltype(std::declval<T&>().number_unsigned(std::declval<Unsigned>()));
  6576. template<typename T, typename Float, typename String>
  6577. using number_float_function_t = decltype(std::declval<T&>().number_float(
  6578. std::declval<Float>(), std::declval<const String&>()));
  6579. template<typename T, typename String>
  6580. using string_function_t =
  6581. decltype(std::declval<T&>().string(std::declval<String&>()));
  6582. template<typename T, typename Binary>
  6583. using binary_function_t =
  6584. decltype(std::declval<T&>().binary(std::declval<Binary&>()));
  6585. template<typename T>
  6586. using start_object_function_t =
  6587. decltype(std::declval<T&>().start_object(std::declval<std::size_t>()));
  6588. template<typename T, typename String>
  6589. using key_function_t =
  6590. decltype(std::declval<T&>().key(std::declval<String&>()));
  6591. template<typename T>
  6592. using end_object_function_t = decltype(std::declval<T&>().end_object());
  6593. template<typename T>
  6594. using start_array_function_t =
  6595. decltype(std::declval<T&>().start_array(std::declval<std::size_t>()));
  6596. template<typename T>
  6597. using end_array_function_t = decltype(std::declval<T&>().end_array());
  6598. template<typename T, typename Exception>
  6599. using parse_error_function_t = decltype(std::declval<T&>().parse_error(
  6600. std::declval<std::size_t>(), std::declval<const std::string&>(),
  6601. std::declval<const Exception&>()));
  6602. template<typename SAX, typename BasicJsonType>
  6603. struct is_sax
  6604. {
  6605. private:
  6606. static_assert(is_basic_json<BasicJsonType>::value,
  6607. "BasicJsonType must be of type basic_json<...>");
  6608. using number_integer_t = typename BasicJsonType::number_integer_t;
  6609. using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
  6610. using number_float_t = typename BasicJsonType::number_float_t;
  6611. using string_t = typename BasicJsonType::string_t;
  6612. using binary_t = typename BasicJsonType::binary_t;
  6613. using exception_t = typename BasicJsonType::exception;
  6614. public:
  6615. static constexpr bool value =
  6616. is_detected_exact<bool, null_function_t, SAX>::value &&
  6617. is_detected_exact<bool, boolean_function_t, SAX>::value &&
  6618. is_detected_exact<bool, number_integer_function_t, SAX, number_integer_t>::value &&
  6619. is_detected_exact<bool, number_unsigned_function_t, SAX, number_unsigned_t>::value &&
  6620. is_detected_exact<bool, number_float_function_t, SAX, number_float_t, string_t>::value &&
  6621. is_detected_exact<bool, string_function_t, SAX, string_t>::value &&
  6622. is_detected_exact<bool, binary_function_t, SAX, binary_t>::value &&
  6623. is_detected_exact<bool, start_object_function_t, SAX>::value &&
  6624. is_detected_exact<bool, key_function_t, SAX, string_t>::value &&
  6625. is_detected_exact<bool, end_object_function_t, SAX>::value &&
  6626. is_detected_exact<bool, start_array_function_t, SAX>::value &&
  6627. is_detected_exact<bool, end_array_function_t, SAX>::value &&
  6628. is_detected_exact<bool, parse_error_function_t, SAX, exception_t>::value;
  6629. };
  6630. template<typename SAX, typename BasicJsonType>
  6631. struct is_sax_static_asserts
  6632. {
  6633. private:
  6634. static_assert(is_basic_json<BasicJsonType>::value,
  6635. "BasicJsonType must be of type basic_json<...>");
  6636. using number_integer_t = typename BasicJsonType::number_integer_t;
  6637. using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
  6638. using number_float_t = typename BasicJsonType::number_float_t;
  6639. using string_t = typename BasicJsonType::string_t;
  6640. using binary_t = typename BasicJsonType::binary_t;
  6641. using exception_t = typename BasicJsonType::exception;
  6642. public:
  6643. static_assert(is_detected_exact<bool, null_function_t, SAX>::value,
  6644. "Missing/invalid function: bool null()");
  6645. static_assert(is_detected_exact<bool, boolean_function_t, SAX>::value,
  6646. "Missing/invalid function: bool boolean(bool)");
  6647. static_assert(is_detected_exact<bool, boolean_function_t, SAX>::value,
  6648. "Missing/invalid function: bool boolean(bool)");
  6649. static_assert(
  6650. is_detected_exact<bool, number_integer_function_t, SAX,
  6651. number_integer_t>::value,
  6652. "Missing/invalid function: bool number_integer(number_integer_t)");
  6653. static_assert(
  6654. is_detected_exact<bool, number_unsigned_function_t, SAX,
  6655. number_unsigned_t>::value,
  6656. "Missing/invalid function: bool number_unsigned(number_unsigned_t)");
  6657. static_assert(is_detected_exact<bool, number_float_function_t, SAX,
  6658. number_float_t, string_t>::value,
  6659. "Missing/invalid function: bool number_float(number_float_t, const string_t&)");
  6660. static_assert(
  6661. is_detected_exact<bool, string_function_t, SAX, string_t>::value,
  6662. "Missing/invalid function: bool string(string_t&)");
  6663. static_assert(
  6664. is_detected_exact<bool, binary_function_t, SAX, binary_t>::value,
  6665. "Missing/invalid function: bool binary(binary_t&)");
  6666. static_assert(is_detected_exact<bool, start_object_function_t, SAX>::value,
  6667. "Missing/invalid function: bool start_object(std::size_t)");
  6668. static_assert(is_detected_exact<bool, key_function_t, SAX, string_t>::value,
  6669. "Missing/invalid function: bool key(string_t&)");
  6670. static_assert(is_detected_exact<bool, end_object_function_t, SAX>::value,
  6671. "Missing/invalid function: bool end_object()");
  6672. static_assert(is_detected_exact<bool, start_array_function_t, SAX>::value,
  6673. "Missing/invalid function: bool start_array(std::size_t)");
  6674. static_assert(is_detected_exact<bool, end_array_function_t, SAX>::value,
  6675. "Missing/invalid function: bool end_array()");
  6676. static_assert(
  6677. is_detected_exact<bool, parse_error_function_t, SAX, exception_t>::value,
  6678. "Missing/invalid function: bool parse_error(std::size_t, const "
  6679. "std::string&, const exception&)");
  6680. };
  6681. } // namespace detail
  6682. } // namespace nlohmann
  6683. // #include <nlohmann/detail/value_t.hpp>
  6684. namespace nlohmann
  6685. {
  6686. namespace detail
  6687. {
  6688. /// how to treat CBOR tags
  6689. enum class cbor_tag_handler_t
  6690. {
  6691. error, ///< throw a parse_error exception in case of a tag
  6692. ignore ///< ignore tags
  6693. };
  6694. /*!
  6695. @brief determine system byte order
  6696. @return true if and only if system's byte order is little endian
  6697. @note from https://stackoverflow.com/a/1001328/266378
  6698. */
  6699. static inline bool little_endianess(int num = 1) noexcept
  6700. {
  6701. return *reinterpret_cast<char*>(&num) == 1;
  6702. }
  6703. ///////////////////
  6704. // binary reader //
  6705. ///////////////////
  6706. /*!
  6707. @brief deserialization of CBOR, MessagePack, and UBJSON values
  6708. */
  6709. template<typename BasicJsonType, typename InputAdapterType, typename SAX = json_sax_dom_parser<BasicJsonType>>
  6710. class binary_reader
  6711. {
  6712. using number_integer_t = typename BasicJsonType::number_integer_t;
  6713. using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
  6714. using number_float_t = typename BasicJsonType::number_float_t;
  6715. using string_t = typename BasicJsonType::string_t;
  6716. using binary_t = typename BasicJsonType::binary_t;
  6717. using json_sax_t = SAX;
  6718. using char_type = typename InputAdapterType::char_type;
  6719. using char_int_type = typename std::char_traits<char_type>::int_type;
  6720. public:
  6721. /*!
  6722. @brief create a binary reader
  6723. @param[in] adapter input adapter to read from
  6724. */
  6725. explicit binary_reader(InputAdapterType&& adapter) : ia(std::move(adapter))
  6726. {
  6727. (void)detail::is_sax_static_asserts<SAX, BasicJsonType> {};
  6728. }
  6729. // make class move-only
  6730. binary_reader(const binary_reader&) = delete;
  6731. binary_reader(binary_reader&&) = default;
  6732. binary_reader& operator=(const binary_reader&) = delete;
  6733. binary_reader& operator=(binary_reader&&) = default;
  6734. ~binary_reader() = default;
  6735. /*!
  6736. @param[in] format the binary format to parse
  6737. @param[in] sax_ a SAX event processor
  6738. @param[in] strict whether to expect the input to be consumed completed
  6739. @param[in] tag_handler how to treat CBOR tags
  6740. @return
  6741. */
  6742. JSON_HEDLEY_NON_NULL(3)
  6743. bool sax_parse(const input_format_t format,
  6744. json_sax_t* sax_,
  6745. const bool strict = true,
  6746. const cbor_tag_handler_t tag_handler = cbor_tag_handler_t::error)
  6747. {
  6748. sax = sax_;
  6749. bool result = false;
  6750. switch (format)
  6751. {
  6752. case input_format_t::bson:
  6753. result = parse_bson_internal();
  6754. break;
  6755. case input_format_t::cbor:
  6756. result = parse_cbor_internal(true, tag_handler);
  6757. break;
  6758. case input_format_t::msgpack:
  6759. result = parse_msgpack_internal();
  6760. break;
  6761. case input_format_t::ubjson:
  6762. result = parse_ubjson_internal();
  6763. break;
  6764. default: // LCOV_EXCL_LINE
  6765. JSON_ASSERT(false); // LCOV_EXCL_LINE
  6766. }
  6767. // strict mode: next byte must be EOF
  6768. if (result && strict)
  6769. {
  6770. if (format == input_format_t::ubjson)
  6771. {
  6772. get_ignore_noop();
  6773. }
  6774. else
  6775. {
  6776. get();
  6777. }
  6778. if (JSON_HEDLEY_UNLIKELY(current != std::char_traits<char_type>::eof()))
  6779. {
  6780. return sax->parse_error(chars_read, get_token_string(),
  6781. parse_error::create(110, chars_read, exception_message(format, "expected end of input; last byte: 0x" + get_token_string(), "value")));
  6782. }
  6783. }
  6784. return result;
  6785. }
  6786. private:
  6787. //////////
  6788. // BSON //
  6789. //////////
  6790. /*!
  6791. @brief Reads in a BSON-object and passes it to the SAX-parser.
  6792. @return whether a valid BSON-value was passed to the SAX parser
  6793. */
  6794. bool parse_bson_internal()
  6795. {
  6796. std::int32_t document_size{};
  6797. get_number<std::int32_t, true>(input_format_t::bson, document_size);
  6798. if (JSON_HEDLEY_UNLIKELY(!sax->start_object(std::size_t(-1))))
  6799. {
  6800. return false;
  6801. }
  6802. if (JSON_HEDLEY_UNLIKELY(!parse_bson_element_list(/*is_array*/false)))
  6803. {
  6804. return false;
  6805. }
  6806. return sax->end_object();
  6807. }
  6808. /*!
  6809. @brief Parses a C-style string from the BSON input.
  6810. @param[in, out] result A reference to the string variable where the read
  6811. string is to be stored.
  6812. @return `true` if the \x00-byte indicating the end of the string was
  6813. encountered before the EOF; false` indicates an unexpected EOF.
  6814. */
  6815. bool get_bson_cstr(string_t& result)
  6816. {
  6817. auto out = std::back_inserter(result);
  6818. while (true)
  6819. {
  6820. get();
  6821. if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(input_format_t::bson, "cstring")))
  6822. {
  6823. return false;
  6824. }
  6825. if (current == 0x00)
  6826. {
  6827. return true;
  6828. }
  6829. *out++ = static_cast<typename string_t::value_type>(current);
  6830. }
  6831. }
  6832. /*!
  6833. @brief Parses a zero-terminated string of length @a len from the BSON
  6834. input.
  6835. @param[in] len The length (including the zero-byte at the end) of the
  6836. string to be read.
  6837. @param[in, out] result A reference to the string variable where the read
  6838. string is to be stored.
  6839. @tparam NumberType The type of the length @a len
  6840. @pre len >= 1
  6841. @return `true` if the string was successfully parsed
  6842. */
  6843. template<typename NumberType>
  6844. bool get_bson_string(const NumberType len, string_t& result)
  6845. {
  6846. if (JSON_HEDLEY_UNLIKELY(len < 1))
  6847. {
  6848. auto last_token = get_token_string();
  6849. 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")));
  6850. }
  6851. return get_string(input_format_t::bson, len - static_cast<NumberType>(1), result) && get() != std::char_traits<char_type>::eof();
  6852. }
  6853. /*!
  6854. @brief Parses a byte array input of length @a len from the BSON input.
  6855. @param[in] len The length of the byte array to be read.
  6856. @param[in, out] result A reference to the binary variable where the read
  6857. array is to be stored.
  6858. @tparam NumberType The type of the length @a len
  6859. @pre len >= 0
  6860. @return `true` if the byte array was successfully parsed
  6861. */
  6862. template<typename NumberType>
  6863. bool get_bson_binary(const NumberType len, binary_t& result)
  6864. {
  6865. if (JSON_HEDLEY_UNLIKELY(len < 0))
  6866. {
  6867. auto last_token = get_token_string();
  6868. 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")));
  6869. }
  6870. // All BSON binary values have a subtype
  6871. std::uint8_t subtype{};
  6872. get_number<std::uint8_t>(input_format_t::bson, subtype);
  6873. result.set_subtype(subtype);
  6874. return get_binary(input_format_t::bson, len, result);
  6875. }
  6876. /*!
  6877. @brief Read a BSON document element of the given @a element_type.
  6878. @param[in] element_type The BSON element type, c.f. http://bsonspec.org/spec.html
  6879. @param[in] element_type_parse_position The position in the input stream,
  6880. where the `element_type` was read.
  6881. @warning Not all BSON element types are supported yet. An unsupported
  6882. @a element_type will give rise to a parse_error.114:
  6883. Unsupported BSON record type 0x...
  6884. @return whether a valid BSON-object/array was passed to the SAX parser
  6885. */
  6886. bool parse_bson_element_internal(const char_int_type element_type,
  6887. const std::size_t element_type_parse_position)
  6888. {
  6889. switch (element_type)
  6890. {
  6891. case 0x01: // double
  6892. {
  6893. double number{};
  6894. return get_number<double, true>(input_format_t::bson, number) && sax->number_float(static_cast<number_float_t>(number), "");
  6895. }
  6896. case 0x02: // string
  6897. {
  6898. std::int32_t len{};
  6899. string_t value;
  6900. return get_number<std::int32_t, true>(input_format_t::bson, len) && get_bson_string(len, value) && sax->string(value);
  6901. }
  6902. case 0x03: // object
  6903. {
  6904. return parse_bson_internal();
  6905. }
  6906. case 0x04: // array
  6907. {
  6908. return parse_bson_array();
  6909. }
  6910. case 0x05: // binary
  6911. {
  6912. std::int32_t len{};
  6913. binary_t value;
  6914. return get_number<std::int32_t, true>(input_format_t::bson, len) && get_bson_binary(len, value) && sax->binary(value);
  6915. }
  6916. case 0x08: // boolean
  6917. {
  6918. return sax->boolean(get() != 0);
  6919. }
  6920. case 0x0A: // null
  6921. {
  6922. return sax->null();
  6923. }
  6924. case 0x10: // int32
  6925. {
  6926. std::int32_t value{};
  6927. return get_number<std::int32_t, true>(input_format_t::bson, value) && sax->number_integer(value);
  6928. }
  6929. case 0x12: // int64
  6930. {
  6931. std::int64_t value{};
  6932. return get_number<std::int64_t, true>(input_format_t::bson, value) && sax->number_integer(value);
  6933. }
  6934. default: // anything else not supported (yet)
  6935. {
  6936. std::array<char, 3> cr{{}};
  6937. (std::snprintf)(cr.data(), cr.size(), "%.2hhX", static_cast<unsigned char>(element_type));
  6938. 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())));
  6939. }
  6940. }
  6941. }
  6942. /*!
  6943. @brief Read a BSON element list (as specified in the BSON-spec)
  6944. The same binary layout is used for objects and arrays, hence it must be
  6945. indicated with the argument @a is_array which one is expected
  6946. (true --> array, false --> object).
  6947. @param[in] is_array Determines if the element list being read is to be
  6948. treated as an object (@a is_array == false), or as an
  6949. array (@a is_array == true).
  6950. @return whether a valid BSON-object/array was passed to the SAX parser
  6951. */
  6952. bool parse_bson_element_list(const bool is_array)
  6953. {
  6954. string_t key;
  6955. while (auto element_type = get())
  6956. {
  6957. if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(input_format_t::bson, "element list")))
  6958. {
  6959. return false;
  6960. }
  6961. const std::size_t element_type_parse_position = chars_read;
  6962. if (JSON_HEDLEY_UNLIKELY(!get_bson_cstr(key)))
  6963. {
  6964. return false;
  6965. }
  6966. if (!is_array && !sax->key(key))
  6967. {
  6968. return false;
  6969. }
  6970. if (JSON_HEDLEY_UNLIKELY(!parse_bson_element_internal(element_type, element_type_parse_position)))
  6971. {
  6972. return false;
  6973. }
  6974. // get_bson_cstr only appends
  6975. key.clear();
  6976. }
  6977. return true;
  6978. }
  6979. /*!
  6980. @brief Reads an array from the BSON input and passes it to the SAX-parser.
  6981. @return whether a valid BSON-array was passed to the SAX parser
  6982. */
  6983. bool parse_bson_array()
  6984. {
  6985. std::int32_t document_size{};
  6986. get_number<std::int32_t, true>(input_format_t::bson, document_size);
  6987. if (JSON_HEDLEY_UNLIKELY(!sax->start_array(std::size_t(-1))))
  6988. {
  6989. return false;
  6990. }
  6991. if (JSON_HEDLEY_UNLIKELY(!parse_bson_element_list(/*is_array*/true)))
  6992. {
  6993. return false;
  6994. }
  6995. return sax->end_array();
  6996. }
  6997. //////////
  6998. // CBOR //
  6999. //////////
  7000. /*!
  7001. @param[in] get_char whether a new character should be retrieved from the
  7002. input (true) or whether the last read character should
  7003. be considered instead (false)
  7004. @param[in] tag_handler how CBOR tags should be treated
  7005. @return whether a valid CBOR value was passed to the SAX parser
  7006. */
  7007. bool parse_cbor_internal(const bool get_char,
  7008. const cbor_tag_handler_t tag_handler)
  7009. {
  7010. switch (get_char ? get() : current)
  7011. {
  7012. // EOF
  7013. case std::char_traits<char_type>::eof():
  7014. return unexpect_eof(input_format_t::cbor, "value");
  7015. // Integer 0x00..0x17 (0..23)
  7016. case 0x00:
  7017. case 0x01:
  7018. case 0x02:
  7019. case 0x03:
  7020. case 0x04:
  7021. case 0x05:
  7022. case 0x06:
  7023. case 0x07:
  7024. case 0x08:
  7025. case 0x09:
  7026. case 0x0A:
  7027. case 0x0B:
  7028. case 0x0C:
  7029. case 0x0D:
  7030. case 0x0E:
  7031. case 0x0F:
  7032. case 0x10:
  7033. case 0x11:
  7034. case 0x12:
  7035. case 0x13:
  7036. case 0x14:
  7037. case 0x15:
  7038. case 0x16:
  7039. case 0x17:
  7040. return sax->number_unsigned(static_cast<number_unsigned_t>(current));
  7041. case 0x18: // Unsigned integer (one-byte uint8_t follows)
  7042. {
  7043. std::uint8_t number{};
  7044. return get_number(input_format_t::cbor, number) && sax->number_unsigned(number);
  7045. }
  7046. case 0x19: // Unsigned integer (two-byte uint16_t follows)
  7047. {
  7048. std::uint16_t number{};
  7049. return get_number(input_format_t::cbor, number) && sax->number_unsigned(number);
  7050. }
  7051. case 0x1A: // Unsigned integer (four-byte uint32_t follows)
  7052. {
  7053. std::uint32_t number{};
  7054. return get_number(input_format_t::cbor, number) && sax->number_unsigned(number);
  7055. }
  7056. case 0x1B: // Unsigned integer (eight-byte uint64_t follows)
  7057. {
  7058. std::uint64_t number{};
  7059. return get_number(input_format_t::cbor, number) && sax->number_unsigned(number);
  7060. }
  7061. // Negative integer -1-0x00..-1-0x17 (-1..-24)
  7062. case 0x20:
  7063. case 0x21:
  7064. case 0x22:
  7065. case 0x23:
  7066. case 0x24:
  7067. case 0x25:
  7068. case 0x26:
  7069. case 0x27:
  7070. case 0x28:
  7071. case 0x29:
  7072. case 0x2A:
  7073. case 0x2B:
  7074. case 0x2C:
  7075. case 0x2D:
  7076. case 0x2E:
  7077. case 0x2F:
  7078. case 0x30:
  7079. case 0x31:
  7080. case 0x32:
  7081. case 0x33:
  7082. case 0x34:
  7083. case 0x35:
  7084. case 0x36:
  7085. case 0x37:
  7086. return sax->number_integer(static_cast<std::int8_t>(0x20 - 1 - current));
  7087. case 0x38: // Negative integer (one-byte uint8_t follows)
  7088. {
  7089. std::uint8_t number{};
  7090. return get_number(input_format_t::cbor, number) && sax->number_integer(static_cast<number_integer_t>(-1) - number);
  7091. }
  7092. case 0x39: // Negative integer -1-n (two-byte uint16_t follows)
  7093. {
  7094. std::uint16_t number{};
  7095. return get_number(input_format_t::cbor, number) && sax->number_integer(static_cast<number_integer_t>(-1) - number);
  7096. }
  7097. case 0x3A: // Negative integer -1-n (four-byte uint32_t follows)
  7098. {
  7099. std::uint32_t number{};
  7100. return get_number(input_format_t::cbor, number) && sax->number_integer(static_cast<number_integer_t>(-1) - number);
  7101. }
  7102. case 0x3B: // Negative integer -1-n (eight-byte uint64_t follows)
  7103. {
  7104. std::uint64_t number{};
  7105. return get_number(input_format_t::cbor, number) && sax->number_integer(static_cast<number_integer_t>(-1)
  7106. - static_cast<number_integer_t>(number));
  7107. }
  7108. // Binary data (0x00..0x17 bytes follow)
  7109. case 0x40:
  7110. case 0x41:
  7111. case 0x42:
  7112. case 0x43:
  7113. case 0x44:
  7114. case 0x45:
  7115. case 0x46:
  7116. case 0x47:
  7117. case 0x48:
  7118. case 0x49:
  7119. case 0x4A:
  7120. case 0x4B:
  7121. case 0x4C:
  7122. case 0x4D:
  7123. case 0x4E:
  7124. case 0x4F:
  7125. case 0x50:
  7126. case 0x51:
  7127. case 0x52:
  7128. case 0x53:
  7129. case 0x54:
  7130. case 0x55:
  7131. case 0x56:
  7132. case 0x57:
  7133. case 0x58: // Binary data (one-byte uint8_t for n follows)
  7134. case 0x59: // Binary data (two-byte uint16_t for n follow)
  7135. case 0x5A: // Binary data (four-byte uint32_t for n follow)
  7136. case 0x5B: // Binary data (eight-byte uint64_t for n follow)
  7137. case 0x5F: // Binary data (indefinite length)
  7138. {
  7139. binary_t b;
  7140. return get_cbor_binary(b) && sax->binary(b);
  7141. }
  7142. // UTF-8 string (0x00..0x17 bytes follow)
  7143. case 0x60:
  7144. case 0x61:
  7145. case 0x62:
  7146. case 0x63:
  7147. case 0x64:
  7148. case 0x65:
  7149. case 0x66:
  7150. case 0x67:
  7151. case 0x68:
  7152. case 0x69:
  7153. case 0x6A:
  7154. case 0x6B:
  7155. case 0x6C:
  7156. case 0x6D:
  7157. case 0x6E:
  7158. case 0x6F:
  7159. case 0x70:
  7160. case 0x71:
  7161. case 0x72:
  7162. case 0x73:
  7163. case 0x74:
  7164. case 0x75:
  7165. case 0x76:
  7166. case 0x77:
  7167. case 0x78: // UTF-8 string (one-byte uint8_t for n follows)
  7168. case 0x79: // UTF-8 string (two-byte uint16_t for n follow)
  7169. case 0x7A: // UTF-8 string (four-byte uint32_t for n follow)
  7170. case 0x7B: // UTF-8 string (eight-byte uint64_t for n follow)
  7171. case 0x7F: // UTF-8 string (indefinite length)
  7172. {
  7173. string_t s;
  7174. return get_cbor_string(s) && sax->string(s);
  7175. }
  7176. // array (0x00..0x17 data items follow)
  7177. case 0x80:
  7178. case 0x81:
  7179. case 0x82:
  7180. case 0x83:
  7181. case 0x84:
  7182. case 0x85:
  7183. case 0x86:
  7184. case 0x87:
  7185. case 0x88:
  7186. case 0x89:
  7187. case 0x8A:
  7188. case 0x8B:
  7189. case 0x8C:
  7190. case 0x8D:
  7191. case 0x8E:
  7192. case 0x8F:
  7193. case 0x90:
  7194. case 0x91:
  7195. case 0x92:
  7196. case 0x93:
  7197. case 0x94:
  7198. case 0x95:
  7199. case 0x96:
  7200. case 0x97:
  7201. return get_cbor_array(static_cast<std::size_t>(static_cast<unsigned int>(current) & 0x1Fu), tag_handler);
  7202. case 0x98: // array (one-byte uint8_t for n follows)
  7203. {
  7204. std::uint8_t len{};
  7205. return get_number(input_format_t::cbor, len) && get_cbor_array(static_cast<std::size_t>(len), tag_handler);
  7206. }
  7207. case 0x99: // array (two-byte uint16_t for n follow)
  7208. {
  7209. std::uint16_t len{};
  7210. return get_number(input_format_t::cbor, len) && get_cbor_array(static_cast<std::size_t>(len), tag_handler);
  7211. }
  7212. case 0x9A: // array (four-byte uint32_t for n follow)
  7213. {
  7214. std::uint32_t len{};
  7215. return get_number(input_format_t::cbor, len) && get_cbor_array(static_cast<std::size_t>(len), tag_handler);
  7216. }
  7217. case 0x9B: // array (eight-byte uint64_t for n follow)
  7218. {
  7219. std::uint64_t len{};
  7220. return get_number(input_format_t::cbor, len) && get_cbor_array(static_cast<std::size_t>(len), tag_handler);
  7221. }
  7222. case 0x9F: // array (indefinite length)
  7223. return get_cbor_array(std::size_t(-1), tag_handler);
  7224. // map (0x00..0x17 pairs of data items follow)
  7225. case 0xA0:
  7226. case 0xA1:
  7227. case 0xA2:
  7228. case 0xA3:
  7229. case 0xA4:
  7230. case 0xA5:
  7231. case 0xA6:
  7232. case 0xA7:
  7233. case 0xA8:
  7234. case 0xA9:
  7235. case 0xAA:
  7236. case 0xAB:
  7237. case 0xAC:
  7238. case 0xAD:
  7239. case 0xAE:
  7240. case 0xAF:
  7241. case 0xB0:
  7242. case 0xB1:
  7243. case 0xB2:
  7244. case 0xB3:
  7245. case 0xB4:
  7246. case 0xB5:
  7247. case 0xB6:
  7248. case 0xB7:
  7249. return get_cbor_object(static_cast<std::size_t>(static_cast<unsigned int>(current) & 0x1Fu), tag_handler);
  7250. case 0xB8: // map (one-byte uint8_t for n follows)
  7251. {
  7252. std::uint8_t len{};
  7253. return get_number(input_format_t::cbor, len) && get_cbor_object(static_cast<std::size_t>(len), tag_handler);
  7254. }
  7255. case 0xB9: // map (two-byte uint16_t for n follow)
  7256. {
  7257. std::uint16_t len{};
  7258. return get_number(input_format_t::cbor, len) && get_cbor_object(static_cast<std::size_t>(len), tag_handler);
  7259. }
  7260. case 0xBA: // map (four-byte uint32_t for n follow)
  7261. {
  7262. std::uint32_t len{};
  7263. return get_number(input_format_t::cbor, len) && get_cbor_object(static_cast<std::size_t>(len), tag_handler);
  7264. }
  7265. case 0xBB: // map (eight-byte uint64_t for n follow)
  7266. {
  7267. std::uint64_t len{};
  7268. return get_number(input_format_t::cbor, len) && get_cbor_object(static_cast<std::size_t>(len), tag_handler);
  7269. }
  7270. case 0xBF: // map (indefinite length)
  7271. return get_cbor_object(std::size_t(-1), tag_handler);
  7272. case 0xC6: // tagged item
  7273. case 0xC7:
  7274. case 0xC8:
  7275. case 0xC9:
  7276. case 0xCA:
  7277. case 0xCB:
  7278. case 0xCC:
  7279. case 0xCD:
  7280. case 0xCE:
  7281. case 0xCF:
  7282. case 0xD0:
  7283. case 0xD1:
  7284. case 0xD2:
  7285. case 0xD3:
  7286. case 0xD4:
  7287. case 0xD8: // tagged item (1 bytes follow)
  7288. case 0xD9: // tagged item (2 bytes follow)
  7289. case 0xDA: // tagged item (4 bytes follow)
  7290. case 0xDB: // tagged item (8 bytes follow)
  7291. {
  7292. switch (tag_handler)
  7293. {
  7294. case cbor_tag_handler_t::error:
  7295. {
  7296. auto last_token = get_token_string();
  7297. 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")));
  7298. }
  7299. case cbor_tag_handler_t::ignore:
  7300. {
  7301. switch (current)
  7302. {
  7303. case 0xD8:
  7304. {
  7305. std::uint8_t len{};
  7306. get_number(input_format_t::cbor, len);
  7307. break;
  7308. }
  7309. case 0xD9:
  7310. {
  7311. std::uint16_t len{};
  7312. get_number(input_format_t::cbor, len);
  7313. break;
  7314. }
  7315. case 0xDA:
  7316. {
  7317. std::uint32_t len{};
  7318. get_number(input_format_t::cbor, len);
  7319. break;
  7320. }
  7321. case 0xDB:
  7322. {
  7323. std::uint64_t len{};
  7324. get_number(input_format_t::cbor, len);
  7325. break;
  7326. }
  7327. default:
  7328. break;
  7329. }
  7330. return parse_cbor_internal(true, tag_handler);
  7331. }
  7332. default: // LCOV_EXCL_LINE
  7333. JSON_ASSERT(false); // LCOV_EXCL_LINE
  7334. }
  7335. }
  7336. case 0xF4: // false
  7337. return sax->boolean(false);
  7338. case 0xF5: // true
  7339. return sax->boolean(true);
  7340. case 0xF6: // null
  7341. return sax->null();
  7342. case 0xF9: // Half-Precision Float (two-byte IEEE 754)
  7343. {
  7344. const auto byte1_raw = get();
  7345. if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(input_format_t::cbor, "number")))
  7346. {
  7347. return false;
  7348. }
  7349. const auto byte2_raw = get();
  7350. if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(input_format_t::cbor, "number")))
  7351. {
  7352. return false;
  7353. }
  7354. const auto byte1 = static_cast<unsigned char>(byte1_raw);
  7355. const auto byte2 = static_cast<unsigned char>(byte2_raw);
  7356. // code from RFC 7049, Appendix D, Figure 3:
  7357. // As half-precision floating-point numbers were only added
  7358. // to IEEE 754 in 2008, today's programming platforms often
  7359. // still only have limited support for them. It is very
  7360. // easy to include at least decoding support for them even
  7361. // without such support. An example of a small decoder for
  7362. // half-precision floating-point numbers in the C language
  7363. // is shown in Fig. 3.
  7364. const auto half = static_cast<unsigned int>((byte1 << 8u) + byte2);
  7365. const double val = [&half]
  7366. {
  7367. const int exp = (half >> 10u) & 0x1Fu;
  7368. const unsigned int mant = half & 0x3FFu;
  7369. JSON_ASSERT(0 <= exp&& exp <= 32);
  7370. JSON_ASSERT(mant <= 1024);
  7371. switch (exp)
  7372. {
  7373. case 0:
  7374. return std::ldexp(mant, -24);
  7375. case 31:
  7376. return (mant == 0)
  7377. ? std::numeric_limits<double>::infinity()
  7378. : std::numeric_limits<double>::quiet_NaN();
  7379. default:
  7380. return std::ldexp(mant + 1024, exp - 25);
  7381. }
  7382. }();
  7383. return sax->number_float((half & 0x8000u) != 0
  7384. ? static_cast<number_float_t>(-val)
  7385. : static_cast<number_float_t>(val), "");
  7386. }
  7387. case 0xFA: // Single-Precision Float (four-byte IEEE 754)
  7388. {
  7389. float number{};
  7390. return get_number(input_format_t::cbor, number) && sax->number_float(static_cast<number_float_t>(number), "");
  7391. }
  7392. case 0xFB: // Double-Precision Float (eight-byte IEEE 754)
  7393. {
  7394. double number{};
  7395. return get_number(input_format_t::cbor, number) && sax->number_float(static_cast<number_float_t>(number), "");
  7396. }
  7397. default: // anything else (0xFF is handled inside the other types)
  7398. {
  7399. auto last_token = get_token_string();
  7400. 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")));
  7401. }
  7402. }
  7403. }
  7404. /*!
  7405. @brief reads a CBOR string
  7406. This function first reads starting bytes to determine the expected
  7407. string length and then copies this number of bytes into a string.
  7408. Additionally, CBOR's strings with indefinite lengths are supported.
  7409. @param[out] result created string
  7410. @return whether string creation completed
  7411. */
  7412. bool get_cbor_string(string_t& result)
  7413. {
  7414. if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(input_format_t::cbor, "string")))
  7415. {
  7416. return false;
  7417. }
  7418. switch (current)
  7419. {
  7420. // UTF-8 string (0x00..0x17 bytes follow)
  7421. case 0x60:
  7422. case 0x61:
  7423. case 0x62:
  7424. case 0x63:
  7425. case 0x64:
  7426. case 0x65:
  7427. case 0x66:
  7428. case 0x67:
  7429. case 0x68:
  7430. case 0x69:
  7431. case 0x6A:
  7432. case 0x6B:
  7433. case 0x6C:
  7434. case 0x6D:
  7435. case 0x6E:
  7436. case 0x6F:
  7437. case 0x70:
  7438. case 0x71:
  7439. case 0x72:
  7440. case 0x73:
  7441. case 0x74:
  7442. case 0x75:
  7443. case 0x76:
  7444. case 0x77:
  7445. {
  7446. return get_string(input_format_t::cbor, static_cast<unsigned int>(current) & 0x1Fu, result);
  7447. }
  7448. case 0x78: // UTF-8 string (one-byte uint8_t for n follows)
  7449. {
  7450. std::uint8_t len{};
  7451. return get_number(input_format_t::cbor, len) && get_string(input_format_t::cbor, len, result);
  7452. }
  7453. case 0x79: // UTF-8 string (two-byte uint16_t for n follow)
  7454. {
  7455. std::uint16_t len{};
  7456. return get_number(input_format_t::cbor, len) && get_string(input_format_t::cbor, len, result);
  7457. }
  7458. case 0x7A: // UTF-8 string (four-byte uint32_t for n follow)
  7459. {
  7460. std::uint32_t len{};
  7461. return get_number(input_format_t::cbor, len) && get_string(input_format_t::cbor, len, result);
  7462. }
  7463. case 0x7B: // UTF-8 string (eight-byte uint64_t for n follow)
  7464. {
  7465. std::uint64_t len{};
  7466. return get_number(input_format_t::cbor, len) && get_string(input_format_t::cbor, len, result);
  7467. }
  7468. case 0x7F: // UTF-8 string (indefinite length)
  7469. {
  7470. while (get() != 0xFF)
  7471. {
  7472. string_t chunk;
  7473. if (!get_cbor_string(chunk))
  7474. {
  7475. return false;
  7476. }
  7477. result.append(chunk);
  7478. }
  7479. return true;
  7480. }
  7481. default:
  7482. {
  7483. auto last_token = get_token_string();
  7484. 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")));
  7485. }
  7486. }
  7487. }
  7488. /*!
  7489. @brief reads a CBOR byte array
  7490. This function first reads starting bytes to determine the expected
  7491. byte array length and then copies this number of bytes into the byte array.
  7492. Additionally, CBOR's byte arrays with indefinite lengths are supported.
  7493. @param[out] result created byte array
  7494. @return whether byte array creation completed
  7495. */
  7496. bool get_cbor_binary(binary_t& result)
  7497. {
  7498. if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(input_format_t::cbor, "binary")))
  7499. {
  7500. return false;
  7501. }
  7502. switch (current)
  7503. {
  7504. // Binary data (0x00..0x17 bytes follow)
  7505. case 0x40:
  7506. case 0x41:
  7507. case 0x42:
  7508. case 0x43:
  7509. case 0x44:
  7510. case 0x45:
  7511. case 0x46:
  7512. case 0x47:
  7513. case 0x48:
  7514. case 0x49:
  7515. case 0x4A:
  7516. case 0x4B:
  7517. case 0x4C:
  7518. case 0x4D:
  7519. case 0x4E:
  7520. case 0x4F:
  7521. case 0x50:
  7522. case 0x51:
  7523. case 0x52:
  7524. case 0x53:
  7525. case 0x54:
  7526. case 0x55:
  7527. case 0x56:
  7528. case 0x57:
  7529. {
  7530. return get_binary(input_format_t::cbor, static_cast<unsigned int>(current) & 0x1Fu, result);
  7531. }
  7532. case 0x58: // Binary data (one-byte uint8_t for n follows)
  7533. {
  7534. std::uint8_t len{};
  7535. return get_number(input_format_t::cbor, len) &&
  7536. get_binary(input_format_t::cbor, len, result);
  7537. }
  7538. case 0x59: // Binary data (two-byte uint16_t for n follow)
  7539. {
  7540. std::uint16_t len{};
  7541. return get_number(input_format_t::cbor, len) &&
  7542. get_binary(input_format_t::cbor, len, result);
  7543. }
  7544. case 0x5A: // Binary data (four-byte uint32_t for n follow)
  7545. {
  7546. std::uint32_t len{};
  7547. return get_number(input_format_t::cbor, len) &&
  7548. get_binary(input_format_t::cbor, len, result);
  7549. }
  7550. case 0x5B: // Binary data (eight-byte uint64_t for n follow)
  7551. {
  7552. std::uint64_t len{};
  7553. return get_number(input_format_t::cbor, len) &&
  7554. get_binary(input_format_t::cbor, len, result);
  7555. }
  7556. case 0x5F: // Binary data (indefinite length)
  7557. {
  7558. while (get() != 0xFF)
  7559. {
  7560. binary_t chunk;
  7561. if (!get_cbor_binary(chunk))
  7562. {
  7563. return false;
  7564. }
  7565. result.insert(result.end(), chunk.begin(), chunk.end());
  7566. }
  7567. return true;
  7568. }
  7569. default:
  7570. {
  7571. auto last_token = get_token_string();
  7572. 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")));
  7573. }
  7574. }
  7575. }
  7576. /*!
  7577. @param[in] len the length of the array or std::size_t(-1) for an
  7578. array of indefinite size
  7579. @param[in] tag_handler how CBOR tags should be treated
  7580. @return whether array creation completed
  7581. */
  7582. bool get_cbor_array(const std::size_t len,
  7583. const cbor_tag_handler_t tag_handler)
  7584. {
  7585. if (JSON_HEDLEY_UNLIKELY(!sax->start_array(len)))
  7586. {
  7587. return false;
  7588. }
  7589. if (len != std::size_t(-1))
  7590. {
  7591. for (std::size_t i = 0; i < len; ++i)
  7592. {
  7593. if (JSON_HEDLEY_UNLIKELY(!parse_cbor_internal(true, tag_handler)))
  7594. {
  7595. return false;
  7596. }
  7597. }
  7598. }
  7599. else
  7600. {
  7601. while (get() != 0xFF)
  7602. {
  7603. if (JSON_HEDLEY_UNLIKELY(!parse_cbor_internal(false, tag_handler)))
  7604. {
  7605. return false;
  7606. }
  7607. }
  7608. }
  7609. return sax->end_array();
  7610. }
  7611. /*!
  7612. @param[in] len the length of the object or std::size_t(-1) for an
  7613. object of indefinite size
  7614. @param[in] tag_handler how CBOR tags should be treated
  7615. @return whether object creation completed
  7616. */
  7617. bool get_cbor_object(const std::size_t len,
  7618. const cbor_tag_handler_t tag_handler)
  7619. {
  7620. if (JSON_HEDLEY_UNLIKELY(!sax->start_object(len)))
  7621. {
  7622. return false;
  7623. }
  7624. string_t key;
  7625. if (len != std::size_t(-1))
  7626. {
  7627. for (std::size_t i = 0; i < len; ++i)
  7628. {
  7629. get();
  7630. if (JSON_HEDLEY_UNLIKELY(!get_cbor_string(key) || !sax->key(key)))
  7631. {
  7632. return false;
  7633. }
  7634. if (JSON_HEDLEY_UNLIKELY(!parse_cbor_internal(true, tag_handler)))
  7635. {
  7636. return false;
  7637. }
  7638. key.clear();
  7639. }
  7640. }
  7641. else
  7642. {
  7643. while (get() != 0xFF)
  7644. {
  7645. if (JSON_HEDLEY_UNLIKELY(!get_cbor_string(key) || !sax->key(key)))
  7646. {
  7647. return false;
  7648. }
  7649. if (JSON_HEDLEY_UNLIKELY(!parse_cbor_internal(true, tag_handler)))
  7650. {
  7651. return false;
  7652. }
  7653. key.clear();
  7654. }
  7655. }
  7656. return sax->end_object();
  7657. }
  7658. /////////////
  7659. // MsgPack //
  7660. /////////////
  7661. /*!
  7662. @return whether a valid MessagePack value was passed to the SAX parser
  7663. */
  7664. bool parse_msgpack_internal()
  7665. {
  7666. switch (get())
  7667. {
  7668. // EOF
  7669. case std::char_traits<char_type>::eof():
  7670. return unexpect_eof(input_format_t::msgpack, "value");
  7671. // positive fixint
  7672. case 0x00:
  7673. case 0x01:
  7674. case 0x02:
  7675. case 0x03:
  7676. case 0x04:
  7677. case 0x05:
  7678. case 0x06:
  7679. case 0x07:
  7680. case 0x08:
  7681. case 0x09:
  7682. case 0x0A:
  7683. case 0x0B:
  7684. case 0x0C:
  7685. case 0x0D:
  7686. case 0x0E:
  7687. case 0x0F:
  7688. case 0x10:
  7689. case 0x11:
  7690. case 0x12:
  7691. case 0x13:
  7692. case 0x14:
  7693. case 0x15:
  7694. case 0x16:
  7695. case 0x17:
  7696. case 0x18:
  7697. case 0x19:
  7698. case 0x1A:
  7699. case 0x1B:
  7700. case 0x1C:
  7701. case 0x1D:
  7702. case 0x1E:
  7703. case 0x1F:
  7704. case 0x20:
  7705. case 0x21:
  7706. case 0x22:
  7707. case 0x23:
  7708. case 0x24:
  7709. case 0x25:
  7710. case 0x26:
  7711. case 0x27:
  7712. case 0x28:
  7713. case 0x29:
  7714. case 0x2A:
  7715. case 0x2B:
  7716. case 0x2C:
  7717. case 0x2D:
  7718. case 0x2E:
  7719. case 0x2F:
  7720. case 0x30:
  7721. case 0x31:
  7722. case 0x32:
  7723. case 0x33:
  7724. case 0x34:
  7725. case 0x35:
  7726. case 0x36:
  7727. case 0x37:
  7728. case 0x38:
  7729. case 0x39:
  7730. case 0x3A:
  7731. case 0x3B:
  7732. case 0x3C:
  7733. case 0x3D:
  7734. case 0x3E:
  7735. case 0x3F:
  7736. case 0x40:
  7737. case 0x41:
  7738. case 0x42:
  7739. case 0x43:
  7740. case 0x44:
  7741. case 0x45:
  7742. case 0x46:
  7743. case 0x47:
  7744. case 0x48:
  7745. case 0x49:
  7746. case 0x4A:
  7747. case 0x4B:
  7748. case 0x4C:
  7749. case 0x4D:
  7750. case 0x4E:
  7751. case 0x4F:
  7752. case 0x50:
  7753. case 0x51:
  7754. case 0x52:
  7755. case 0x53:
  7756. case 0x54:
  7757. case 0x55:
  7758. case 0x56:
  7759. case 0x57:
  7760. case 0x58:
  7761. case 0x59:
  7762. case 0x5A:
  7763. case 0x5B:
  7764. case 0x5C:
  7765. case 0x5D:
  7766. case 0x5E:
  7767. case 0x5F:
  7768. case 0x60:
  7769. case 0x61:
  7770. case 0x62:
  7771. case 0x63:
  7772. case 0x64:
  7773. case 0x65:
  7774. case 0x66:
  7775. case 0x67:
  7776. case 0x68:
  7777. case 0x69:
  7778. case 0x6A:
  7779. case 0x6B:
  7780. case 0x6C:
  7781. case 0x6D:
  7782. case 0x6E:
  7783. case 0x6F:
  7784. case 0x70:
  7785. case 0x71:
  7786. case 0x72:
  7787. case 0x73:
  7788. case 0x74:
  7789. case 0x75:
  7790. case 0x76:
  7791. case 0x77:
  7792. case 0x78:
  7793. case 0x79:
  7794. case 0x7A:
  7795. case 0x7B:
  7796. case 0x7C:
  7797. case 0x7D:
  7798. case 0x7E:
  7799. case 0x7F:
  7800. return sax->number_unsigned(static_cast<number_unsigned_t>(current));
  7801. // fixmap
  7802. case 0x80:
  7803. case 0x81:
  7804. case 0x82:
  7805. case 0x83:
  7806. case 0x84:
  7807. case 0x85:
  7808. case 0x86:
  7809. case 0x87:
  7810. case 0x88:
  7811. case 0x89:
  7812. case 0x8A:
  7813. case 0x8B:
  7814. case 0x8C:
  7815. case 0x8D:
  7816. case 0x8E:
  7817. case 0x8F:
  7818. return get_msgpack_object(static_cast<std::size_t>(static_cast<unsigned int>(current) & 0x0Fu));
  7819. // fixarray
  7820. case 0x90:
  7821. case 0x91:
  7822. case 0x92:
  7823. case 0x93:
  7824. case 0x94:
  7825. case 0x95:
  7826. case 0x96:
  7827. case 0x97:
  7828. case 0x98:
  7829. case 0x99:
  7830. case 0x9A:
  7831. case 0x9B:
  7832. case 0x9C:
  7833. case 0x9D:
  7834. case 0x9E:
  7835. case 0x9F:
  7836. return get_msgpack_array(static_cast<std::size_t>(static_cast<unsigned int>(current) & 0x0Fu));
  7837. // fixstr
  7838. case 0xA0:
  7839. case 0xA1:
  7840. case 0xA2:
  7841. case 0xA3:
  7842. case 0xA4:
  7843. case 0xA5:
  7844. case 0xA6:
  7845. case 0xA7:
  7846. case 0xA8:
  7847. case 0xA9:
  7848. case 0xAA:
  7849. case 0xAB:
  7850. case 0xAC:
  7851. case 0xAD:
  7852. case 0xAE:
  7853. case 0xAF:
  7854. case 0xB0:
  7855. case 0xB1:
  7856. case 0xB2:
  7857. case 0xB3:
  7858. case 0xB4:
  7859. case 0xB5:
  7860. case 0xB6:
  7861. case 0xB7:
  7862. case 0xB8:
  7863. case 0xB9:
  7864. case 0xBA:
  7865. case 0xBB:
  7866. case 0xBC:
  7867. case 0xBD:
  7868. case 0xBE:
  7869. case 0xBF:
  7870. case 0xD9: // str 8
  7871. case 0xDA: // str 16
  7872. case 0xDB: // str 32
  7873. {
  7874. string_t s;
  7875. return get_msgpack_string(s) && sax->string(s);
  7876. }
  7877. case 0xC0: // nil
  7878. return sax->null();
  7879. case 0xC2: // false
  7880. return sax->boolean(false);
  7881. case 0xC3: // true
  7882. return sax->boolean(true);
  7883. case 0xC4: // bin 8
  7884. case 0xC5: // bin 16
  7885. case 0xC6: // bin 32
  7886. case 0xC7: // ext 8
  7887. case 0xC8: // ext 16
  7888. case 0xC9: // ext 32
  7889. case 0xD4: // fixext 1
  7890. case 0xD5: // fixext 2
  7891. case 0xD6: // fixext 4
  7892. case 0xD7: // fixext 8
  7893. case 0xD8: // fixext 16
  7894. {
  7895. binary_t b;
  7896. return get_msgpack_binary(b) && sax->binary(b);
  7897. }
  7898. case 0xCA: // float 32
  7899. {
  7900. float number{};
  7901. return get_number(input_format_t::msgpack, number) && sax->number_float(static_cast<number_float_t>(number), "");
  7902. }
  7903. case 0xCB: // float 64
  7904. {
  7905. double number{};
  7906. return get_number(input_format_t::msgpack, number) && sax->number_float(static_cast<number_float_t>(number), "");
  7907. }
  7908. case 0xCC: // uint 8
  7909. {
  7910. std::uint8_t number{};
  7911. return get_number(input_format_t::msgpack, number) && sax->number_unsigned(number);
  7912. }
  7913. case 0xCD: // uint 16
  7914. {
  7915. std::uint16_t number{};
  7916. return get_number(input_format_t::msgpack, number) && sax->number_unsigned(number);
  7917. }
  7918. case 0xCE: // uint 32
  7919. {
  7920. std::uint32_t number{};
  7921. return get_number(input_format_t::msgpack, number) && sax->number_unsigned(number);
  7922. }
  7923. case 0xCF: // uint 64
  7924. {
  7925. std::uint64_t number{};
  7926. return get_number(input_format_t::msgpack, number) && sax->number_unsigned(number);
  7927. }
  7928. case 0xD0: // int 8
  7929. {
  7930. std::int8_t number{};
  7931. return get_number(input_format_t::msgpack, number) && sax->number_integer(number);
  7932. }
  7933. case 0xD1: // int 16
  7934. {
  7935. std::int16_t number{};
  7936. return get_number(input_format_t::msgpack, number) && sax->number_integer(number);
  7937. }
  7938. case 0xD2: // int 32
  7939. {
  7940. std::int32_t number{};
  7941. return get_number(input_format_t::msgpack, number) && sax->number_integer(number);
  7942. }
  7943. case 0xD3: // int 64
  7944. {
  7945. std::int64_t number{};
  7946. return get_number(input_format_t::msgpack, number) && sax->number_integer(number);
  7947. }
  7948. case 0xDC: // array 16
  7949. {
  7950. std::uint16_t len{};
  7951. return get_number(input_format_t::msgpack, len) && get_msgpack_array(static_cast<std::size_t>(len));
  7952. }
  7953. case 0xDD: // array 32
  7954. {
  7955. std::uint32_t len{};
  7956. return get_number(input_format_t::msgpack, len) && get_msgpack_array(static_cast<std::size_t>(len));
  7957. }
  7958. case 0xDE: // map 16
  7959. {
  7960. std::uint16_t len{};
  7961. return get_number(input_format_t::msgpack, len) && get_msgpack_object(static_cast<std::size_t>(len));
  7962. }
  7963. case 0xDF: // map 32
  7964. {
  7965. std::uint32_t len{};
  7966. return get_number(input_format_t::msgpack, len) && get_msgpack_object(static_cast<std::size_t>(len));
  7967. }
  7968. // negative fixint
  7969. case 0xE0:
  7970. case 0xE1:
  7971. case 0xE2:
  7972. case 0xE3:
  7973. case 0xE4:
  7974. case 0xE5:
  7975. case 0xE6:
  7976. case 0xE7:
  7977. case 0xE8:
  7978. case 0xE9:
  7979. case 0xEA:
  7980. case 0xEB:
  7981. case 0xEC:
  7982. case 0xED:
  7983. case 0xEE:
  7984. case 0xEF:
  7985. case 0xF0:
  7986. case 0xF1:
  7987. case 0xF2:
  7988. case 0xF3:
  7989. case 0xF4:
  7990. case 0xF5:
  7991. case 0xF6:
  7992. case 0xF7:
  7993. case 0xF8:
  7994. case 0xF9:
  7995. case 0xFA:
  7996. case 0xFB:
  7997. case 0xFC:
  7998. case 0xFD:
  7999. case 0xFE:
  8000. case 0xFF:
  8001. return sax->number_integer(static_cast<std::int8_t>(current));
  8002. default: // anything else
  8003. {
  8004. auto last_token = get_token_string();
  8005. 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")));
  8006. }
  8007. }
  8008. }
  8009. /*!
  8010. @brief reads a MessagePack string
  8011. This function first reads starting bytes to determine the expected
  8012. string length and then copies this number of bytes into a string.
  8013. @param[out] result created string
  8014. @return whether string creation completed
  8015. */
  8016. bool get_msgpack_string(string_t& result)
  8017. {
  8018. if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(input_format_t::msgpack, "string")))
  8019. {
  8020. return false;
  8021. }
  8022. switch (current)
  8023. {
  8024. // fixstr
  8025. case 0xA0:
  8026. case 0xA1:
  8027. case 0xA2:
  8028. case 0xA3:
  8029. case 0xA4:
  8030. case 0xA5:
  8031. case 0xA6:
  8032. case 0xA7:
  8033. case 0xA8:
  8034. case 0xA9:
  8035. case 0xAA:
  8036. case 0xAB:
  8037. case 0xAC:
  8038. case 0xAD:
  8039. case 0xAE:
  8040. case 0xAF:
  8041. case 0xB0:
  8042. case 0xB1:
  8043. case 0xB2:
  8044. case 0xB3:
  8045. case 0xB4:
  8046. case 0xB5:
  8047. case 0xB6:
  8048. case 0xB7:
  8049. case 0xB8:
  8050. case 0xB9:
  8051. case 0xBA:
  8052. case 0xBB:
  8053. case 0xBC:
  8054. case 0xBD:
  8055. case 0xBE:
  8056. case 0xBF:
  8057. {
  8058. return get_string(input_format_t::msgpack, static_cast<unsigned int>(current) & 0x1Fu, result);
  8059. }
  8060. case 0xD9: // str 8
  8061. {
  8062. std::uint8_t len{};
  8063. return get_number(input_format_t::msgpack, len) && get_string(input_format_t::msgpack, len, result);
  8064. }
  8065. case 0xDA: // str 16
  8066. {
  8067. std::uint16_t len{};
  8068. return get_number(input_format_t::msgpack, len) && get_string(input_format_t::msgpack, len, result);
  8069. }
  8070. case 0xDB: // str 32
  8071. {
  8072. std::uint32_t len{};
  8073. return get_number(input_format_t::msgpack, len) && get_string(input_format_t::msgpack, len, result);
  8074. }
  8075. default:
  8076. {
  8077. auto last_token = get_token_string();
  8078. 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")));
  8079. }
  8080. }
  8081. }
  8082. /*!
  8083. @brief reads a MessagePack byte array
  8084. This function first reads starting bytes to determine the expected
  8085. byte array length and then copies this number of bytes into a byte array.
  8086. @param[out] result created byte array
  8087. @return whether byte array creation completed
  8088. */
  8089. bool get_msgpack_binary(binary_t& result)
  8090. {
  8091. // helper function to set the subtype
  8092. auto assign_and_return_true = [&result](std::int8_t subtype)
  8093. {
  8094. result.set_subtype(static_cast<std::uint8_t>(subtype));
  8095. return true;
  8096. };
  8097. switch (current)
  8098. {
  8099. case 0xC4: // bin 8
  8100. {
  8101. std::uint8_t len{};
  8102. return get_number(input_format_t::msgpack, len) &&
  8103. get_binary(input_format_t::msgpack, len, result);
  8104. }
  8105. case 0xC5: // bin 16
  8106. {
  8107. std::uint16_t len{};
  8108. return get_number(input_format_t::msgpack, len) &&
  8109. get_binary(input_format_t::msgpack, len, result);
  8110. }
  8111. case 0xC6: // bin 32
  8112. {
  8113. std::uint32_t len{};
  8114. return get_number(input_format_t::msgpack, len) &&
  8115. get_binary(input_format_t::msgpack, len, result);
  8116. }
  8117. case 0xC7: // ext 8
  8118. {
  8119. std::uint8_t len{};
  8120. std::int8_t subtype{};
  8121. return get_number(input_format_t::msgpack, len) &&
  8122. get_number(input_format_t::msgpack, subtype) &&
  8123. get_binary(input_format_t::msgpack, len, result) &&
  8124. assign_and_return_true(subtype);
  8125. }
  8126. case 0xC8: // ext 16
  8127. {
  8128. std::uint16_t len{};
  8129. std::int8_t subtype{};
  8130. return get_number(input_format_t::msgpack, len) &&
  8131. get_number(input_format_t::msgpack, subtype) &&
  8132. get_binary(input_format_t::msgpack, len, result) &&
  8133. assign_and_return_true(subtype);
  8134. }
  8135. case 0xC9: // ext 32
  8136. {
  8137. std::uint32_t len{};
  8138. std::int8_t subtype{};
  8139. return get_number(input_format_t::msgpack, len) &&
  8140. get_number(input_format_t::msgpack, subtype) &&
  8141. get_binary(input_format_t::msgpack, len, result) &&
  8142. assign_and_return_true(subtype);
  8143. }
  8144. case 0xD4: // fixext 1
  8145. {
  8146. std::int8_t subtype{};
  8147. return get_number(input_format_t::msgpack, subtype) &&
  8148. get_binary(input_format_t::msgpack, 1, result) &&
  8149. assign_and_return_true(subtype);
  8150. }
  8151. case 0xD5: // fixext 2
  8152. {
  8153. std::int8_t subtype{};
  8154. return get_number(input_format_t::msgpack, subtype) &&
  8155. get_binary(input_format_t::msgpack, 2, result) &&
  8156. assign_and_return_true(subtype);
  8157. }
  8158. case 0xD6: // fixext 4
  8159. {
  8160. std::int8_t subtype{};
  8161. return get_number(input_format_t::msgpack, subtype) &&
  8162. get_binary(input_format_t::msgpack, 4, result) &&
  8163. assign_and_return_true(subtype);
  8164. }
  8165. case 0xD7: // fixext 8
  8166. {
  8167. std::int8_t subtype{};
  8168. return get_number(input_format_t::msgpack, subtype) &&
  8169. get_binary(input_format_t::msgpack, 8, result) &&
  8170. assign_and_return_true(subtype);
  8171. }
  8172. case 0xD8: // fixext 16
  8173. {
  8174. std::int8_t subtype{};
  8175. return get_number(input_format_t::msgpack, subtype) &&
  8176. get_binary(input_format_t::msgpack, 16, result) &&
  8177. assign_and_return_true(subtype);
  8178. }
  8179. default: // LCOV_EXCL_LINE
  8180. return false; // LCOV_EXCL_LINE
  8181. }
  8182. }
  8183. /*!
  8184. @param[in] len the length of the array
  8185. @return whether array creation completed
  8186. */
  8187. bool get_msgpack_array(const std::size_t len)
  8188. {
  8189. if (JSON_HEDLEY_UNLIKELY(!sax->start_array(len)))
  8190. {
  8191. return false;
  8192. }
  8193. for (std::size_t i = 0; i < len; ++i)
  8194. {
  8195. if (JSON_HEDLEY_UNLIKELY(!parse_msgpack_internal()))
  8196. {
  8197. return false;
  8198. }
  8199. }
  8200. return sax->end_array();
  8201. }
  8202. /*!
  8203. @param[in] len the length of the object
  8204. @return whether object creation completed
  8205. */
  8206. bool get_msgpack_object(const std::size_t len)
  8207. {
  8208. if (JSON_HEDLEY_UNLIKELY(!sax->start_object(len)))
  8209. {
  8210. return false;
  8211. }
  8212. string_t key;
  8213. for (std::size_t i = 0; i < len; ++i)
  8214. {
  8215. get();
  8216. if (JSON_HEDLEY_UNLIKELY(!get_msgpack_string(key) || !sax->key(key)))
  8217. {
  8218. return false;
  8219. }
  8220. if (JSON_HEDLEY_UNLIKELY(!parse_msgpack_internal()))
  8221. {
  8222. return false;
  8223. }
  8224. key.clear();
  8225. }
  8226. return sax->end_object();
  8227. }
  8228. ////////////
  8229. // UBJSON //
  8230. ////////////
  8231. /*!
  8232. @param[in] get_char whether a new character should be retrieved from the
  8233. input (true, default) or whether the last read
  8234. character should be considered instead
  8235. @return whether a valid UBJSON value was passed to the SAX parser
  8236. */
  8237. bool parse_ubjson_internal(const bool get_char = true)
  8238. {
  8239. return get_ubjson_value(get_char ? get_ignore_noop() : current);
  8240. }
  8241. /*!
  8242. @brief reads a UBJSON string
  8243. This function is either called after reading the 'S' byte explicitly
  8244. indicating a string, or in case of an object key where the 'S' byte can be
  8245. left out.
  8246. @param[out] result created string
  8247. @param[in] get_char whether a new character should be retrieved from the
  8248. input (true, default) or whether the last read
  8249. character should be considered instead
  8250. @return whether string creation completed
  8251. */
  8252. bool get_ubjson_string(string_t& result, const bool get_char = true)
  8253. {
  8254. if (get_char)
  8255. {
  8256. get(); // TODO(niels): may we ignore N here?
  8257. }
  8258. if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(input_format_t::ubjson, "value")))
  8259. {
  8260. return false;
  8261. }
  8262. switch (current)
  8263. {
  8264. case 'U':
  8265. {
  8266. std::uint8_t len{};
  8267. return get_number(input_format_t::ubjson, len) && get_string(input_format_t::ubjson, len, result);
  8268. }
  8269. case 'i':
  8270. {
  8271. std::int8_t len{};
  8272. return get_number(input_format_t::ubjson, len) && get_string(input_format_t::ubjson, len, result);
  8273. }
  8274. case 'I':
  8275. {
  8276. std::int16_t len{};
  8277. return get_number(input_format_t::ubjson, len) && get_string(input_format_t::ubjson, len, result);
  8278. }
  8279. case 'l':
  8280. {
  8281. std::int32_t len{};
  8282. return get_number(input_format_t::ubjson, len) && get_string(input_format_t::ubjson, len, result);
  8283. }
  8284. case 'L':
  8285. {
  8286. std::int64_t len{};
  8287. return get_number(input_format_t::ubjson, len) && get_string(input_format_t::ubjson, len, result);
  8288. }
  8289. default:
  8290. auto last_token = get_token_string();
  8291. 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")));
  8292. }
  8293. }
  8294. /*!
  8295. @param[out] result determined size
  8296. @return whether size determination completed
  8297. */
  8298. bool get_ubjson_size_value(std::size_t& result)
  8299. {
  8300. switch (get_ignore_noop())
  8301. {
  8302. case 'U':
  8303. {
  8304. std::uint8_t number{};
  8305. if (JSON_HEDLEY_UNLIKELY(!get_number(input_format_t::ubjson, number)))
  8306. {
  8307. return false;
  8308. }
  8309. result = static_cast<std::size_t>(number);
  8310. return true;
  8311. }
  8312. case 'i':
  8313. {
  8314. std::int8_t number{};
  8315. if (JSON_HEDLEY_UNLIKELY(!get_number(input_format_t::ubjson, number)))
  8316. {
  8317. return false;
  8318. }
  8319. result = static_cast<std::size_t>(number);
  8320. return true;
  8321. }
  8322. case 'I':
  8323. {
  8324. std::int16_t number{};
  8325. if (JSON_HEDLEY_UNLIKELY(!get_number(input_format_t::ubjson, number)))
  8326. {
  8327. return false;
  8328. }
  8329. result = static_cast<std::size_t>(number);
  8330. return true;
  8331. }
  8332. case 'l':
  8333. {
  8334. std::int32_t number{};
  8335. if (JSON_HEDLEY_UNLIKELY(!get_number(input_format_t::ubjson, number)))
  8336. {
  8337. return false;
  8338. }
  8339. result = static_cast<std::size_t>(number);
  8340. return true;
  8341. }
  8342. case 'L':
  8343. {
  8344. std::int64_t number{};
  8345. if (JSON_HEDLEY_UNLIKELY(!get_number(input_format_t::ubjson, number)))
  8346. {
  8347. return false;
  8348. }
  8349. result = static_cast<std::size_t>(number);
  8350. return true;
  8351. }
  8352. default:
  8353. {
  8354. auto last_token = get_token_string();
  8355. 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")));
  8356. }
  8357. }
  8358. }
  8359. /*!
  8360. @brief determine the type and size for a container
  8361. In the optimized UBJSON format, a type and a size can be provided to allow
  8362. for a more compact representation.
  8363. @param[out] result pair of the size and the type
  8364. @return whether pair creation completed
  8365. */
  8366. bool get_ubjson_size_type(std::pair<std::size_t, char_int_type>& result)
  8367. {
  8368. result.first = string_t::npos; // size
  8369. result.second = 0; // type
  8370. get_ignore_noop();
  8371. if (current == '$')
  8372. {
  8373. result.second = get(); // must not ignore 'N', because 'N' maybe the type
  8374. if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(input_format_t::ubjson, "type")))
  8375. {
  8376. return false;
  8377. }
  8378. get_ignore_noop();
  8379. if (JSON_HEDLEY_UNLIKELY(current != '#'))
  8380. {
  8381. if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(input_format_t::ubjson, "value")))
  8382. {
  8383. return false;
  8384. }
  8385. auto last_token = get_token_string();
  8386. 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")));
  8387. }
  8388. return get_ubjson_size_value(result.first);
  8389. }
  8390. if (current == '#')
  8391. {
  8392. return get_ubjson_size_value(result.first);
  8393. }
  8394. return true;
  8395. }
  8396. /*!
  8397. @param prefix the previously read or set type prefix
  8398. @return whether value creation completed
  8399. */
  8400. bool get_ubjson_value(const char_int_type prefix)
  8401. {
  8402. switch (prefix)
  8403. {
  8404. case std::char_traits<char_type>::eof(): // EOF
  8405. return unexpect_eof(input_format_t::ubjson, "value");
  8406. case 'T': // true
  8407. return sax->boolean(true);
  8408. case 'F': // false
  8409. return sax->boolean(false);
  8410. case 'Z': // null
  8411. return sax->null();
  8412. case 'U':
  8413. {
  8414. std::uint8_t number{};
  8415. return get_number(input_format_t::ubjson, number) && sax->number_unsigned(number);
  8416. }
  8417. case 'i':
  8418. {
  8419. std::int8_t number{};
  8420. return get_number(input_format_t::ubjson, number) && sax->number_integer(number);
  8421. }
  8422. case 'I':
  8423. {
  8424. std::int16_t number{};
  8425. return get_number(input_format_t::ubjson, number) && sax->number_integer(number);
  8426. }
  8427. case 'l':
  8428. {
  8429. std::int32_t number{};
  8430. return get_number(input_format_t::ubjson, number) && sax->number_integer(number);
  8431. }
  8432. case 'L':
  8433. {
  8434. std::int64_t number{};
  8435. return get_number(input_format_t::ubjson, number) && sax->number_integer(number);
  8436. }
  8437. case 'd':
  8438. {
  8439. float number{};
  8440. return get_number(input_format_t::ubjson, number) && sax->number_float(static_cast<number_float_t>(number), "");
  8441. }
  8442. case 'D':
  8443. {
  8444. double number{};
  8445. return get_number(input_format_t::ubjson, number) && sax->number_float(static_cast<number_float_t>(number), "");
  8446. }
  8447. case 'H':
  8448. {
  8449. return get_ubjson_high_precision_number();
  8450. }
  8451. case 'C': // char
  8452. {
  8453. get();
  8454. if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(input_format_t::ubjson, "char")))
  8455. {
  8456. return false;
  8457. }
  8458. if (JSON_HEDLEY_UNLIKELY(current > 127))
  8459. {
  8460. auto last_token = get_token_string();
  8461. 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")));
  8462. }
  8463. string_t s(1, static_cast<typename string_t::value_type>(current));
  8464. return sax->string(s);
  8465. }
  8466. case 'S': // string
  8467. {
  8468. string_t s;
  8469. return get_ubjson_string(s) && sax->string(s);
  8470. }
  8471. case '[': // array
  8472. return get_ubjson_array();
  8473. case '{': // object
  8474. return get_ubjson_object();
  8475. default: // anything else
  8476. {
  8477. auto last_token = get_token_string();
  8478. 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")));
  8479. }
  8480. }
  8481. }
  8482. /*!
  8483. @return whether array creation completed
  8484. */
  8485. bool get_ubjson_array()
  8486. {
  8487. std::pair<std::size_t, char_int_type> size_and_type;
  8488. if (JSON_HEDLEY_UNLIKELY(!get_ubjson_size_type(size_and_type)))
  8489. {
  8490. return false;
  8491. }
  8492. if (size_and_type.first != string_t::npos)
  8493. {
  8494. if (JSON_HEDLEY_UNLIKELY(!sax->start_array(size_and_type.first)))
  8495. {
  8496. return false;
  8497. }
  8498. if (size_and_type.second != 0)
  8499. {
  8500. if (size_and_type.second != 'N')
  8501. {
  8502. for (std::size_t i = 0; i < size_and_type.first; ++i)
  8503. {
  8504. if (JSON_HEDLEY_UNLIKELY(!get_ubjson_value(size_and_type.second)))
  8505. {
  8506. return false;
  8507. }
  8508. }
  8509. }
  8510. }
  8511. else
  8512. {
  8513. for (std::size_t i = 0; i < size_and_type.first; ++i)
  8514. {
  8515. if (JSON_HEDLEY_UNLIKELY(!parse_ubjson_internal()))
  8516. {
  8517. return false;
  8518. }
  8519. }
  8520. }
  8521. }
  8522. else
  8523. {
  8524. if (JSON_HEDLEY_UNLIKELY(!sax->start_array(std::size_t(-1))))
  8525. {
  8526. return false;
  8527. }
  8528. while (current != ']')
  8529. {
  8530. if (JSON_HEDLEY_UNLIKELY(!parse_ubjson_internal(false)))
  8531. {
  8532. return false;
  8533. }
  8534. get_ignore_noop();
  8535. }
  8536. }
  8537. return sax->end_array();
  8538. }
  8539. /*!
  8540. @return whether object creation completed
  8541. */
  8542. bool get_ubjson_object()
  8543. {
  8544. std::pair<std::size_t, char_int_type> size_and_type;
  8545. if (JSON_HEDLEY_UNLIKELY(!get_ubjson_size_type(size_and_type)))
  8546. {
  8547. return false;
  8548. }
  8549. string_t key;
  8550. if (size_and_type.first != string_t::npos)
  8551. {
  8552. if (JSON_HEDLEY_UNLIKELY(!sax->start_object(size_and_type.first)))
  8553. {
  8554. return false;
  8555. }
  8556. if (size_and_type.second != 0)
  8557. {
  8558. for (std::size_t i = 0; i < size_and_type.first; ++i)
  8559. {
  8560. if (JSON_HEDLEY_UNLIKELY(!get_ubjson_string(key) || !sax->key(key)))
  8561. {
  8562. return false;
  8563. }
  8564. if (JSON_HEDLEY_UNLIKELY(!get_ubjson_value(size_and_type.second)))
  8565. {
  8566. return false;
  8567. }
  8568. key.clear();
  8569. }
  8570. }
  8571. else
  8572. {
  8573. for (std::size_t i = 0; i < size_and_type.first; ++i)
  8574. {
  8575. if (JSON_HEDLEY_UNLIKELY(!get_ubjson_string(key) || !sax->key(key)))
  8576. {
  8577. return false;
  8578. }
  8579. if (JSON_HEDLEY_UNLIKELY(!parse_ubjson_internal()))
  8580. {
  8581. return false;
  8582. }
  8583. key.clear();
  8584. }
  8585. }
  8586. }
  8587. else
  8588. {
  8589. if (JSON_HEDLEY_UNLIKELY(!sax->start_object(std::size_t(-1))))
  8590. {
  8591. return false;
  8592. }
  8593. while (current != '}')
  8594. {
  8595. if (JSON_HEDLEY_UNLIKELY(!get_ubjson_string(key, false) || !sax->key(key)))
  8596. {
  8597. return false;
  8598. }
  8599. if (JSON_HEDLEY_UNLIKELY(!parse_ubjson_internal()))
  8600. {
  8601. return false;
  8602. }
  8603. get_ignore_noop();
  8604. key.clear();
  8605. }
  8606. }
  8607. return sax->end_object();
  8608. }
  8609. // Note, no reader for UBJSON binary types is implemented because they do
  8610. // not exist
  8611. bool get_ubjson_high_precision_number()
  8612. {
  8613. // get size of following number string
  8614. std::size_t size{};
  8615. auto res = get_ubjson_size_value(size);
  8616. if (JSON_HEDLEY_UNLIKELY(!res))
  8617. {
  8618. return res;
  8619. }
  8620. // get number string
  8621. std::vector<char> number_vector;
  8622. for (std::size_t i = 0; i < size; ++i)
  8623. {
  8624. get();
  8625. if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(input_format_t::ubjson, "number")))
  8626. {
  8627. return false;
  8628. }
  8629. number_vector.push_back(static_cast<char>(current));
  8630. }
  8631. // parse number string
  8632. auto number_ia = detail::input_adapter(std::forward<decltype(number_vector)>(number_vector));
  8633. auto number_lexer = detail::lexer<BasicJsonType, decltype(number_ia)>(std::move(number_ia), false);
  8634. const auto result_number = number_lexer.scan();
  8635. const auto number_string = number_lexer.get_token_string();
  8636. const auto result_remainder = number_lexer.scan();
  8637. using token_type = typename detail::lexer_base<BasicJsonType>::token_type;
  8638. if (JSON_HEDLEY_UNLIKELY(result_remainder != token_type::end_of_input))
  8639. {
  8640. 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")));
  8641. }
  8642. switch (result_number)
  8643. {
  8644. case token_type::value_integer:
  8645. return sax->number_integer(number_lexer.get_number_integer());
  8646. case token_type::value_unsigned:
  8647. return sax->number_unsigned(number_lexer.get_number_unsigned());
  8648. case token_type::value_float:
  8649. return sax->number_float(number_lexer.get_number_float(), std::move(number_string));
  8650. default:
  8651. 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")));
  8652. }
  8653. }
  8654. ///////////////////////
  8655. // Utility functions //
  8656. ///////////////////////
  8657. /*!
  8658. @brief get next character from the input
  8659. This function provides the interface to the used input adapter. It does
  8660. not throw in case the input reached EOF, but returns a -'ve valued
  8661. `std::char_traits<char_type>::eof()` in that case.
  8662. @return character read from the input
  8663. */
  8664. char_int_type get()
  8665. {
  8666. ++chars_read;
  8667. return current = ia.get_character();
  8668. }
  8669. /*!
  8670. @return character read from the input after ignoring all 'N' entries
  8671. */
  8672. char_int_type get_ignore_noop()
  8673. {
  8674. do
  8675. {
  8676. get();
  8677. }
  8678. while (current == 'N');
  8679. return current;
  8680. }
  8681. /*
  8682. @brief read a number from the input
  8683. @tparam NumberType the type of the number
  8684. @param[in] format the current format (for diagnostics)
  8685. @param[out] result number of type @a NumberType
  8686. @return whether conversion completed
  8687. @note This function needs to respect the system's endianess, because
  8688. bytes in CBOR, MessagePack, and UBJSON are stored in network order
  8689. (big endian) and therefore need reordering on little endian systems.
  8690. */
  8691. template<typename NumberType, bool InputIsLittleEndian = false>
  8692. bool get_number(const input_format_t format, NumberType& result)
  8693. {
  8694. // step 1: read input into array with system's byte order
  8695. std::array<std::uint8_t, sizeof(NumberType)> vec;
  8696. for (std::size_t i = 0; i < sizeof(NumberType); ++i)
  8697. {
  8698. get();
  8699. if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(format, "number")))
  8700. {
  8701. return false;
  8702. }
  8703. // reverse byte order prior to conversion if necessary
  8704. if (is_little_endian != InputIsLittleEndian)
  8705. {
  8706. vec[sizeof(NumberType) - i - 1] = static_cast<std::uint8_t>(current);
  8707. }
  8708. else
  8709. {
  8710. vec[i] = static_cast<std::uint8_t>(current); // LCOV_EXCL_LINE
  8711. }
  8712. }
  8713. // step 2: convert array into number of type T and return
  8714. std::memcpy(&result, vec.data(), sizeof(NumberType));
  8715. return true;
  8716. }
  8717. /*!
  8718. @brief create a string by reading characters from the input
  8719. @tparam NumberType the type of the number
  8720. @param[in] format the current format (for diagnostics)
  8721. @param[in] len number of characters to read
  8722. @param[out] result string created by reading @a len bytes
  8723. @return whether string creation completed
  8724. @note We can not reserve @a len bytes for the result, because @a len
  8725. may be too large. Usually, @ref unexpect_eof() detects the end of
  8726. the input before we run out of string memory.
  8727. */
  8728. template<typename NumberType>
  8729. bool get_string(const input_format_t format,
  8730. const NumberType len,
  8731. string_t& result)
  8732. {
  8733. bool success = true;
  8734. for (NumberType i = 0; i < len; i++)
  8735. {
  8736. get();
  8737. if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(format, "string")))
  8738. {
  8739. success = false;
  8740. break;
  8741. }
  8742. result.push_back(static_cast<typename string_t::value_type>(current));
  8743. };
  8744. return success;
  8745. }
  8746. /*!
  8747. @brief create a byte array by reading bytes from the input
  8748. @tparam NumberType the type of the number
  8749. @param[in] format the current format (for diagnostics)
  8750. @param[in] len number of bytes to read
  8751. @param[out] result byte array created by reading @a len bytes
  8752. @return whether byte array creation completed
  8753. @note We can not reserve @a len bytes for the result, because @a len
  8754. may be too large. Usually, @ref unexpect_eof() detects the end of
  8755. the input before we run out of memory.
  8756. */
  8757. template<typename NumberType>
  8758. bool get_binary(const input_format_t format,
  8759. const NumberType len,
  8760. binary_t& result)
  8761. {
  8762. bool success = true;
  8763. for (NumberType i = 0; i < len; i++)
  8764. {
  8765. get();
  8766. if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(format, "binary")))
  8767. {
  8768. success = false;
  8769. break;
  8770. }
  8771. result.push_back(static_cast<std::uint8_t>(current));
  8772. }
  8773. return success;
  8774. }
  8775. /*!
  8776. @param[in] format the current format (for diagnostics)
  8777. @param[in] context further context information (for diagnostics)
  8778. @return whether the last read character is not EOF
  8779. */
  8780. JSON_HEDLEY_NON_NULL(3)
  8781. bool unexpect_eof(const input_format_t format, const char* context) const
  8782. {
  8783. if (JSON_HEDLEY_UNLIKELY(current == std::char_traits<char_type>::eof()))
  8784. {
  8785. return sax->parse_error(chars_read, "<end of file>",
  8786. parse_error::create(110, chars_read, exception_message(format, "unexpected end of input", context)));
  8787. }
  8788. return true;
  8789. }
  8790. /*!
  8791. @return a string representation of the last read byte
  8792. */
  8793. std::string get_token_string() const
  8794. {
  8795. std::array<char, 3> cr{{}};
  8796. (std::snprintf)(cr.data(), cr.size(), "%.2hhX", static_cast<unsigned char>(current));
  8797. return std::string{cr.data()};
  8798. }
  8799. /*!
  8800. @param[in] format the current format
  8801. @param[in] detail a detailed error message
  8802. @param[in] context further context information
  8803. @return a message string to use in the parse_error exceptions
  8804. */
  8805. std::string exception_message(const input_format_t format,
  8806. const std::string& detail,
  8807. const std::string& context) const
  8808. {
  8809. std::string error_msg = "syntax error while parsing ";
  8810. switch (format)
  8811. {
  8812. case input_format_t::cbor:
  8813. error_msg += "CBOR";
  8814. break;
  8815. case input_format_t::msgpack:
  8816. error_msg += "MessagePack";
  8817. break;
  8818. case input_format_t::ubjson:
  8819. error_msg += "UBJSON";
  8820. break;
  8821. case input_format_t::bson:
  8822. error_msg += "BSON";
  8823. break;
  8824. default: // LCOV_EXCL_LINE
  8825. JSON_ASSERT(false); // LCOV_EXCL_LINE
  8826. }
  8827. return error_msg + " " + context + ": " + detail;
  8828. }
  8829. private:
  8830. /// input adapter
  8831. InputAdapterType ia;
  8832. /// the current character
  8833. char_int_type current = std::char_traits<char_type>::eof();
  8834. /// the number of characters read
  8835. std::size_t chars_read = 0;
  8836. /// whether we can assume little endianess
  8837. const bool is_little_endian = little_endianess();
  8838. /// the SAX parser
  8839. json_sax_t* sax = nullptr;
  8840. };
  8841. } // namespace detail
  8842. } // namespace nlohmann
  8843. // #include <nlohmann/detail/input/input_adapters.hpp>
  8844. // #include <nlohmann/detail/input/lexer.hpp>
  8845. // #include <nlohmann/detail/input/parser.hpp>
  8846. #include <cmath> // isfinite
  8847. #include <cstdint> // uint8_t
  8848. #include <functional> // function
  8849. #include <string> // string
  8850. #include <utility> // move
  8851. #include <vector> // vector
  8852. // #include <nlohmann/detail/exceptions.hpp>
  8853. // #include <nlohmann/detail/input/input_adapters.hpp>
  8854. // #include <nlohmann/detail/input/json_sax.hpp>
  8855. // #include <nlohmann/detail/input/lexer.hpp>
  8856. // #include <nlohmann/detail/macro_scope.hpp>
  8857. // #include <nlohmann/detail/meta/is_sax.hpp>
  8858. // #include <nlohmann/detail/value_t.hpp>
  8859. namespace nlohmann
  8860. {
  8861. namespace detail
  8862. {
  8863. ////////////
  8864. // parser //
  8865. ////////////
  8866. enum class parse_event_t : uint8_t
  8867. {
  8868. /// the parser read `{` and started to process a JSON object
  8869. object_start,
  8870. /// the parser read `}` and finished processing a JSON object
  8871. object_end,
  8872. /// the parser read `[` and started to process a JSON array
  8873. array_start,
  8874. /// the parser read `]` and finished processing a JSON array
  8875. array_end,
  8876. /// the parser read a key of a value in an object
  8877. key,
  8878. /// the parser finished reading a JSON value
  8879. value
  8880. };
  8881. template<typename BasicJsonType>
  8882. using parser_callback_t =
  8883. std::function<bool(int depth, parse_event_t event, BasicJsonType& parsed)>;
  8884. /*!
  8885. @brief syntax analysis
  8886. This class implements a recursive descent parser.
  8887. */
  8888. template<typename BasicJsonType, typename InputAdapterType>
  8889. class parser
  8890. {
  8891. using number_integer_t = typename BasicJsonType::number_integer_t;
  8892. using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
  8893. using number_float_t = typename BasicJsonType::number_float_t;
  8894. using string_t = typename BasicJsonType::string_t;
  8895. using lexer_t = lexer<BasicJsonType, InputAdapterType>;
  8896. using token_type = typename lexer_t::token_type;
  8897. public:
  8898. /// a parser reading from an input adapter
  8899. explicit parser(InputAdapterType&& adapter,
  8900. const parser_callback_t<BasicJsonType> cb = nullptr,
  8901. const bool allow_exceptions_ = true,
  8902. const bool skip_comments = false)
  8903. : callback(cb)
  8904. , m_lexer(std::move(adapter), skip_comments)
  8905. , allow_exceptions(allow_exceptions_)
  8906. {
  8907. // read first token
  8908. get_token();
  8909. }
  8910. /*!
  8911. @brief public parser interface
  8912. @param[in] strict whether to expect the last token to be EOF
  8913. @param[in,out] result parsed JSON value
  8914. @throw parse_error.101 in case of an unexpected token
  8915. @throw parse_error.102 if to_unicode fails or surrogate error
  8916. @throw parse_error.103 if to_unicode fails
  8917. */
  8918. void parse(const bool strict, BasicJsonType& result)
  8919. {
  8920. if (callback)
  8921. {
  8922. json_sax_dom_callback_parser<BasicJsonType> sdp(result, callback, allow_exceptions);
  8923. sax_parse_internal(&sdp);
  8924. result.assert_invariant();
  8925. // in strict mode, input must be completely read
  8926. if (strict && (get_token() != token_type::end_of_input))
  8927. {
  8928. sdp.parse_error(m_lexer.get_position(),
  8929. m_lexer.get_token_string(),
  8930. parse_error::create(101, m_lexer.get_position(),
  8931. exception_message(token_type::end_of_input, "value")));
  8932. }
  8933. // in case of an error, return discarded value
  8934. if (sdp.is_errored())
  8935. {
  8936. result = value_t::discarded;
  8937. return;
  8938. }
  8939. // set top-level value to null if it was discarded by the callback
  8940. // function
  8941. if (result.is_discarded())
  8942. {
  8943. result = nullptr;
  8944. }
  8945. }
  8946. else
  8947. {
  8948. json_sax_dom_parser<BasicJsonType> sdp(result, allow_exceptions);
  8949. sax_parse_internal(&sdp);
  8950. result.assert_invariant();
  8951. // in strict mode, input must be completely read
  8952. if (strict && (get_token() != token_type::end_of_input))
  8953. {
  8954. sdp.parse_error(m_lexer.get_position(),
  8955. m_lexer.get_token_string(),
  8956. parse_error::create(101, m_lexer.get_position(),
  8957. exception_message(token_type::end_of_input, "value")));
  8958. }
  8959. // in case of an error, return discarded value
  8960. if (sdp.is_errored())
  8961. {
  8962. result = value_t::discarded;
  8963. return;
  8964. }
  8965. }
  8966. }
  8967. /*!
  8968. @brief public accept interface
  8969. @param[in] strict whether to expect the last token to be EOF
  8970. @return whether the input is a proper JSON text
  8971. */
  8972. bool accept(const bool strict = true)
  8973. {
  8974. json_sax_acceptor<BasicJsonType> sax_acceptor;
  8975. return sax_parse(&sax_acceptor, strict);
  8976. }
  8977. template<typename SAX>
  8978. JSON_HEDLEY_NON_NULL(2)
  8979. bool sax_parse(SAX* sax, const bool strict = true)
  8980. {
  8981. (void)detail::is_sax_static_asserts<SAX, BasicJsonType> {};
  8982. const bool result = sax_parse_internal(sax);
  8983. // strict mode: next byte must be EOF
  8984. if (result && strict && (get_token() != token_type::end_of_input))
  8985. {
  8986. return sax->parse_error(m_lexer.get_position(),
  8987. m_lexer.get_token_string(),
  8988. parse_error::create(101, m_lexer.get_position(),
  8989. exception_message(token_type::end_of_input, "value")));
  8990. }
  8991. return result;
  8992. }
  8993. private:
  8994. template<typename SAX>
  8995. JSON_HEDLEY_NON_NULL(2)
  8996. bool sax_parse_internal(SAX* sax)
  8997. {
  8998. // stack to remember the hierarchy of structured values we are parsing
  8999. // true = array; false = object
  9000. std::vector<bool> states;
  9001. // value to avoid a goto (see comment where set to true)
  9002. bool skip_to_state_evaluation = false;
  9003. while (true)
  9004. {
  9005. if (!skip_to_state_evaluation)
  9006. {
  9007. // invariant: get_token() was called before each iteration
  9008. switch (last_token)
  9009. {
  9010. case token_type::begin_object:
  9011. {
  9012. if (JSON_HEDLEY_UNLIKELY(!sax->start_object(std::size_t(-1))))
  9013. {
  9014. return false;
  9015. }
  9016. // closing } -> we are done
  9017. if (get_token() == token_type::end_object)
  9018. {
  9019. if (JSON_HEDLEY_UNLIKELY(!sax->end_object()))
  9020. {
  9021. return false;
  9022. }
  9023. break;
  9024. }
  9025. // parse key
  9026. if (JSON_HEDLEY_UNLIKELY(last_token != token_type::value_string))
  9027. {
  9028. return sax->parse_error(m_lexer.get_position(),
  9029. m_lexer.get_token_string(),
  9030. parse_error::create(101, m_lexer.get_position(),
  9031. exception_message(token_type::value_string, "object key")));
  9032. }
  9033. if (JSON_HEDLEY_UNLIKELY(!sax->key(m_lexer.get_string())))
  9034. {
  9035. return false;
  9036. }
  9037. // parse separator (:)
  9038. if (JSON_HEDLEY_UNLIKELY(get_token() != token_type::name_separator))
  9039. {
  9040. return sax->parse_error(m_lexer.get_position(),
  9041. m_lexer.get_token_string(),
  9042. parse_error::create(101, m_lexer.get_position(),
  9043. exception_message(token_type::name_separator, "object separator")));
  9044. }
  9045. // remember we are now inside an object
  9046. states.push_back(false);
  9047. // parse values
  9048. get_token();
  9049. continue;
  9050. }
  9051. case token_type::begin_array:
  9052. {
  9053. if (JSON_HEDLEY_UNLIKELY(!sax->start_array(std::size_t(-1))))
  9054. {
  9055. return false;
  9056. }
  9057. // closing ] -> we are done
  9058. if (get_token() == token_type::end_array)
  9059. {
  9060. if (JSON_HEDLEY_UNLIKELY(!sax->end_array()))
  9061. {
  9062. return false;
  9063. }
  9064. break;
  9065. }
  9066. // remember we are now inside an array
  9067. states.push_back(true);
  9068. // parse values (no need to call get_token)
  9069. continue;
  9070. }
  9071. case token_type::value_float:
  9072. {
  9073. const auto res = m_lexer.get_number_float();
  9074. if (JSON_HEDLEY_UNLIKELY(!std::isfinite(res)))
  9075. {
  9076. return sax->parse_error(m_lexer.get_position(),
  9077. m_lexer.get_token_string(),
  9078. out_of_range::create(406, "number overflow parsing '" + m_lexer.get_token_string() + "'"));
  9079. }
  9080. if (JSON_HEDLEY_UNLIKELY(!sax->number_float(res, m_lexer.get_string())))
  9081. {
  9082. return false;
  9083. }
  9084. break;
  9085. }
  9086. case token_type::literal_false:
  9087. {
  9088. if (JSON_HEDLEY_UNLIKELY(!sax->boolean(false)))
  9089. {
  9090. return false;
  9091. }
  9092. break;
  9093. }
  9094. case token_type::literal_null:
  9095. {
  9096. if (JSON_HEDLEY_UNLIKELY(!sax->null()))
  9097. {
  9098. return false;
  9099. }
  9100. break;
  9101. }
  9102. case token_type::literal_true:
  9103. {
  9104. if (JSON_HEDLEY_UNLIKELY(!sax->boolean(true)))
  9105. {
  9106. return false;
  9107. }
  9108. break;
  9109. }
  9110. case token_type::value_integer:
  9111. {
  9112. if (JSON_HEDLEY_UNLIKELY(!sax->number_integer(m_lexer.get_number_integer())))
  9113. {
  9114. return false;
  9115. }
  9116. break;
  9117. }
  9118. case token_type::value_string:
  9119. {
  9120. if (JSON_HEDLEY_UNLIKELY(!sax->string(m_lexer.get_string())))
  9121. {
  9122. return false;
  9123. }
  9124. break;
  9125. }
  9126. case token_type::value_unsigned:
  9127. {
  9128. if (JSON_HEDLEY_UNLIKELY(!sax->number_unsigned(m_lexer.get_number_unsigned())))
  9129. {
  9130. return false;
  9131. }
  9132. break;
  9133. }
  9134. case token_type::parse_error:
  9135. {
  9136. // using "uninitialized" to avoid "expected" message
  9137. return sax->parse_error(m_lexer.get_position(),
  9138. m_lexer.get_token_string(),
  9139. parse_error::create(101, m_lexer.get_position(),
  9140. exception_message(token_type::uninitialized, "value")));
  9141. }
  9142. default: // the last token was unexpected
  9143. {
  9144. return sax->parse_error(m_lexer.get_position(),
  9145. m_lexer.get_token_string(),
  9146. parse_error::create(101, m_lexer.get_position(),
  9147. exception_message(token_type::literal_or_value, "value")));
  9148. }
  9149. }
  9150. }
  9151. else
  9152. {
  9153. skip_to_state_evaluation = false;
  9154. }
  9155. // we reached this line after we successfully parsed a value
  9156. if (states.empty())
  9157. {
  9158. // empty stack: we reached the end of the hierarchy: done
  9159. return true;
  9160. }
  9161. if (states.back()) // array
  9162. {
  9163. // comma -> next value
  9164. if (get_token() == token_type::value_separator)
  9165. {
  9166. // parse a new value
  9167. get_token();
  9168. continue;
  9169. }
  9170. // closing ]
  9171. if (JSON_HEDLEY_LIKELY(last_token == token_type::end_array))
  9172. {
  9173. if (JSON_HEDLEY_UNLIKELY(!sax->end_array()))
  9174. {
  9175. return false;
  9176. }
  9177. // We are done with this array. Before we can parse a
  9178. // new value, we need to evaluate the new state first.
  9179. // By setting skip_to_state_evaluation to false, we
  9180. // are effectively jumping to the beginning of this if.
  9181. JSON_ASSERT(!states.empty());
  9182. states.pop_back();
  9183. skip_to_state_evaluation = true;
  9184. continue;
  9185. }
  9186. return sax->parse_error(m_lexer.get_position(),
  9187. m_lexer.get_token_string(),
  9188. parse_error::create(101, m_lexer.get_position(),
  9189. exception_message(token_type::end_array, "array")));
  9190. }
  9191. else // object
  9192. {
  9193. // comma -> next value
  9194. if (get_token() == token_type::value_separator)
  9195. {
  9196. // parse key
  9197. if (JSON_HEDLEY_UNLIKELY(get_token() != token_type::value_string))
  9198. {
  9199. return sax->parse_error(m_lexer.get_position(),
  9200. m_lexer.get_token_string(),
  9201. parse_error::create(101, m_lexer.get_position(),
  9202. exception_message(token_type::value_string, "object key")));
  9203. }
  9204. if (JSON_HEDLEY_UNLIKELY(!sax->key(m_lexer.get_string())))
  9205. {
  9206. return false;
  9207. }
  9208. // parse separator (:)
  9209. if (JSON_HEDLEY_UNLIKELY(get_token() != token_type::name_separator))
  9210. {
  9211. return sax->parse_error(m_lexer.get_position(),
  9212. m_lexer.get_token_string(),
  9213. parse_error::create(101, m_lexer.get_position(),
  9214. exception_message(token_type::name_separator, "object separator")));
  9215. }
  9216. // parse values
  9217. get_token();
  9218. continue;
  9219. }
  9220. // closing }
  9221. if (JSON_HEDLEY_LIKELY(last_token == token_type::end_object))
  9222. {
  9223. if (JSON_HEDLEY_UNLIKELY(!sax->end_object()))
  9224. {
  9225. return false;
  9226. }
  9227. // We are done with this object. Before we can parse a
  9228. // new value, we need to evaluate the new state first.
  9229. // By setting skip_to_state_evaluation to false, we
  9230. // are effectively jumping to the beginning of this if.
  9231. JSON_ASSERT(!states.empty());
  9232. states.pop_back();
  9233. skip_to_state_evaluation = true;
  9234. continue;
  9235. }
  9236. return sax->parse_error(m_lexer.get_position(),
  9237. m_lexer.get_token_string(),
  9238. parse_error::create(101, m_lexer.get_position(),
  9239. exception_message(token_type::end_object, "object")));
  9240. }
  9241. }
  9242. }
  9243. /// get next token from lexer
  9244. token_type get_token()
  9245. {
  9246. return last_token = m_lexer.scan();
  9247. }
  9248. std::string exception_message(const token_type expected, const std::string& context)
  9249. {
  9250. std::string error_msg = "syntax error ";
  9251. if (!context.empty())
  9252. {
  9253. error_msg += "while parsing " + context + " ";
  9254. }
  9255. error_msg += "- ";
  9256. if (last_token == token_type::parse_error)
  9257. {
  9258. error_msg += std::string(m_lexer.get_error_message()) + "; last read: '" +
  9259. m_lexer.get_token_string() + "'";
  9260. }
  9261. else
  9262. {
  9263. error_msg += "unexpected " + std::string(lexer_t::token_type_name(last_token));
  9264. }
  9265. if (expected != token_type::uninitialized)
  9266. {
  9267. error_msg += "; expected " + std::string(lexer_t::token_type_name(expected));
  9268. }
  9269. return error_msg;
  9270. }
  9271. private:
  9272. /// callback function
  9273. const parser_callback_t<BasicJsonType> callback = nullptr;
  9274. /// the type of the last read token
  9275. token_type last_token = token_type::uninitialized;
  9276. /// the lexer
  9277. lexer_t m_lexer;
  9278. /// whether to throw exceptions in case of errors
  9279. const bool allow_exceptions = true;
  9280. };
  9281. } // namespace detail
  9282. } // namespace nlohmann
  9283. // #include <nlohmann/detail/iterators/internal_iterator.hpp>
  9284. // #include <nlohmann/detail/iterators/primitive_iterator.hpp>
  9285. #include <cstddef> // ptrdiff_t
  9286. #include <limits> // numeric_limits
  9287. namespace nlohmann
  9288. {
  9289. namespace detail
  9290. {
  9291. /*
  9292. @brief an iterator for primitive JSON types
  9293. This class models an iterator for primitive JSON types (boolean, number,
  9294. string). It's only purpose is to allow the iterator/const_iterator classes
  9295. to "iterate" over primitive values. Internally, the iterator is modeled by
  9296. a `difference_type` variable. Value begin_value (`0`) models the begin,
  9297. end_value (`1`) models past the end.
  9298. */
  9299. class primitive_iterator_t
  9300. {
  9301. private:
  9302. using difference_type = std::ptrdiff_t;
  9303. static constexpr difference_type begin_value = 0;
  9304. static constexpr difference_type end_value = begin_value + 1;
  9305. /// iterator as signed integer type
  9306. difference_type m_it = (std::numeric_limits<std::ptrdiff_t>::min)();
  9307. public:
  9308. constexpr difference_type get_value() const noexcept
  9309. {
  9310. return m_it;
  9311. }
  9312. /// set iterator to a defined beginning
  9313. void set_begin() noexcept
  9314. {
  9315. m_it = begin_value;
  9316. }
  9317. /// set iterator to a defined past the end
  9318. void set_end() noexcept
  9319. {
  9320. m_it = end_value;
  9321. }
  9322. /// return whether the iterator can be dereferenced
  9323. constexpr bool is_begin() const noexcept
  9324. {
  9325. return m_it == begin_value;
  9326. }
  9327. /// return whether the iterator is at end
  9328. constexpr bool is_end() const noexcept
  9329. {
  9330. return m_it == end_value;
  9331. }
  9332. friend constexpr bool operator==(primitive_iterator_t lhs, primitive_iterator_t rhs) noexcept
  9333. {
  9334. return lhs.m_it == rhs.m_it;
  9335. }
  9336. friend constexpr bool operator<(primitive_iterator_t lhs, primitive_iterator_t rhs) noexcept
  9337. {
  9338. return lhs.m_it < rhs.m_it;
  9339. }
  9340. primitive_iterator_t operator+(difference_type n) noexcept
  9341. {
  9342. auto result = *this;
  9343. result += n;
  9344. return result;
  9345. }
  9346. friend constexpr difference_type operator-(primitive_iterator_t lhs, primitive_iterator_t rhs) noexcept
  9347. {
  9348. return lhs.m_it - rhs.m_it;
  9349. }
  9350. primitive_iterator_t& operator++() noexcept
  9351. {
  9352. ++m_it;
  9353. return *this;
  9354. }
  9355. primitive_iterator_t const operator++(int) noexcept
  9356. {
  9357. auto result = *this;
  9358. ++m_it;
  9359. return result;
  9360. }
  9361. primitive_iterator_t& operator--() noexcept
  9362. {
  9363. --m_it;
  9364. return *this;
  9365. }
  9366. primitive_iterator_t const operator--(int) noexcept
  9367. {
  9368. auto result = *this;
  9369. --m_it;
  9370. return result;
  9371. }
  9372. primitive_iterator_t& operator+=(difference_type n) noexcept
  9373. {
  9374. m_it += n;
  9375. return *this;
  9376. }
  9377. primitive_iterator_t& operator-=(difference_type n) noexcept
  9378. {
  9379. m_it -= n;
  9380. return *this;
  9381. }
  9382. };
  9383. } // namespace detail
  9384. } // namespace nlohmann
  9385. namespace nlohmann
  9386. {
  9387. namespace detail
  9388. {
  9389. /*!
  9390. @brief an iterator value
  9391. @note This structure could easily be a union, but MSVC currently does not allow
  9392. unions members with complex constructors, see https://github.com/nlohmann/json/pull/105.
  9393. */
  9394. template<typename BasicJsonType> struct internal_iterator
  9395. {
  9396. /// iterator for JSON objects
  9397. typename BasicJsonType::object_t::iterator object_iterator {};
  9398. /// iterator for JSON arrays
  9399. typename BasicJsonType::array_t::iterator array_iterator {};
  9400. /// generic iterator for all other types
  9401. primitive_iterator_t primitive_iterator {};
  9402. };
  9403. } // namespace detail
  9404. } // namespace nlohmann
  9405. // #include <nlohmann/detail/iterators/iter_impl.hpp>
  9406. #include <iterator> // iterator, random_access_iterator_tag, bidirectional_iterator_tag, advance, next
  9407. #include <type_traits> // conditional, is_const, remove_const
  9408. // #include <nlohmann/detail/exceptions.hpp>
  9409. // #include <nlohmann/detail/iterators/internal_iterator.hpp>
  9410. // #include <nlohmann/detail/iterators/primitive_iterator.hpp>
  9411. // #include <nlohmann/detail/macro_scope.hpp>
  9412. // #include <nlohmann/detail/meta/cpp_future.hpp>
  9413. // #include <nlohmann/detail/meta/type_traits.hpp>
  9414. // #include <nlohmann/detail/value_t.hpp>
  9415. namespace nlohmann
  9416. {
  9417. namespace detail
  9418. {
  9419. // forward declare, to be able to friend it later on
  9420. template<typename IteratorType> class iteration_proxy;
  9421. template<typename IteratorType> class iteration_proxy_value;
  9422. /*!
  9423. @brief a template for a bidirectional iterator for the @ref basic_json class
  9424. This class implements a both iterators (iterator and const_iterator) for the
  9425. @ref basic_json class.
  9426. @note An iterator is called *initialized* when a pointer to a JSON value has
  9427. been set (e.g., by a constructor or a copy assignment). If the iterator is
  9428. default-constructed, it is *uninitialized* and most methods are undefined.
  9429. **The library uses assertions to detect calls on uninitialized iterators.**
  9430. @requirement The class satisfies the following concept requirements:
  9431. -
  9432. [BidirectionalIterator](https://en.cppreference.com/w/cpp/named_req/BidirectionalIterator):
  9433. The iterator that can be moved can be moved in both directions (i.e.
  9434. incremented and decremented).
  9435. @since version 1.0.0, simplified in version 2.0.9, change to bidirectional
  9436. iterators in version 3.0.0 (see https://github.com/nlohmann/json/issues/593)
  9437. */
  9438. template<typename BasicJsonType>
  9439. class iter_impl
  9440. {
  9441. /// allow basic_json to access private members
  9442. friend iter_impl<typename std::conditional<std::is_const<BasicJsonType>::value, typename std::remove_const<BasicJsonType>::type, const BasicJsonType>::type>;
  9443. friend BasicJsonType;
  9444. friend iteration_proxy<iter_impl>;
  9445. friend iteration_proxy_value<iter_impl>;
  9446. using object_t = typename BasicJsonType::object_t;
  9447. using array_t = typename BasicJsonType::array_t;
  9448. // make sure BasicJsonType is basic_json or const basic_json
  9449. static_assert(is_basic_json<typename std::remove_const<BasicJsonType>::type>::value,
  9450. "iter_impl only accepts (const) basic_json");
  9451. public:
  9452. /// The std::iterator class template (used as a base class to provide typedefs) is deprecated in C++17.
  9453. /// The C++ Standard has never required user-defined iterators to derive from std::iterator.
  9454. /// A user-defined iterator should provide publicly accessible typedefs named
  9455. /// iterator_category, value_type, difference_type, pointer, and reference.
  9456. /// Note that value_type is required to be non-const, even for constant iterators.
  9457. using iterator_category = std::bidirectional_iterator_tag;
  9458. /// the type of the values when the iterator is dereferenced
  9459. using value_type = typename BasicJsonType::value_type;
  9460. /// a type to represent differences between iterators
  9461. using difference_type = typename BasicJsonType::difference_type;
  9462. /// defines a pointer to the type iterated over (value_type)
  9463. using pointer = typename std::conditional<std::is_const<BasicJsonType>::value,
  9464. typename BasicJsonType::const_pointer,
  9465. typename BasicJsonType::pointer>::type;
  9466. /// defines a reference to the type iterated over (value_type)
  9467. using reference =
  9468. typename std::conditional<std::is_const<BasicJsonType>::value,
  9469. typename BasicJsonType::const_reference,
  9470. typename BasicJsonType::reference>::type;
  9471. /// default constructor
  9472. iter_impl() = default;
  9473. /*!
  9474. @brief constructor for a given JSON instance
  9475. @param[in] object pointer to a JSON object for this iterator
  9476. @pre object != nullptr
  9477. @post The iterator is initialized; i.e. `m_object != nullptr`.
  9478. */
  9479. explicit iter_impl(pointer object) noexcept : m_object(object)
  9480. {
  9481. JSON_ASSERT(m_object != nullptr);
  9482. switch (m_object->m_type)
  9483. {
  9484. case value_t::object:
  9485. {
  9486. m_it.object_iterator = typename object_t::iterator();
  9487. break;
  9488. }
  9489. case value_t::array:
  9490. {
  9491. m_it.array_iterator = typename array_t::iterator();
  9492. break;
  9493. }
  9494. default:
  9495. {
  9496. m_it.primitive_iterator = primitive_iterator_t();
  9497. break;
  9498. }
  9499. }
  9500. }
  9501. /*!
  9502. @note The conventional copy constructor and copy assignment are implicitly
  9503. defined. Combined with the following converting constructor and
  9504. assignment, they support: (1) copy from iterator to iterator, (2)
  9505. copy from const iterator to const iterator, and (3) conversion from
  9506. iterator to const iterator. However conversion from const iterator
  9507. to iterator is not defined.
  9508. */
  9509. /*!
  9510. @brief const copy constructor
  9511. @param[in] other const iterator to copy from
  9512. @note This copy constructor had to be defined explicitly to circumvent a bug
  9513. occurring on msvc v19.0 compiler (VS 2015) debug build. For more
  9514. information refer to: https://github.com/nlohmann/json/issues/1608
  9515. */
  9516. iter_impl(const iter_impl<const BasicJsonType>& other) noexcept
  9517. : m_object(other.m_object), m_it(other.m_it)
  9518. {}
  9519. /*!
  9520. @brief converting assignment
  9521. @param[in] other const iterator to copy from
  9522. @return const/non-const iterator
  9523. @note It is not checked whether @a other is initialized.
  9524. */
  9525. iter_impl& operator=(const iter_impl<const BasicJsonType>& other) noexcept
  9526. {
  9527. m_object = other.m_object;
  9528. m_it = other.m_it;
  9529. return *this;
  9530. }
  9531. /*!
  9532. @brief converting constructor
  9533. @param[in] other non-const iterator to copy from
  9534. @note It is not checked whether @a other is initialized.
  9535. */
  9536. iter_impl(const iter_impl<typename std::remove_const<BasicJsonType>::type>& other) noexcept
  9537. : m_object(other.m_object), m_it(other.m_it)
  9538. {}
  9539. /*!
  9540. @brief converting assignment
  9541. @param[in] other non-const iterator to copy from
  9542. @return const/non-const iterator
  9543. @note It is not checked whether @a other is initialized.
  9544. */
  9545. iter_impl& operator=(const iter_impl<typename std::remove_const<BasicJsonType>::type>& other) noexcept
  9546. {
  9547. m_object = other.m_object;
  9548. m_it = other.m_it;
  9549. return *this;
  9550. }
  9551. private:
  9552. /*!
  9553. @brief set the iterator to the first value
  9554. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  9555. */
  9556. void set_begin() noexcept
  9557. {
  9558. JSON_ASSERT(m_object != nullptr);
  9559. switch (m_object->m_type)
  9560. {
  9561. case value_t::object:
  9562. {
  9563. m_it.object_iterator = m_object->m_value.object->begin();
  9564. break;
  9565. }
  9566. case value_t::array:
  9567. {
  9568. m_it.array_iterator = m_object->m_value.array->begin();
  9569. break;
  9570. }
  9571. case value_t::null:
  9572. {
  9573. // set to end so begin()==end() is true: null is empty
  9574. m_it.primitive_iterator.set_end();
  9575. break;
  9576. }
  9577. default:
  9578. {
  9579. m_it.primitive_iterator.set_begin();
  9580. break;
  9581. }
  9582. }
  9583. }
  9584. /*!
  9585. @brief set the iterator past the last value
  9586. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  9587. */
  9588. void set_end() noexcept
  9589. {
  9590. JSON_ASSERT(m_object != nullptr);
  9591. switch (m_object->m_type)
  9592. {
  9593. case value_t::object:
  9594. {
  9595. m_it.object_iterator = m_object->m_value.object->end();
  9596. break;
  9597. }
  9598. case value_t::array:
  9599. {
  9600. m_it.array_iterator = m_object->m_value.array->end();
  9601. break;
  9602. }
  9603. default:
  9604. {
  9605. m_it.primitive_iterator.set_end();
  9606. break;
  9607. }
  9608. }
  9609. }
  9610. public:
  9611. /*!
  9612. @brief return a reference to the value pointed to by the iterator
  9613. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  9614. */
  9615. reference operator*() const
  9616. {
  9617. JSON_ASSERT(m_object != nullptr);
  9618. switch (m_object->m_type)
  9619. {
  9620. case value_t::object:
  9621. {
  9622. JSON_ASSERT(m_it.object_iterator != m_object->m_value.object->end());
  9623. return m_it.object_iterator->second;
  9624. }
  9625. case value_t::array:
  9626. {
  9627. JSON_ASSERT(m_it.array_iterator != m_object->m_value.array->end());
  9628. return *m_it.array_iterator;
  9629. }
  9630. case value_t::null:
  9631. JSON_THROW(invalid_iterator::create(214, "cannot get value"));
  9632. default:
  9633. {
  9634. if (JSON_HEDLEY_LIKELY(m_it.primitive_iterator.is_begin()))
  9635. {
  9636. return *m_object;
  9637. }
  9638. JSON_THROW(invalid_iterator::create(214, "cannot get value"));
  9639. }
  9640. }
  9641. }
  9642. /*!
  9643. @brief dereference the iterator
  9644. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  9645. */
  9646. pointer operator->() const
  9647. {
  9648. JSON_ASSERT(m_object != nullptr);
  9649. switch (m_object->m_type)
  9650. {
  9651. case value_t::object:
  9652. {
  9653. JSON_ASSERT(m_it.object_iterator != m_object->m_value.object->end());
  9654. return &(m_it.object_iterator->second);
  9655. }
  9656. case value_t::array:
  9657. {
  9658. JSON_ASSERT(m_it.array_iterator != m_object->m_value.array->end());
  9659. return &*m_it.array_iterator;
  9660. }
  9661. default:
  9662. {
  9663. if (JSON_HEDLEY_LIKELY(m_it.primitive_iterator.is_begin()))
  9664. {
  9665. return m_object;
  9666. }
  9667. JSON_THROW(invalid_iterator::create(214, "cannot get value"));
  9668. }
  9669. }
  9670. }
  9671. /*!
  9672. @brief post-increment (it++)
  9673. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  9674. */
  9675. iter_impl const operator++(int)
  9676. {
  9677. auto result = *this;
  9678. ++(*this);
  9679. return result;
  9680. }
  9681. /*!
  9682. @brief pre-increment (++it)
  9683. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  9684. */
  9685. iter_impl& operator++()
  9686. {
  9687. JSON_ASSERT(m_object != nullptr);
  9688. switch (m_object->m_type)
  9689. {
  9690. case value_t::object:
  9691. {
  9692. std::advance(m_it.object_iterator, 1);
  9693. break;
  9694. }
  9695. case value_t::array:
  9696. {
  9697. std::advance(m_it.array_iterator, 1);
  9698. break;
  9699. }
  9700. default:
  9701. {
  9702. ++m_it.primitive_iterator;
  9703. break;
  9704. }
  9705. }
  9706. return *this;
  9707. }
  9708. /*!
  9709. @brief post-decrement (it--)
  9710. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  9711. */
  9712. iter_impl const operator--(int)
  9713. {
  9714. auto result = *this;
  9715. --(*this);
  9716. return result;
  9717. }
  9718. /*!
  9719. @brief pre-decrement (--it)
  9720. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  9721. */
  9722. iter_impl& operator--()
  9723. {
  9724. JSON_ASSERT(m_object != nullptr);
  9725. switch (m_object->m_type)
  9726. {
  9727. case value_t::object:
  9728. {
  9729. std::advance(m_it.object_iterator, -1);
  9730. break;
  9731. }
  9732. case value_t::array:
  9733. {
  9734. std::advance(m_it.array_iterator, -1);
  9735. break;
  9736. }
  9737. default:
  9738. {
  9739. --m_it.primitive_iterator;
  9740. break;
  9741. }
  9742. }
  9743. return *this;
  9744. }
  9745. /*!
  9746. @brief comparison: equal
  9747. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  9748. */
  9749. bool operator==(const iter_impl& other) const
  9750. {
  9751. // if objects are not the same, the comparison is undefined
  9752. if (JSON_HEDLEY_UNLIKELY(m_object != other.m_object))
  9753. {
  9754. JSON_THROW(invalid_iterator::create(212, "cannot compare iterators of different containers"));
  9755. }
  9756. JSON_ASSERT(m_object != nullptr);
  9757. switch (m_object->m_type)
  9758. {
  9759. case value_t::object:
  9760. return (m_it.object_iterator == other.m_it.object_iterator);
  9761. case value_t::array:
  9762. return (m_it.array_iterator == other.m_it.array_iterator);
  9763. default:
  9764. return (m_it.primitive_iterator == other.m_it.primitive_iterator);
  9765. }
  9766. }
  9767. /*!
  9768. @brief comparison: not equal
  9769. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  9770. */
  9771. bool operator!=(const iter_impl& other) const
  9772. {
  9773. return !operator==(other);
  9774. }
  9775. /*!
  9776. @brief comparison: smaller
  9777. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  9778. */
  9779. bool operator<(const iter_impl& other) const
  9780. {
  9781. // if objects are not the same, the comparison is undefined
  9782. if (JSON_HEDLEY_UNLIKELY(m_object != other.m_object))
  9783. {
  9784. JSON_THROW(invalid_iterator::create(212, "cannot compare iterators of different containers"));
  9785. }
  9786. JSON_ASSERT(m_object != nullptr);
  9787. switch (m_object->m_type)
  9788. {
  9789. case value_t::object:
  9790. JSON_THROW(invalid_iterator::create(213, "cannot compare order of object iterators"));
  9791. case value_t::array:
  9792. return (m_it.array_iterator < other.m_it.array_iterator);
  9793. default:
  9794. return (m_it.primitive_iterator < other.m_it.primitive_iterator);
  9795. }
  9796. }
  9797. /*!
  9798. @brief comparison: less than or equal
  9799. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  9800. */
  9801. bool operator<=(const iter_impl& other) const
  9802. {
  9803. return !other.operator < (*this);
  9804. }
  9805. /*!
  9806. @brief comparison: greater than
  9807. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  9808. */
  9809. bool operator>(const iter_impl& other) const
  9810. {
  9811. return !operator<=(other);
  9812. }
  9813. /*!
  9814. @brief comparison: greater than or equal
  9815. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  9816. */
  9817. bool operator>=(const iter_impl& other) const
  9818. {
  9819. return !operator<(other);
  9820. }
  9821. /*!
  9822. @brief add to iterator
  9823. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  9824. */
  9825. iter_impl& operator+=(difference_type i)
  9826. {
  9827. JSON_ASSERT(m_object != nullptr);
  9828. switch (m_object->m_type)
  9829. {
  9830. case value_t::object:
  9831. JSON_THROW(invalid_iterator::create(209, "cannot use offsets with object iterators"));
  9832. case value_t::array:
  9833. {
  9834. std::advance(m_it.array_iterator, i);
  9835. break;
  9836. }
  9837. default:
  9838. {
  9839. m_it.primitive_iterator += i;
  9840. break;
  9841. }
  9842. }
  9843. return *this;
  9844. }
  9845. /*!
  9846. @brief subtract from iterator
  9847. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  9848. */
  9849. iter_impl& operator-=(difference_type i)
  9850. {
  9851. return operator+=(-i);
  9852. }
  9853. /*!
  9854. @brief add to iterator
  9855. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  9856. */
  9857. iter_impl operator+(difference_type i) const
  9858. {
  9859. auto result = *this;
  9860. result += i;
  9861. return result;
  9862. }
  9863. /*!
  9864. @brief addition of distance and iterator
  9865. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  9866. */
  9867. friend iter_impl operator+(difference_type i, const iter_impl& it)
  9868. {
  9869. auto result = it;
  9870. result += i;
  9871. return result;
  9872. }
  9873. /*!
  9874. @brief subtract from iterator
  9875. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  9876. */
  9877. iter_impl operator-(difference_type i) const
  9878. {
  9879. auto result = *this;
  9880. result -= i;
  9881. return result;
  9882. }
  9883. /*!
  9884. @brief return difference
  9885. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  9886. */
  9887. difference_type operator-(const iter_impl& other) const
  9888. {
  9889. JSON_ASSERT(m_object != nullptr);
  9890. switch (m_object->m_type)
  9891. {
  9892. case value_t::object:
  9893. JSON_THROW(invalid_iterator::create(209, "cannot use offsets with object iterators"));
  9894. case value_t::array:
  9895. return m_it.array_iterator - other.m_it.array_iterator;
  9896. default:
  9897. return m_it.primitive_iterator - other.m_it.primitive_iterator;
  9898. }
  9899. }
  9900. /*!
  9901. @brief access to successor
  9902. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  9903. */
  9904. reference operator[](difference_type n) const
  9905. {
  9906. JSON_ASSERT(m_object != nullptr);
  9907. switch (m_object->m_type)
  9908. {
  9909. case value_t::object:
  9910. JSON_THROW(invalid_iterator::create(208, "cannot use operator[] for object iterators"));
  9911. case value_t::array:
  9912. return *std::next(m_it.array_iterator, n);
  9913. case value_t::null:
  9914. JSON_THROW(invalid_iterator::create(214, "cannot get value"));
  9915. default:
  9916. {
  9917. if (JSON_HEDLEY_LIKELY(m_it.primitive_iterator.get_value() == -n))
  9918. {
  9919. return *m_object;
  9920. }
  9921. JSON_THROW(invalid_iterator::create(214, "cannot get value"));
  9922. }
  9923. }
  9924. }
  9925. /*!
  9926. @brief return the key of an object iterator
  9927. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  9928. */
  9929. const typename object_t::key_type& key() const
  9930. {
  9931. JSON_ASSERT(m_object != nullptr);
  9932. if (JSON_HEDLEY_LIKELY(m_object->is_object()))
  9933. {
  9934. return m_it.object_iterator->first;
  9935. }
  9936. JSON_THROW(invalid_iterator::create(207, "cannot use key() for non-object iterators"));
  9937. }
  9938. /*!
  9939. @brief return the value of an iterator
  9940. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  9941. */
  9942. reference value() const
  9943. {
  9944. return operator*();
  9945. }
  9946. private:
  9947. /// associated JSON instance
  9948. pointer m_object = nullptr;
  9949. /// the actual iterator of the associated instance
  9950. internal_iterator<typename std::remove_const<BasicJsonType>::type> m_it {};
  9951. };
  9952. } // namespace detail
  9953. } // namespace nlohmann
  9954. // #include <nlohmann/detail/iterators/iteration_proxy.hpp>
  9955. // #include <nlohmann/detail/iterators/json_reverse_iterator.hpp>
  9956. #include <cstddef> // ptrdiff_t
  9957. #include <iterator> // reverse_iterator
  9958. #include <utility> // declval
  9959. namespace nlohmann
  9960. {
  9961. namespace detail
  9962. {
  9963. //////////////////////
  9964. // reverse_iterator //
  9965. //////////////////////
  9966. /*!
  9967. @brief a template for a reverse iterator class
  9968. @tparam Base the base iterator type to reverse. Valid types are @ref
  9969. iterator (to create @ref reverse_iterator) and @ref const_iterator (to
  9970. create @ref const_reverse_iterator).
  9971. @requirement The class satisfies the following concept requirements:
  9972. -
  9973. [BidirectionalIterator](https://en.cppreference.com/w/cpp/named_req/BidirectionalIterator):
  9974. The iterator that can be moved can be moved in both directions (i.e.
  9975. incremented and decremented).
  9976. - [OutputIterator](https://en.cppreference.com/w/cpp/named_req/OutputIterator):
  9977. It is possible to write to the pointed-to element (only if @a Base is
  9978. @ref iterator).
  9979. @since version 1.0.0
  9980. */
  9981. template<typename Base>
  9982. class json_reverse_iterator : public std::reverse_iterator<Base>
  9983. {
  9984. public:
  9985. using difference_type = std::ptrdiff_t;
  9986. /// shortcut to the reverse iterator adapter
  9987. using base_iterator = std::reverse_iterator<Base>;
  9988. /// the reference type for the pointed-to element
  9989. using reference = typename Base::reference;
  9990. /// create reverse iterator from iterator
  9991. explicit json_reverse_iterator(const typename base_iterator::iterator_type& it) noexcept
  9992. : base_iterator(it) {}
  9993. /// create reverse iterator from base class
  9994. explicit json_reverse_iterator(const base_iterator& it) noexcept : base_iterator(it) {}
  9995. /// post-increment (it++)
  9996. json_reverse_iterator const operator++(int)
  9997. {
  9998. return static_cast<json_reverse_iterator>(base_iterator::operator++(1));
  9999. }
  10000. /// pre-increment (++it)
  10001. json_reverse_iterator& operator++()
  10002. {
  10003. return static_cast<json_reverse_iterator&>(base_iterator::operator++());
  10004. }
  10005. /// post-decrement (it--)
  10006. json_reverse_iterator const operator--(int)
  10007. {
  10008. return static_cast<json_reverse_iterator>(base_iterator::operator--(1));
  10009. }
  10010. /// pre-decrement (--it)
  10011. json_reverse_iterator& operator--()
  10012. {
  10013. return static_cast<json_reverse_iterator&>(base_iterator::operator--());
  10014. }
  10015. /// add to iterator
  10016. json_reverse_iterator& operator+=(difference_type i)
  10017. {
  10018. return static_cast<json_reverse_iterator&>(base_iterator::operator+=(i));
  10019. }
  10020. /// add to iterator
  10021. json_reverse_iterator operator+(difference_type i) const
  10022. {
  10023. return static_cast<json_reverse_iterator>(base_iterator::operator+(i));
  10024. }
  10025. /// subtract from iterator
  10026. json_reverse_iterator operator-(difference_type i) const
  10027. {
  10028. return static_cast<json_reverse_iterator>(base_iterator::operator-(i));
  10029. }
  10030. /// return difference
  10031. difference_type operator-(const json_reverse_iterator& other) const
  10032. {
  10033. return base_iterator(*this) - base_iterator(other);
  10034. }
  10035. /// access to successor
  10036. reference operator[](difference_type n) const
  10037. {
  10038. return *(this->operator+(n));
  10039. }
  10040. /// return the key of an object iterator
  10041. auto key() const -> decltype(std::declval<Base>().key())
  10042. {
  10043. auto it = --this->base();
  10044. return it.key();
  10045. }
  10046. /// return the value of an iterator
  10047. reference value() const
  10048. {
  10049. auto it = --this->base();
  10050. return it.operator * ();
  10051. }
  10052. };
  10053. } // namespace detail
  10054. } // namespace nlohmann
  10055. // #include <nlohmann/detail/iterators/primitive_iterator.hpp>
  10056. // #include <nlohmann/detail/json_pointer.hpp>
  10057. #include <algorithm> // all_of
  10058. #include <cctype> // isdigit
  10059. #include <limits> // max
  10060. #include <numeric> // accumulate
  10061. #include <string> // string
  10062. #include <utility> // move
  10063. #include <vector> // vector
  10064. // #include <nlohmann/detail/exceptions.hpp>
  10065. // #include <nlohmann/detail/macro_scope.hpp>
  10066. // #include <nlohmann/detail/value_t.hpp>
  10067. namespace nlohmann
  10068. {
  10069. template<typename BasicJsonType>
  10070. class json_pointer
  10071. {
  10072. // allow basic_json to access private members
  10073. NLOHMANN_BASIC_JSON_TPL_DECLARATION
  10074. friend class basic_json;
  10075. public:
  10076. /*!
  10077. @brief create JSON pointer
  10078. Create a JSON pointer according to the syntax described in
  10079. [Section 3 of RFC6901](https://tools.ietf.org/html/rfc6901#section-3).
  10080. @param[in] s string representing the JSON pointer; if omitted, the empty
  10081. string is assumed which references the whole JSON value
  10082. @throw parse_error.107 if the given JSON pointer @a s is nonempty and does
  10083. not begin with a slash (`/`); see example below
  10084. @throw parse_error.108 if a tilde (`~`) in the given JSON pointer @a s is
  10085. not followed by `0` (representing `~`) or `1` (representing `/`); see
  10086. example below
  10087. @liveexample{The example shows the construction several valid JSON pointers
  10088. as well as the exceptional behavior.,json_pointer}
  10089. @since version 2.0.0
  10090. */
  10091. explicit json_pointer(const std::string& s = "")
  10092. : reference_tokens(split(s))
  10093. {}
  10094. /*!
  10095. @brief return a string representation of the JSON pointer
  10096. @invariant For each JSON pointer `ptr`, it holds:
  10097. @code {.cpp}
  10098. ptr == json_pointer(ptr.to_string());
  10099. @endcode
  10100. @return a string representation of the JSON pointer
  10101. @liveexample{The example shows the result of `to_string`.,json_pointer__to_string}
  10102. @since version 2.0.0
  10103. */
  10104. std::string to_string() const
  10105. {
  10106. return std::accumulate(reference_tokens.begin(), reference_tokens.end(),
  10107. std::string{},
  10108. [](const std::string & a, const std::string & b)
  10109. {
  10110. return a + "/" + escape(b);
  10111. });
  10112. }
  10113. /// @copydoc to_string()
  10114. operator std::string() const
  10115. {
  10116. return to_string();
  10117. }
  10118. /*!
  10119. @brief append another JSON pointer at the end of this JSON pointer
  10120. @param[in] ptr JSON pointer to append
  10121. @return JSON pointer with @a ptr appended
  10122. @liveexample{The example shows the usage of `operator/=`.,json_pointer__operator_add}
  10123. @complexity Linear in the length of @a ptr.
  10124. @sa @ref operator/=(std::string) to append a reference token
  10125. @sa @ref operator/=(std::size_t) to append an array index
  10126. @sa @ref operator/(const json_pointer&, const json_pointer&) for a binary operator
  10127. @since version 3.6.0
  10128. */
  10129. json_pointer& operator/=(const json_pointer& ptr)
  10130. {
  10131. reference_tokens.insert(reference_tokens.end(),
  10132. ptr.reference_tokens.begin(),
  10133. ptr.reference_tokens.end());
  10134. return *this;
  10135. }
  10136. /*!
  10137. @brief append an unescaped reference token at the end of this JSON pointer
  10138. @param[in] token reference token to append
  10139. @return JSON pointer with @a token appended without escaping @a token
  10140. @liveexample{The example shows the usage of `operator/=`.,json_pointer__operator_add}
  10141. @complexity Amortized constant.
  10142. @sa @ref operator/=(const json_pointer&) to append a JSON pointer
  10143. @sa @ref operator/=(std::size_t) to append an array index
  10144. @sa @ref operator/(const json_pointer&, std::size_t) for a binary operator
  10145. @since version 3.6.0
  10146. */
  10147. json_pointer& operator/=(std::string token)
  10148. {
  10149. push_back(std::move(token));
  10150. return *this;
  10151. }
  10152. /*!
  10153. @brief append an array index at the end of this JSON pointer
  10154. @param[in] array_idx array index to append
  10155. @return JSON pointer with @a array_idx appended
  10156. @liveexample{The example shows the usage of `operator/=`.,json_pointer__operator_add}
  10157. @complexity Amortized constant.
  10158. @sa @ref operator/=(const json_pointer&) to append a JSON pointer
  10159. @sa @ref operator/=(std::string) to append a reference token
  10160. @sa @ref operator/(const json_pointer&, std::string) for a binary operator
  10161. @since version 3.6.0
  10162. */
  10163. json_pointer& operator/=(std::size_t array_idx)
  10164. {
  10165. return *this /= std::to_string(array_idx);
  10166. }
  10167. /*!
  10168. @brief create a new JSON pointer by appending the right JSON pointer at the end of the left JSON pointer
  10169. @param[in] lhs JSON pointer
  10170. @param[in] rhs JSON pointer
  10171. @return a new JSON pointer with @a rhs appended to @a lhs
  10172. @liveexample{The example shows the usage of `operator/`.,json_pointer__operator_add_binary}
  10173. @complexity Linear in the length of @a lhs and @a rhs.
  10174. @sa @ref operator/=(const json_pointer&) to append a JSON pointer
  10175. @since version 3.6.0
  10176. */
  10177. friend json_pointer operator/(const json_pointer& lhs,
  10178. const json_pointer& rhs)
  10179. {
  10180. return json_pointer(lhs) /= rhs;
  10181. }
  10182. /*!
  10183. @brief create a new JSON pointer by appending the unescaped token at the end of the JSON pointer
  10184. @param[in] ptr JSON pointer
  10185. @param[in] token reference token
  10186. @return a new JSON pointer with unescaped @a token appended to @a ptr
  10187. @liveexample{The example shows the usage of `operator/`.,json_pointer__operator_add_binary}
  10188. @complexity Linear in the length of @a ptr.
  10189. @sa @ref operator/=(std::string) to append a reference token
  10190. @since version 3.6.0
  10191. */
  10192. friend json_pointer operator/(const json_pointer& ptr, std::string token)
  10193. {
  10194. return json_pointer(ptr) /= std::move(token);
  10195. }
  10196. /*!
  10197. @brief create a new JSON pointer by appending the array-index-token at the end of the JSON pointer
  10198. @param[in] ptr JSON pointer
  10199. @param[in] array_idx array index
  10200. @return a new JSON pointer with @a array_idx appended to @a ptr
  10201. @liveexample{The example shows the usage of `operator/`.,json_pointer__operator_add_binary}
  10202. @complexity Linear in the length of @a ptr.
  10203. @sa @ref operator/=(std::size_t) to append an array index
  10204. @since version 3.6.0
  10205. */
  10206. friend json_pointer operator/(const json_pointer& ptr, std::size_t array_idx)
  10207. {
  10208. return json_pointer(ptr) /= array_idx;
  10209. }
  10210. /*!
  10211. @brief returns the parent of this JSON pointer
  10212. @return parent of this JSON pointer; in case this JSON pointer is the root,
  10213. the root itself is returned
  10214. @complexity Linear in the length of the JSON pointer.
  10215. @liveexample{The example shows the result of `parent_pointer` for different
  10216. JSON Pointers.,json_pointer__parent_pointer}
  10217. @since version 3.6.0
  10218. */
  10219. json_pointer parent_pointer() const
  10220. {
  10221. if (empty())
  10222. {
  10223. return *this;
  10224. }
  10225. json_pointer res = *this;
  10226. res.pop_back();
  10227. return res;
  10228. }
  10229. /*!
  10230. @brief remove last reference token
  10231. @pre not `empty()`
  10232. @liveexample{The example shows the usage of `pop_back`.,json_pointer__pop_back}
  10233. @complexity Constant.
  10234. @throw out_of_range.405 if JSON pointer has no parent
  10235. @since version 3.6.0
  10236. */
  10237. void pop_back()
  10238. {
  10239. if (JSON_HEDLEY_UNLIKELY(empty()))
  10240. {
  10241. JSON_THROW(detail::out_of_range::create(405, "JSON pointer has no parent"));
  10242. }
  10243. reference_tokens.pop_back();
  10244. }
  10245. /*!
  10246. @brief return last reference token
  10247. @pre not `empty()`
  10248. @return last reference token
  10249. @liveexample{The example shows the usage of `back`.,json_pointer__back}
  10250. @complexity Constant.
  10251. @throw out_of_range.405 if JSON pointer has no parent
  10252. @since version 3.6.0
  10253. */
  10254. const std::string& back() const
  10255. {
  10256. if (JSON_HEDLEY_UNLIKELY(empty()))
  10257. {
  10258. JSON_THROW(detail::out_of_range::create(405, "JSON pointer has no parent"));
  10259. }
  10260. return reference_tokens.back();
  10261. }
  10262. /*!
  10263. @brief append an unescaped token at the end of the reference pointer
  10264. @param[in] token token to add
  10265. @complexity Amortized constant.
  10266. @liveexample{The example shows the result of `push_back` for different
  10267. JSON Pointers.,json_pointer__push_back}
  10268. @since version 3.6.0
  10269. */
  10270. void push_back(const std::string& token)
  10271. {
  10272. reference_tokens.push_back(token);
  10273. }
  10274. /// @copydoc push_back(const std::string&)
  10275. void push_back(std::string&& token)
  10276. {
  10277. reference_tokens.push_back(std::move(token));
  10278. }
  10279. /*!
  10280. @brief return whether pointer points to the root document
  10281. @return true iff the JSON pointer points to the root document
  10282. @complexity Constant.
  10283. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  10284. @liveexample{The example shows the result of `empty` for different JSON
  10285. Pointers.,json_pointer__empty}
  10286. @since version 3.6.0
  10287. */
  10288. bool empty() const noexcept
  10289. {
  10290. return reference_tokens.empty();
  10291. }
  10292. private:
  10293. /*!
  10294. @param[in] s reference token to be converted into an array index
  10295. @return integer representation of @a s
  10296. @throw parse_error.106 if an array index begins with '0'
  10297. @throw parse_error.109 if an array index begins not with a digit
  10298. @throw out_of_range.404 if string @a s could not be converted to an integer
  10299. @throw out_of_range.410 if an array index exceeds size_type
  10300. */
  10301. static typename BasicJsonType::size_type array_index(const std::string& s)
  10302. {
  10303. using size_type = typename BasicJsonType::size_type;
  10304. // error condition (cf. RFC 6901, Sect. 4)
  10305. if (JSON_HEDLEY_UNLIKELY(s.size() > 1 && s[0] == '0'))
  10306. {
  10307. JSON_THROW(detail::parse_error::create(106, 0,
  10308. "array index '" + s +
  10309. "' must not begin with '0'"));
  10310. }
  10311. // error condition (cf. RFC 6901, Sect. 4)
  10312. if (JSON_HEDLEY_UNLIKELY(s.size() > 1 && !(s[0] >= '1' && s[0] <= '9')))
  10313. {
  10314. JSON_THROW(detail::parse_error::create(109, 0, "array index '" + s + "' is not a number"));
  10315. }
  10316. std::size_t processed_chars = 0;
  10317. unsigned long long res = 0;
  10318. JSON_TRY
  10319. {
  10320. res = std::stoull(s, &processed_chars);
  10321. }
  10322. JSON_CATCH(std::out_of_range&)
  10323. {
  10324. JSON_THROW(detail::out_of_range::create(404, "unresolved reference token '" + s + "'"));
  10325. }
  10326. // check if the string was completely read
  10327. if (JSON_HEDLEY_UNLIKELY(processed_chars != s.size()))
  10328. {
  10329. JSON_THROW(detail::out_of_range::create(404, "unresolved reference token '" + s + "'"));
  10330. }
  10331. // only triggered on special platforms (like 32bit), see also
  10332. // https://github.com/nlohmann/json/pull/2203
  10333. if (res >= static_cast<unsigned long long>((std::numeric_limits<size_type>::max)()))
  10334. {
  10335. JSON_THROW(detail::out_of_range::create(410, "array index " + s + " exceeds size_type")); // LCOV_EXCL_LINE
  10336. }
  10337. return static_cast<size_type>(res);
  10338. }
  10339. json_pointer top() const
  10340. {
  10341. if (JSON_HEDLEY_UNLIKELY(empty()))
  10342. {
  10343. JSON_THROW(detail::out_of_range::create(405, "JSON pointer has no parent"));
  10344. }
  10345. json_pointer result = *this;
  10346. result.reference_tokens = {reference_tokens[0]};
  10347. return result;
  10348. }
  10349. /*!
  10350. @brief create and return a reference to the pointed to value
  10351. @complexity Linear in the number of reference tokens.
  10352. @throw parse_error.109 if array index is not a number
  10353. @throw type_error.313 if value cannot be unflattened
  10354. */
  10355. BasicJsonType& get_and_create(BasicJsonType& j) const
  10356. {
  10357. auto result = &j;
  10358. // in case no reference tokens exist, return a reference to the JSON value
  10359. // j which will be overwritten by a primitive value
  10360. for (const auto& reference_token : reference_tokens)
  10361. {
  10362. switch (result->type())
  10363. {
  10364. case detail::value_t::null:
  10365. {
  10366. if (reference_token == "0")
  10367. {
  10368. // start a new array if reference token is 0
  10369. result = &result->operator[](0);
  10370. }
  10371. else
  10372. {
  10373. // start a new object otherwise
  10374. result = &result->operator[](reference_token);
  10375. }
  10376. break;
  10377. }
  10378. case detail::value_t::object:
  10379. {
  10380. // create an entry in the object
  10381. result = &result->operator[](reference_token);
  10382. break;
  10383. }
  10384. case detail::value_t::array:
  10385. {
  10386. // create an entry in the array
  10387. result = &result->operator[](array_index(reference_token));
  10388. break;
  10389. }
  10390. /*
  10391. The following code is only reached if there exists a reference
  10392. token _and_ the current value is primitive. In this case, we have
  10393. an error situation, because primitive values may only occur as
  10394. single value; that is, with an empty list of reference tokens.
  10395. */
  10396. default:
  10397. JSON_THROW(detail::type_error::create(313, "invalid value to unflatten"));
  10398. }
  10399. }
  10400. return *result;
  10401. }
  10402. /*!
  10403. @brief return a reference to the pointed to value
  10404. @note This version does not throw if a value is not present, but tries to
  10405. create nested values instead. For instance, calling this function
  10406. with pointer `"/this/that"` on a null value is equivalent to calling
  10407. `operator[]("this").operator[]("that")` on that value, effectively
  10408. changing the null value to an object.
  10409. @param[in] ptr a JSON value
  10410. @return reference to the JSON value pointed to by the JSON pointer
  10411. @complexity Linear in the length of the JSON pointer.
  10412. @throw parse_error.106 if an array index begins with '0'
  10413. @throw parse_error.109 if an array index was not a number
  10414. @throw out_of_range.404 if the JSON pointer can not be resolved
  10415. */
  10416. BasicJsonType& get_unchecked(BasicJsonType* ptr) const
  10417. {
  10418. for (const auto& reference_token : reference_tokens)
  10419. {
  10420. // convert null values to arrays or objects before continuing
  10421. if (ptr->is_null())
  10422. {
  10423. // check if reference token is a number
  10424. const bool nums =
  10425. std::all_of(reference_token.begin(), reference_token.end(),
  10426. [](const unsigned char x)
  10427. {
  10428. return std::isdigit(x);
  10429. });
  10430. // change value to array for numbers or "-" or to object otherwise
  10431. *ptr = (nums || reference_token == "-")
  10432. ? detail::value_t::array
  10433. : detail::value_t::object;
  10434. }
  10435. switch (ptr->type())
  10436. {
  10437. case detail::value_t::object:
  10438. {
  10439. // use unchecked object access
  10440. ptr = &ptr->operator[](reference_token);
  10441. break;
  10442. }
  10443. case detail::value_t::array:
  10444. {
  10445. if (reference_token == "-")
  10446. {
  10447. // explicitly treat "-" as index beyond the end
  10448. ptr = &ptr->operator[](ptr->m_value.array->size());
  10449. }
  10450. else
  10451. {
  10452. // convert array index to number; unchecked access
  10453. ptr = &ptr->operator[](array_index(reference_token));
  10454. }
  10455. break;
  10456. }
  10457. default:
  10458. JSON_THROW(detail::out_of_range::create(404, "unresolved reference token '" + reference_token + "'"));
  10459. }
  10460. }
  10461. return *ptr;
  10462. }
  10463. /*!
  10464. @throw parse_error.106 if an array index begins with '0'
  10465. @throw parse_error.109 if an array index was not a number
  10466. @throw out_of_range.402 if the array index '-' is used
  10467. @throw out_of_range.404 if the JSON pointer can not be resolved
  10468. */
  10469. BasicJsonType& get_checked(BasicJsonType* ptr) const
  10470. {
  10471. for (const auto& reference_token : reference_tokens)
  10472. {
  10473. switch (ptr->type())
  10474. {
  10475. case detail::value_t::object:
  10476. {
  10477. // note: at performs range check
  10478. ptr = &ptr->at(reference_token);
  10479. break;
  10480. }
  10481. case detail::value_t::array:
  10482. {
  10483. if (JSON_HEDLEY_UNLIKELY(reference_token == "-"))
  10484. {
  10485. // "-" always fails the range check
  10486. JSON_THROW(detail::out_of_range::create(402,
  10487. "array index '-' (" + std::to_string(ptr->m_value.array->size()) +
  10488. ") is out of range"));
  10489. }
  10490. // note: at performs range check
  10491. ptr = &ptr->at(array_index(reference_token));
  10492. break;
  10493. }
  10494. default:
  10495. JSON_THROW(detail::out_of_range::create(404, "unresolved reference token '" + reference_token + "'"));
  10496. }
  10497. }
  10498. return *ptr;
  10499. }
  10500. /*!
  10501. @brief return a const reference to the pointed to value
  10502. @param[in] ptr a JSON value
  10503. @return const reference to the JSON value pointed to by the JSON
  10504. pointer
  10505. @throw parse_error.106 if an array index begins with '0'
  10506. @throw parse_error.109 if an array index was not a number
  10507. @throw out_of_range.402 if the array index '-' is used
  10508. @throw out_of_range.404 if the JSON pointer can not be resolved
  10509. */
  10510. const BasicJsonType& get_unchecked(const BasicJsonType* ptr) const
  10511. {
  10512. for (const auto& reference_token : reference_tokens)
  10513. {
  10514. switch (ptr->type())
  10515. {
  10516. case detail::value_t::object:
  10517. {
  10518. // use unchecked object access
  10519. ptr = &ptr->operator[](reference_token);
  10520. break;
  10521. }
  10522. case detail::value_t::array:
  10523. {
  10524. if (JSON_HEDLEY_UNLIKELY(reference_token == "-"))
  10525. {
  10526. // "-" cannot be used for const access
  10527. JSON_THROW(detail::out_of_range::create(402,
  10528. "array index '-' (" + std::to_string(ptr->m_value.array->size()) +
  10529. ") is out of range"));
  10530. }
  10531. // use unchecked array access
  10532. ptr = &ptr->operator[](array_index(reference_token));
  10533. break;
  10534. }
  10535. default:
  10536. JSON_THROW(detail::out_of_range::create(404, "unresolved reference token '" + reference_token + "'"));
  10537. }
  10538. }
  10539. return *ptr;
  10540. }
  10541. /*!
  10542. @throw parse_error.106 if an array index begins with '0'
  10543. @throw parse_error.109 if an array index was not a number
  10544. @throw out_of_range.402 if the array index '-' is used
  10545. @throw out_of_range.404 if the JSON pointer can not be resolved
  10546. */
  10547. const BasicJsonType& get_checked(const BasicJsonType* ptr) const
  10548. {
  10549. for (const auto& reference_token : reference_tokens)
  10550. {
  10551. switch (ptr->type())
  10552. {
  10553. case detail::value_t::object:
  10554. {
  10555. // note: at performs range check
  10556. ptr = &ptr->at(reference_token);
  10557. break;
  10558. }
  10559. case detail::value_t::array:
  10560. {
  10561. if (JSON_HEDLEY_UNLIKELY(reference_token == "-"))
  10562. {
  10563. // "-" always fails the range check
  10564. JSON_THROW(detail::out_of_range::create(402,
  10565. "array index '-' (" + std::to_string(ptr->m_value.array->size()) +
  10566. ") is out of range"));
  10567. }
  10568. // note: at performs range check
  10569. ptr = &ptr->at(array_index(reference_token));
  10570. break;
  10571. }
  10572. default:
  10573. JSON_THROW(detail::out_of_range::create(404, "unresolved reference token '" + reference_token + "'"));
  10574. }
  10575. }
  10576. return *ptr;
  10577. }
  10578. /*!
  10579. @throw parse_error.106 if an array index begins with '0'
  10580. @throw parse_error.109 if an array index was not a number
  10581. */
  10582. bool contains(const BasicJsonType* ptr) const
  10583. {
  10584. for (const auto& reference_token : reference_tokens)
  10585. {
  10586. switch (ptr->type())
  10587. {
  10588. case detail::value_t::object:
  10589. {
  10590. if (!ptr->contains(reference_token))
  10591. {
  10592. // we did not find the key in the object
  10593. return false;
  10594. }
  10595. ptr = &ptr->operator[](reference_token);
  10596. break;
  10597. }
  10598. case detail::value_t::array:
  10599. {
  10600. if (JSON_HEDLEY_UNLIKELY(reference_token == "-"))
  10601. {
  10602. // "-" always fails the range check
  10603. return false;
  10604. }
  10605. if (JSON_HEDLEY_UNLIKELY(reference_token.size() == 1 && !("0" <= reference_token && reference_token <= "9")))
  10606. {
  10607. // invalid char
  10608. return false;
  10609. }
  10610. if (JSON_HEDLEY_UNLIKELY(reference_token.size() > 1))
  10611. {
  10612. if (JSON_HEDLEY_UNLIKELY(!('1' <= reference_token[0] && reference_token[0] <= '9')))
  10613. {
  10614. // first char should be between '1' and '9'
  10615. return false;
  10616. }
  10617. for (std::size_t i = 1; i < reference_token.size(); i++)
  10618. {
  10619. if (JSON_HEDLEY_UNLIKELY(!('0' <= reference_token[i] && reference_token[i] <= '9')))
  10620. {
  10621. // other char should be between '0' and '9'
  10622. return false;
  10623. }
  10624. }
  10625. }
  10626. const auto idx = array_index(reference_token);
  10627. if (idx >= ptr->size())
  10628. {
  10629. // index out of range
  10630. return false;
  10631. }
  10632. ptr = &ptr->operator[](idx);
  10633. break;
  10634. }
  10635. default:
  10636. {
  10637. // we do not expect primitive values if there is still a
  10638. // reference token to process
  10639. return false;
  10640. }
  10641. }
  10642. }
  10643. // no reference token left means we found a primitive value
  10644. return true;
  10645. }
  10646. /*!
  10647. @brief split the string input to reference tokens
  10648. @note This function is only called by the json_pointer constructor.
  10649. All exceptions below are documented there.
  10650. @throw parse_error.107 if the pointer is not empty or begins with '/'
  10651. @throw parse_error.108 if character '~' is not followed by '0' or '1'
  10652. */
  10653. static std::vector<std::string> split(const std::string& reference_string)
  10654. {
  10655. std::vector<std::string> result;
  10656. // special case: empty reference string -> no reference tokens
  10657. if (reference_string.empty())
  10658. {
  10659. return result;
  10660. }
  10661. // check if nonempty reference string begins with slash
  10662. if (JSON_HEDLEY_UNLIKELY(reference_string[0] != '/'))
  10663. {
  10664. JSON_THROW(detail::parse_error::create(107, 1,
  10665. "JSON pointer must be empty or begin with '/' - was: '" +
  10666. reference_string + "'"));
  10667. }
  10668. // extract the reference tokens:
  10669. // - slash: position of the last read slash (or end of string)
  10670. // - start: position after the previous slash
  10671. for (
  10672. // search for the first slash after the first character
  10673. std::size_t slash = reference_string.find_first_of('/', 1),
  10674. // set the beginning of the first reference token
  10675. start = 1;
  10676. // we can stop if start == 0 (if slash == std::string::npos)
  10677. start != 0;
  10678. // set the beginning of the next reference token
  10679. // (will eventually be 0 if slash == std::string::npos)
  10680. start = (slash == std::string::npos) ? 0 : slash + 1,
  10681. // find next slash
  10682. slash = reference_string.find_first_of('/', start))
  10683. {
  10684. // use the text between the beginning of the reference token
  10685. // (start) and the last slash (slash).
  10686. auto reference_token = reference_string.substr(start, slash - start);
  10687. // check reference tokens are properly escaped
  10688. for (std::size_t pos = reference_token.find_first_of('~');
  10689. pos != std::string::npos;
  10690. pos = reference_token.find_first_of('~', pos + 1))
  10691. {
  10692. JSON_ASSERT(reference_token[pos] == '~');
  10693. // ~ must be followed by 0 or 1
  10694. if (JSON_HEDLEY_UNLIKELY(pos == reference_token.size() - 1 ||
  10695. (reference_token[pos + 1] != '0' &&
  10696. reference_token[pos + 1] != '1')))
  10697. {
  10698. JSON_THROW(detail::parse_error::create(108, 0, "escape character '~' must be followed with '0' or '1'"));
  10699. }
  10700. }
  10701. // finally, store the reference token
  10702. unescape(reference_token);
  10703. result.push_back(reference_token);
  10704. }
  10705. return result;
  10706. }
  10707. /*!
  10708. @brief replace all occurrences of a substring by another string
  10709. @param[in,out] s the string to manipulate; changed so that all
  10710. occurrences of @a f are replaced with @a t
  10711. @param[in] f the substring to replace with @a t
  10712. @param[in] t the string to replace @a f
  10713. @pre The search string @a f must not be empty. **This precondition is
  10714. enforced with an assertion.**
  10715. @since version 2.0.0
  10716. */
  10717. static void replace_substring(std::string& s, const std::string& f,
  10718. const std::string& t)
  10719. {
  10720. JSON_ASSERT(!f.empty());
  10721. for (auto pos = s.find(f); // find first occurrence of f
  10722. pos != std::string::npos; // make sure f was found
  10723. s.replace(pos, f.size(), t), // replace with t, and
  10724. pos = s.find(f, pos + t.size())) // find next occurrence of f
  10725. {}
  10726. }
  10727. /// escape "~" to "~0" and "/" to "~1"
  10728. static std::string escape(std::string s)
  10729. {
  10730. replace_substring(s, "~", "~0");
  10731. replace_substring(s, "/", "~1");
  10732. return s;
  10733. }
  10734. /// unescape "~1" to tilde and "~0" to slash (order is important!)
  10735. static void unescape(std::string& s)
  10736. {
  10737. replace_substring(s, "~1", "/");
  10738. replace_substring(s, "~0", "~");
  10739. }
  10740. /*!
  10741. @param[in] reference_string the reference string to the current value
  10742. @param[in] value the value to consider
  10743. @param[in,out] result the result object to insert values to
  10744. @note Empty objects or arrays are flattened to `null`.
  10745. */
  10746. static void flatten(const std::string& reference_string,
  10747. const BasicJsonType& value,
  10748. BasicJsonType& result)
  10749. {
  10750. switch (value.type())
  10751. {
  10752. case detail::value_t::array:
  10753. {
  10754. if (value.m_value.array->empty())
  10755. {
  10756. // flatten empty array as null
  10757. result[reference_string] = nullptr;
  10758. }
  10759. else
  10760. {
  10761. // iterate array and use index as reference string
  10762. for (std::size_t i = 0; i < value.m_value.array->size(); ++i)
  10763. {
  10764. flatten(reference_string + "/" + std::to_string(i),
  10765. value.m_value.array->operator[](i), result);
  10766. }
  10767. }
  10768. break;
  10769. }
  10770. case detail::value_t::object:
  10771. {
  10772. if (value.m_value.object->empty())
  10773. {
  10774. // flatten empty object as null
  10775. result[reference_string] = nullptr;
  10776. }
  10777. else
  10778. {
  10779. // iterate object and use keys as reference string
  10780. for (const auto& element : *value.m_value.object)
  10781. {
  10782. flatten(reference_string + "/" + escape(element.first), element.second, result);
  10783. }
  10784. }
  10785. break;
  10786. }
  10787. default:
  10788. {
  10789. // add primitive value with its reference string
  10790. result[reference_string] = value;
  10791. break;
  10792. }
  10793. }
  10794. }
  10795. /*!
  10796. @param[in] value flattened JSON
  10797. @return unflattened JSON
  10798. @throw parse_error.109 if array index is not a number
  10799. @throw type_error.314 if value is not an object
  10800. @throw type_error.315 if object values are not primitive
  10801. @throw type_error.313 if value cannot be unflattened
  10802. */
  10803. static BasicJsonType
  10804. unflatten(const BasicJsonType& value)
  10805. {
  10806. if (JSON_HEDLEY_UNLIKELY(!value.is_object()))
  10807. {
  10808. JSON_THROW(detail::type_error::create(314, "only objects can be unflattened"));
  10809. }
  10810. BasicJsonType result;
  10811. // iterate the JSON object values
  10812. for (const auto& element : *value.m_value.object)
  10813. {
  10814. if (JSON_HEDLEY_UNLIKELY(!element.second.is_primitive()))
  10815. {
  10816. JSON_THROW(detail::type_error::create(315, "values in object must be primitive"));
  10817. }
  10818. // assign value to reference pointed to by JSON pointer; Note that if
  10819. // the JSON pointer is "" (i.e., points to the whole value), function
  10820. // get_and_create returns a reference to result itself. An assignment
  10821. // will then create a primitive value.
  10822. json_pointer(element.first).get_and_create(result) = element.second;
  10823. }
  10824. return result;
  10825. }
  10826. /*!
  10827. @brief compares two JSON pointers for equality
  10828. @param[in] lhs JSON pointer to compare
  10829. @param[in] rhs JSON pointer to compare
  10830. @return whether @a lhs is equal to @a rhs
  10831. @complexity Linear in the length of the JSON pointer
  10832. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  10833. */
  10834. friend bool operator==(json_pointer const& lhs,
  10835. json_pointer const& rhs) noexcept
  10836. {
  10837. return lhs.reference_tokens == rhs.reference_tokens;
  10838. }
  10839. /*!
  10840. @brief compares two JSON pointers for inequality
  10841. @param[in] lhs JSON pointer to compare
  10842. @param[in] rhs JSON pointer to compare
  10843. @return whether @a lhs is not equal @a rhs
  10844. @complexity Linear in the length of the JSON pointer
  10845. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  10846. */
  10847. friend bool operator!=(json_pointer const& lhs,
  10848. json_pointer const& rhs) noexcept
  10849. {
  10850. return !(lhs == rhs);
  10851. }
  10852. /// the reference tokens
  10853. std::vector<std::string> reference_tokens;
  10854. };
  10855. } // namespace nlohmann
  10856. // #include <nlohmann/detail/json_ref.hpp>
  10857. #include <initializer_list>
  10858. #include <utility>
  10859. // #include <nlohmann/detail/meta/type_traits.hpp>
  10860. namespace nlohmann
  10861. {
  10862. namespace detail
  10863. {
  10864. template<typename BasicJsonType>
  10865. class json_ref
  10866. {
  10867. public:
  10868. using value_type = BasicJsonType;
  10869. json_ref(value_type&& value)
  10870. : owned_value(std::move(value))
  10871. , value_ref(&owned_value)
  10872. , is_rvalue(true)
  10873. {}
  10874. json_ref(const value_type& value)
  10875. : value_ref(const_cast<value_type*>(&value))
  10876. , is_rvalue(false)
  10877. {}
  10878. json_ref(std::initializer_list<json_ref> init)
  10879. : owned_value(init)
  10880. , value_ref(&owned_value)
  10881. , is_rvalue(true)
  10882. {}
  10883. template <
  10884. class... Args,
  10885. enable_if_t<std::is_constructible<value_type, Args...>::value, int> = 0 >
  10886. json_ref(Args && ... args)
  10887. : owned_value(std::forward<Args>(args)...)
  10888. , value_ref(&owned_value)
  10889. , is_rvalue(true)
  10890. {}
  10891. // class should be movable only
  10892. json_ref(json_ref&&) = default;
  10893. json_ref(const json_ref&) = delete;
  10894. json_ref& operator=(const json_ref&) = delete;
  10895. json_ref& operator=(json_ref&&) = delete;
  10896. ~json_ref() = default;
  10897. value_type moved_or_copied() const
  10898. {
  10899. if (is_rvalue)
  10900. {
  10901. return std::move(*value_ref);
  10902. }
  10903. return *value_ref;
  10904. }
  10905. value_type const& operator*() const
  10906. {
  10907. return *static_cast<value_type const*>(value_ref);
  10908. }
  10909. value_type const* operator->() const
  10910. {
  10911. return static_cast<value_type const*>(value_ref);
  10912. }
  10913. private:
  10914. mutable value_type owned_value = nullptr;
  10915. value_type* value_ref = nullptr;
  10916. const bool is_rvalue = true;
  10917. };
  10918. } // namespace detail
  10919. } // namespace nlohmann
  10920. // #include <nlohmann/detail/macro_scope.hpp>
  10921. // #include <nlohmann/detail/meta/cpp_future.hpp>
  10922. // #include <nlohmann/detail/meta/type_traits.hpp>
  10923. // #include <nlohmann/detail/output/binary_writer.hpp>
  10924. #include <algorithm> // reverse
  10925. #include <array> // array
  10926. #include <cstdint> // uint8_t, uint16_t, uint32_t, uint64_t
  10927. #include <cstring> // memcpy
  10928. #include <limits> // numeric_limits
  10929. #include <string> // string
  10930. #include <cmath> // isnan, isinf
  10931. // #include <nlohmann/detail/input/binary_reader.hpp>
  10932. // #include <nlohmann/detail/macro_scope.hpp>
  10933. // #include <nlohmann/detail/output/output_adapters.hpp>
  10934. #include <algorithm> // copy
  10935. #include <cstddef> // size_t
  10936. #include <ios> // streamsize
  10937. #include <iterator> // back_inserter
  10938. #include <memory> // shared_ptr, make_shared
  10939. #include <ostream> // basic_ostream
  10940. #include <string> // basic_string
  10941. #include <vector> // vector
  10942. // #include <nlohmann/detail/macro_scope.hpp>
  10943. namespace nlohmann
  10944. {
  10945. namespace detail
  10946. {
  10947. /// abstract output adapter interface
  10948. template<typename CharType> struct output_adapter_protocol
  10949. {
  10950. virtual void write_character(CharType c) = 0;
  10951. virtual void write_characters(const CharType* s, std::size_t length) = 0;
  10952. virtual ~output_adapter_protocol() = default;
  10953. };
  10954. /// a type to simplify interfaces
  10955. template<typename CharType>
  10956. using output_adapter_t = std::shared_ptr<output_adapter_protocol<CharType>>;
  10957. /// output adapter for byte vectors
  10958. template<typename CharType>
  10959. class output_vector_adapter : public output_adapter_protocol<CharType>
  10960. {
  10961. public:
  10962. explicit output_vector_adapter(std::vector<CharType>& vec) noexcept
  10963. : v(vec)
  10964. {}
  10965. void write_character(CharType c) override
  10966. {
  10967. v.push_back(c);
  10968. }
  10969. JSON_HEDLEY_NON_NULL(2)
  10970. void write_characters(const CharType* s, std::size_t length) override
  10971. {
  10972. std::copy(s, s + length, std::back_inserter(v));
  10973. }
  10974. private:
  10975. std::vector<CharType>& v;
  10976. };
  10977. /// output adapter for output streams
  10978. template<typename CharType>
  10979. class output_stream_adapter : public output_adapter_protocol<CharType>
  10980. {
  10981. public:
  10982. explicit output_stream_adapter(std::basic_ostream<CharType>& s) noexcept
  10983. : stream(s)
  10984. {}
  10985. void write_character(CharType c) override
  10986. {
  10987. stream.put(c);
  10988. }
  10989. JSON_HEDLEY_NON_NULL(2)
  10990. void write_characters(const CharType* s, std::size_t length) override
  10991. {
  10992. stream.write(s, static_cast<std::streamsize>(length));
  10993. }
  10994. private:
  10995. std::basic_ostream<CharType>& stream;
  10996. };
  10997. /// output adapter for basic_string
  10998. template<typename CharType, typename StringType = std::basic_string<CharType>>
  10999. class output_string_adapter : public output_adapter_protocol<CharType>
  11000. {
  11001. public:
  11002. explicit output_string_adapter(StringType& s) noexcept
  11003. : str(s)
  11004. {}
  11005. void write_character(CharType c) override
  11006. {
  11007. str.push_back(c);
  11008. }
  11009. JSON_HEDLEY_NON_NULL(2)
  11010. void write_characters(const CharType* s, std::size_t length) override
  11011. {
  11012. str.append(s, length);
  11013. }
  11014. private:
  11015. StringType& str;
  11016. };
  11017. template<typename CharType, typename StringType = std::basic_string<CharType>>
  11018. class output_adapter
  11019. {
  11020. public:
  11021. output_adapter(std::vector<CharType>& vec)
  11022. : oa(std::make_shared<output_vector_adapter<CharType>>(vec)) {}
  11023. output_adapter(std::basic_ostream<CharType>& s)
  11024. : oa(std::make_shared<output_stream_adapter<CharType>>(s)) {}
  11025. output_adapter(StringType& s)
  11026. : oa(std::make_shared<output_string_adapter<CharType, StringType>>(s)) {}
  11027. operator output_adapter_t<CharType>()
  11028. {
  11029. return oa;
  11030. }
  11031. private:
  11032. output_adapter_t<CharType> oa = nullptr;
  11033. };
  11034. } // namespace detail
  11035. } // namespace nlohmann
  11036. namespace nlohmann
  11037. {
  11038. namespace detail
  11039. {
  11040. ///////////////////
  11041. // binary writer //
  11042. ///////////////////
  11043. /*!
  11044. @brief serialization to CBOR and MessagePack values
  11045. */
  11046. template<typename BasicJsonType, typename CharType>
  11047. class binary_writer
  11048. {
  11049. using string_t = typename BasicJsonType::string_t;
  11050. using binary_t = typename BasicJsonType::binary_t;
  11051. using number_float_t = typename BasicJsonType::number_float_t;
  11052. public:
  11053. /*!
  11054. @brief create a binary writer
  11055. @param[in] adapter output adapter to write to
  11056. */
  11057. explicit binary_writer(output_adapter_t<CharType> adapter) : oa(adapter)
  11058. {
  11059. JSON_ASSERT(oa);
  11060. }
  11061. /*!
  11062. @param[in] j JSON value to serialize
  11063. @pre j.type() == value_t::object
  11064. */
  11065. void write_bson(const BasicJsonType& j)
  11066. {
  11067. switch (j.type())
  11068. {
  11069. case value_t::object:
  11070. {
  11071. write_bson_object(*j.m_value.object);
  11072. break;
  11073. }
  11074. default:
  11075. {
  11076. JSON_THROW(type_error::create(317, "to serialize to BSON, top-level type must be object, but is " + std::string(j.type_name())));
  11077. }
  11078. }
  11079. }
  11080. /*!
  11081. @param[in] j JSON value to serialize
  11082. */
  11083. void write_cbor(const BasicJsonType& j)
  11084. {
  11085. switch (j.type())
  11086. {
  11087. case value_t::null:
  11088. {
  11089. oa->write_character(to_char_type(0xF6));
  11090. break;
  11091. }
  11092. case value_t::boolean:
  11093. {
  11094. oa->write_character(j.m_value.boolean
  11095. ? to_char_type(0xF5)
  11096. : to_char_type(0xF4));
  11097. break;
  11098. }
  11099. case value_t::number_integer:
  11100. {
  11101. if (j.m_value.number_integer >= 0)
  11102. {
  11103. // CBOR does not differentiate between positive signed
  11104. // integers and unsigned integers. Therefore, we used the
  11105. // code from the value_t::number_unsigned case here.
  11106. if (j.m_value.number_integer <= 0x17)
  11107. {
  11108. write_number(static_cast<std::uint8_t>(j.m_value.number_integer));
  11109. }
  11110. else if (j.m_value.number_integer <= (std::numeric_limits<std::uint8_t>::max)())
  11111. {
  11112. oa->write_character(to_char_type(0x18));
  11113. write_number(static_cast<std::uint8_t>(j.m_value.number_integer));
  11114. }
  11115. else if (j.m_value.number_integer <= (std::numeric_limits<std::uint16_t>::max)())
  11116. {
  11117. oa->write_character(to_char_type(0x19));
  11118. write_number(static_cast<std::uint16_t>(j.m_value.number_integer));
  11119. }
  11120. else if (j.m_value.number_integer <= (std::numeric_limits<std::uint32_t>::max)())
  11121. {
  11122. oa->write_character(to_char_type(0x1A));
  11123. write_number(static_cast<std::uint32_t>(j.m_value.number_integer));
  11124. }
  11125. else
  11126. {
  11127. oa->write_character(to_char_type(0x1B));
  11128. write_number(static_cast<std::uint64_t>(j.m_value.number_integer));
  11129. }
  11130. }
  11131. else
  11132. {
  11133. // The conversions below encode the sign in the first
  11134. // byte, and the value is converted to a positive number.
  11135. const auto positive_number = -1 - j.m_value.number_integer;
  11136. if (j.m_value.number_integer >= -24)
  11137. {
  11138. write_number(static_cast<std::uint8_t>(0x20 + positive_number));
  11139. }
  11140. else if (positive_number <= (std::numeric_limits<std::uint8_t>::max)())
  11141. {
  11142. oa->write_character(to_char_type(0x38));
  11143. write_number(static_cast<std::uint8_t>(positive_number));
  11144. }
  11145. else if (positive_number <= (std::numeric_limits<std::uint16_t>::max)())
  11146. {
  11147. oa->write_character(to_char_type(0x39));
  11148. write_number(static_cast<std::uint16_t>(positive_number));
  11149. }
  11150. else if (positive_number <= (std::numeric_limits<std::uint32_t>::max)())
  11151. {
  11152. oa->write_character(to_char_type(0x3A));
  11153. write_number(static_cast<std::uint32_t>(positive_number));
  11154. }
  11155. else
  11156. {
  11157. oa->write_character(to_char_type(0x3B));
  11158. write_number(static_cast<std::uint64_t>(positive_number));
  11159. }
  11160. }
  11161. break;
  11162. }
  11163. case value_t::number_unsigned:
  11164. {
  11165. if (j.m_value.number_unsigned <= 0x17)
  11166. {
  11167. write_number(static_cast<std::uint8_t>(j.m_value.number_unsigned));
  11168. }
  11169. else if (j.m_value.number_unsigned <= (std::numeric_limits<std::uint8_t>::max)())
  11170. {
  11171. oa->write_character(to_char_type(0x18));
  11172. write_number(static_cast<std::uint8_t>(j.m_value.number_unsigned));
  11173. }
  11174. else if (j.m_value.number_unsigned <= (std::numeric_limits<std::uint16_t>::max)())
  11175. {
  11176. oa->write_character(to_char_type(0x19));
  11177. write_number(static_cast<std::uint16_t>(j.m_value.number_unsigned));
  11178. }
  11179. else if (j.m_value.number_unsigned <= (std::numeric_limits<std::uint32_t>::max)())
  11180. {
  11181. oa->write_character(to_char_type(0x1A));
  11182. write_number(static_cast<std::uint32_t>(j.m_value.number_unsigned));
  11183. }
  11184. else
  11185. {
  11186. oa->write_character(to_char_type(0x1B));
  11187. write_number(static_cast<std::uint64_t>(j.m_value.number_unsigned));
  11188. }
  11189. break;
  11190. }
  11191. case value_t::number_float:
  11192. {
  11193. if (std::isnan(j.m_value.number_float))
  11194. {
  11195. // NaN is 0xf97e00 in CBOR
  11196. oa->write_character(to_char_type(0xF9));
  11197. oa->write_character(to_char_type(0x7E));
  11198. oa->write_character(to_char_type(0x00));
  11199. }
  11200. else if (std::isinf(j.m_value.number_float))
  11201. {
  11202. // Infinity is 0xf97c00, -Infinity is 0xf9fc00
  11203. oa->write_character(to_char_type(0xf9));
  11204. oa->write_character(j.m_value.number_float > 0 ? to_char_type(0x7C) : to_char_type(0xFC));
  11205. oa->write_character(to_char_type(0x00));
  11206. }
  11207. else
  11208. {
  11209. write_compact_float(j.m_value.number_float, detail::input_format_t::cbor);
  11210. }
  11211. break;
  11212. }
  11213. case value_t::string:
  11214. {
  11215. // step 1: write control byte and the string length
  11216. const auto N = j.m_value.string->size();
  11217. if (N <= 0x17)
  11218. {
  11219. write_number(static_cast<std::uint8_t>(0x60 + N));
  11220. }
  11221. else if (N <= (std::numeric_limits<std::uint8_t>::max)())
  11222. {
  11223. oa->write_character(to_char_type(0x78));
  11224. write_number(static_cast<std::uint8_t>(N));
  11225. }
  11226. else if (N <= (std::numeric_limits<std::uint16_t>::max)())
  11227. {
  11228. oa->write_character(to_char_type(0x79));
  11229. write_number(static_cast<std::uint16_t>(N));
  11230. }
  11231. else if (N <= (std::numeric_limits<std::uint32_t>::max)())
  11232. {
  11233. oa->write_character(to_char_type(0x7A));
  11234. write_number(static_cast<std::uint32_t>(N));
  11235. }
  11236. // LCOV_EXCL_START
  11237. else if (N <= (std::numeric_limits<std::uint64_t>::max)())
  11238. {
  11239. oa->write_character(to_char_type(0x7B));
  11240. write_number(static_cast<std::uint64_t>(N));
  11241. }
  11242. // LCOV_EXCL_STOP
  11243. // step 2: write the string
  11244. oa->write_characters(
  11245. reinterpret_cast<const CharType*>(j.m_value.string->c_str()),
  11246. j.m_value.string->size());
  11247. break;
  11248. }
  11249. case value_t::array:
  11250. {
  11251. // step 1: write control byte and the array size
  11252. const auto N = j.m_value.array->size();
  11253. if (N <= 0x17)
  11254. {
  11255. write_number(static_cast<std::uint8_t>(0x80 + N));
  11256. }
  11257. else if (N <= (std::numeric_limits<std::uint8_t>::max)())
  11258. {
  11259. oa->write_character(to_char_type(0x98));
  11260. write_number(static_cast<std::uint8_t>(N));
  11261. }
  11262. else if (N <= (std::numeric_limits<std::uint16_t>::max)())
  11263. {
  11264. oa->write_character(to_char_type(0x99));
  11265. write_number(static_cast<std::uint16_t>(N));
  11266. }
  11267. else if (N <= (std::numeric_limits<std::uint32_t>::max)())
  11268. {
  11269. oa->write_character(to_char_type(0x9A));
  11270. write_number(static_cast<std::uint32_t>(N));
  11271. }
  11272. // LCOV_EXCL_START
  11273. else if (N <= (std::numeric_limits<std::uint64_t>::max)())
  11274. {
  11275. oa->write_character(to_char_type(0x9B));
  11276. write_number(static_cast<std::uint64_t>(N));
  11277. }
  11278. // LCOV_EXCL_STOP
  11279. // step 2: write each element
  11280. for (const auto& el : *j.m_value.array)
  11281. {
  11282. write_cbor(el);
  11283. }
  11284. break;
  11285. }
  11286. case value_t::binary:
  11287. {
  11288. if (j.m_value.binary->has_subtype())
  11289. {
  11290. write_number(static_cast<std::uint8_t>(0xd8));
  11291. write_number(j.m_value.binary->subtype());
  11292. }
  11293. // step 1: write control byte and the binary array size
  11294. const auto N = j.m_value.binary->size();
  11295. if (N <= 0x17)
  11296. {
  11297. write_number(static_cast<std::uint8_t>(0x40 + N));
  11298. }
  11299. else if (N <= (std::numeric_limits<std::uint8_t>::max)())
  11300. {
  11301. oa->write_character(to_char_type(0x58));
  11302. write_number(static_cast<std::uint8_t>(N));
  11303. }
  11304. else if (N <= (std::numeric_limits<std::uint16_t>::max)())
  11305. {
  11306. oa->write_character(to_char_type(0x59));
  11307. write_number(static_cast<std::uint16_t>(N));
  11308. }
  11309. else if (N <= (std::numeric_limits<std::uint32_t>::max)())
  11310. {
  11311. oa->write_character(to_char_type(0x5A));
  11312. write_number(static_cast<std::uint32_t>(N));
  11313. }
  11314. // LCOV_EXCL_START
  11315. else if (N <= (std::numeric_limits<std::uint64_t>::max)())
  11316. {
  11317. oa->write_character(to_char_type(0x5B));
  11318. write_number(static_cast<std::uint64_t>(N));
  11319. }
  11320. // LCOV_EXCL_STOP
  11321. // step 2: write each element
  11322. oa->write_characters(
  11323. reinterpret_cast<const CharType*>(j.m_value.binary->data()),
  11324. N);
  11325. break;
  11326. }
  11327. case value_t::object:
  11328. {
  11329. // step 1: write control byte and the object size
  11330. const auto N = j.m_value.object->size();
  11331. if (N <= 0x17)
  11332. {
  11333. write_number(static_cast<std::uint8_t>(0xA0 + N));
  11334. }
  11335. else if (N <= (std::numeric_limits<std::uint8_t>::max)())
  11336. {
  11337. oa->write_character(to_char_type(0xB8));
  11338. write_number(static_cast<std::uint8_t>(N));
  11339. }
  11340. else if (N <= (std::numeric_limits<std::uint16_t>::max)())
  11341. {
  11342. oa->write_character(to_char_type(0xB9));
  11343. write_number(static_cast<std::uint16_t>(N));
  11344. }
  11345. else if (N <= (std::numeric_limits<std::uint32_t>::max)())
  11346. {
  11347. oa->write_character(to_char_type(0xBA));
  11348. write_number(static_cast<std::uint32_t>(N));
  11349. }
  11350. // LCOV_EXCL_START
  11351. else if (N <= (std::numeric_limits<std::uint64_t>::max)())
  11352. {
  11353. oa->write_character(to_char_type(0xBB));
  11354. write_number(static_cast<std::uint64_t>(N));
  11355. }
  11356. // LCOV_EXCL_STOP
  11357. // step 2: write each element
  11358. for (const auto& el : *j.m_value.object)
  11359. {
  11360. write_cbor(el.first);
  11361. write_cbor(el.second);
  11362. }
  11363. break;
  11364. }
  11365. default:
  11366. break;
  11367. }
  11368. }
  11369. /*!
  11370. @param[in] j JSON value to serialize
  11371. */
  11372. void write_msgpack(const BasicJsonType& j)
  11373. {
  11374. switch (j.type())
  11375. {
  11376. case value_t::null: // nil
  11377. {
  11378. oa->write_character(to_char_type(0xC0));
  11379. break;
  11380. }
  11381. case value_t::boolean: // true and false
  11382. {
  11383. oa->write_character(j.m_value.boolean
  11384. ? to_char_type(0xC3)
  11385. : to_char_type(0xC2));
  11386. break;
  11387. }
  11388. case value_t::number_integer:
  11389. {
  11390. if (j.m_value.number_integer >= 0)
  11391. {
  11392. // MessagePack does not differentiate between positive
  11393. // signed integers and unsigned integers. Therefore, we used
  11394. // the code from the value_t::number_unsigned case here.
  11395. if (j.m_value.number_unsigned < 128)
  11396. {
  11397. // positive fixnum
  11398. write_number(static_cast<std::uint8_t>(j.m_value.number_integer));
  11399. }
  11400. else if (j.m_value.number_unsigned <= (std::numeric_limits<std::uint8_t>::max)())
  11401. {
  11402. // uint 8
  11403. oa->write_character(to_char_type(0xCC));
  11404. write_number(static_cast<std::uint8_t>(j.m_value.number_integer));
  11405. }
  11406. else if (j.m_value.number_unsigned <= (std::numeric_limits<std::uint16_t>::max)())
  11407. {
  11408. // uint 16
  11409. oa->write_character(to_char_type(0xCD));
  11410. write_number(static_cast<std::uint16_t>(j.m_value.number_integer));
  11411. }
  11412. else if (j.m_value.number_unsigned <= (std::numeric_limits<std::uint32_t>::max)())
  11413. {
  11414. // uint 32
  11415. oa->write_character(to_char_type(0xCE));
  11416. write_number(static_cast<std::uint32_t>(j.m_value.number_integer));
  11417. }
  11418. else if (j.m_value.number_unsigned <= (std::numeric_limits<std::uint64_t>::max)())
  11419. {
  11420. // uint 64
  11421. oa->write_character(to_char_type(0xCF));
  11422. write_number(static_cast<std::uint64_t>(j.m_value.number_integer));
  11423. }
  11424. }
  11425. else
  11426. {
  11427. if (j.m_value.number_integer >= -32)
  11428. {
  11429. // negative fixnum
  11430. write_number(static_cast<std::int8_t>(j.m_value.number_integer));
  11431. }
  11432. else if (j.m_value.number_integer >= (std::numeric_limits<std::int8_t>::min)() &&
  11433. j.m_value.number_integer <= (std::numeric_limits<std::int8_t>::max)())
  11434. {
  11435. // int 8
  11436. oa->write_character(to_char_type(0xD0));
  11437. write_number(static_cast<std::int8_t>(j.m_value.number_integer));
  11438. }
  11439. else if (j.m_value.number_integer >= (std::numeric_limits<std::int16_t>::min)() &&
  11440. j.m_value.number_integer <= (std::numeric_limits<std::int16_t>::max)())
  11441. {
  11442. // int 16
  11443. oa->write_character(to_char_type(0xD1));
  11444. write_number(static_cast<std::int16_t>(j.m_value.number_integer));
  11445. }
  11446. else if (j.m_value.number_integer >= (std::numeric_limits<std::int32_t>::min)() &&
  11447. j.m_value.number_integer <= (std::numeric_limits<std::int32_t>::max)())
  11448. {
  11449. // int 32
  11450. oa->write_character(to_char_type(0xD2));
  11451. write_number(static_cast<std::int32_t>(j.m_value.number_integer));
  11452. }
  11453. else if (j.m_value.number_integer >= (std::numeric_limits<std::int64_t>::min)() &&
  11454. j.m_value.number_integer <= (std::numeric_limits<std::int64_t>::max)())
  11455. {
  11456. // int 64
  11457. oa->write_character(to_char_type(0xD3));
  11458. write_number(static_cast<std::int64_t>(j.m_value.number_integer));
  11459. }
  11460. }
  11461. break;
  11462. }
  11463. case value_t::number_unsigned:
  11464. {
  11465. if (j.m_value.number_unsigned < 128)
  11466. {
  11467. // positive fixnum
  11468. write_number(static_cast<std::uint8_t>(j.m_value.number_integer));
  11469. }
  11470. else if (j.m_value.number_unsigned <= (std::numeric_limits<std::uint8_t>::max)())
  11471. {
  11472. // uint 8
  11473. oa->write_character(to_char_type(0xCC));
  11474. write_number(static_cast<std::uint8_t>(j.m_value.number_integer));
  11475. }
  11476. else if (j.m_value.number_unsigned <= (std::numeric_limits<std::uint16_t>::max)())
  11477. {
  11478. // uint 16
  11479. oa->write_character(to_char_type(0xCD));
  11480. write_number(static_cast<std::uint16_t>(j.m_value.number_integer));
  11481. }
  11482. else if (j.m_value.number_unsigned <= (std::numeric_limits<std::uint32_t>::max)())
  11483. {
  11484. // uint 32
  11485. oa->write_character(to_char_type(0xCE));
  11486. write_number(static_cast<std::uint32_t>(j.m_value.number_integer));
  11487. }
  11488. else if (j.m_value.number_unsigned <= (std::numeric_limits<std::uint64_t>::max)())
  11489. {
  11490. // uint 64
  11491. oa->write_character(to_char_type(0xCF));
  11492. write_number(static_cast<std::uint64_t>(j.m_value.number_integer));
  11493. }
  11494. break;
  11495. }
  11496. case value_t::number_float:
  11497. {
  11498. write_compact_float(j.m_value.number_float, detail::input_format_t::msgpack);
  11499. break;
  11500. }
  11501. case value_t::string:
  11502. {
  11503. // step 1: write control byte and the string length
  11504. const auto N = j.m_value.string->size();
  11505. if (N <= 31)
  11506. {
  11507. // fixstr
  11508. write_number(static_cast<std::uint8_t>(0xA0 | N));
  11509. }
  11510. else if (N <= (std::numeric_limits<std::uint8_t>::max)())
  11511. {
  11512. // str 8
  11513. oa->write_character(to_char_type(0xD9));
  11514. write_number(static_cast<std::uint8_t>(N));
  11515. }
  11516. else if (N <= (std::numeric_limits<std::uint16_t>::max)())
  11517. {
  11518. // str 16
  11519. oa->write_character(to_char_type(0xDA));
  11520. write_number(static_cast<std::uint16_t>(N));
  11521. }
  11522. else if (N <= (std::numeric_limits<std::uint32_t>::max)())
  11523. {
  11524. // str 32
  11525. oa->write_character(to_char_type(0xDB));
  11526. write_number(static_cast<std::uint32_t>(N));
  11527. }
  11528. // step 2: write the string
  11529. oa->write_characters(
  11530. reinterpret_cast<const CharType*>(j.m_value.string->c_str()),
  11531. j.m_value.string->size());
  11532. break;
  11533. }
  11534. case value_t::array:
  11535. {
  11536. // step 1: write control byte and the array size
  11537. const auto N = j.m_value.array->size();
  11538. if (N <= 15)
  11539. {
  11540. // fixarray
  11541. write_number(static_cast<std::uint8_t>(0x90 | N));
  11542. }
  11543. else if (N <= (std::numeric_limits<std::uint16_t>::max)())
  11544. {
  11545. // array 16
  11546. oa->write_character(to_char_type(0xDC));
  11547. write_number(static_cast<std::uint16_t>(N));
  11548. }
  11549. else if (N <= (std::numeric_limits<std::uint32_t>::max)())
  11550. {
  11551. // array 32
  11552. oa->write_character(to_char_type(0xDD));
  11553. write_number(static_cast<std::uint32_t>(N));
  11554. }
  11555. // step 2: write each element
  11556. for (const auto& el : *j.m_value.array)
  11557. {
  11558. write_msgpack(el);
  11559. }
  11560. break;
  11561. }
  11562. case value_t::binary:
  11563. {
  11564. // step 0: determine if the binary type has a set subtype to
  11565. // determine whether or not to use the ext or fixext types
  11566. const bool use_ext = j.m_value.binary->has_subtype();
  11567. // step 1: write control byte and the byte string length
  11568. const auto N = j.m_value.binary->size();
  11569. if (N <= (std::numeric_limits<std::uint8_t>::max)())
  11570. {
  11571. std::uint8_t output_type{};
  11572. bool fixed = true;
  11573. if (use_ext)
  11574. {
  11575. switch (N)
  11576. {
  11577. case 1:
  11578. output_type = 0xD4; // fixext 1
  11579. break;
  11580. case 2:
  11581. output_type = 0xD5; // fixext 2
  11582. break;
  11583. case 4:
  11584. output_type = 0xD6; // fixext 4
  11585. break;
  11586. case 8:
  11587. output_type = 0xD7; // fixext 8
  11588. break;
  11589. case 16:
  11590. output_type = 0xD8; // fixext 16
  11591. break;
  11592. default:
  11593. output_type = 0xC7; // ext 8
  11594. fixed = false;
  11595. break;
  11596. }
  11597. }
  11598. else
  11599. {
  11600. output_type = 0xC4; // bin 8
  11601. fixed = false;
  11602. }
  11603. oa->write_character(to_char_type(output_type));
  11604. if (!fixed)
  11605. {
  11606. write_number(static_cast<std::uint8_t>(N));
  11607. }
  11608. }
  11609. else if (N <= (std::numeric_limits<std::uint16_t>::max)())
  11610. {
  11611. std::uint8_t output_type = use_ext
  11612. ? 0xC8 // ext 16
  11613. : 0xC5; // bin 16
  11614. oa->write_character(to_char_type(output_type));
  11615. write_number(static_cast<std::uint16_t>(N));
  11616. }
  11617. else if (N <= (std::numeric_limits<std::uint32_t>::max)())
  11618. {
  11619. std::uint8_t output_type = use_ext
  11620. ? 0xC9 // ext 32
  11621. : 0xC6; // bin 32
  11622. oa->write_character(to_char_type(output_type));
  11623. write_number(static_cast<std::uint32_t>(N));
  11624. }
  11625. // step 1.5: if this is an ext type, write the subtype
  11626. if (use_ext)
  11627. {
  11628. write_number(static_cast<std::int8_t>(j.m_value.binary->subtype()));
  11629. }
  11630. // step 2: write the byte string
  11631. oa->write_characters(
  11632. reinterpret_cast<const CharType*>(j.m_value.binary->data()),
  11633. N);
  11634. break;
  11635. }
  11636. case value_t::object:
  11637. {
  11638. // step 1: write control byte and the object size
  11639. const auto N = j.m_value.object->size();
  11640. if (N <= 15)
  11641. {
  11642. // fixmap
  11643. write_number(static_cast<std::uint8_t>(0x80 | (N & 0xF)));
  11644. }
  11645. else if (N <= (std::numeric_limits<std::uint16_t>::max)())
  11646. {
  11647. // map 16
  11648. oa->write_character(to_char_type(0xDE));
  11649. write_number(static_cast<std::uint16_t>(N));
  11650. }
  11651. else if (N <= (std::numeric_limits<std::uint32_t>::max)())
  11652. {
  11653. // map 32
  11654. oa->write_character(to_char_type(0xDF));
  11655. write_number(static_cast<std::uint32_t>(N));
  11656. }
  11657. // step 2: write each element
  11658. for (const auto& el : *j.m_value.object)
  11659. {
  11660. write_msgpack(el.first);
  11661. write_msgpack(el.second);
  11662. }
  11663. break;
  11664. }
  11665. default:
  11666. break;
  11667. }
  11668. }
  11669. /*!
  11670. @param[in] j JSON value to serialize
  11671. @param[in] use_count whether to use '#' prefixes (optimized format)
  11672. @param[in] use_type whether to use '$' prefixes (optimized format)
  11673. @param[in] add_prefix whether prefixes need to be used for this value
  11674. */
  11675. void write_ubjson(const BasicJsonType& j, const bool use_count,
  11676. const bool use_type, const bool add_prefix = true)
  11677. {
  11678. switch (j.type())
  11679. {
  11680. case value_t::null:
  11681. {
  11682. if (add_prefix)
  11683. {
  11684. oa->write_character(to_char_type('Z'));
  11685. }
  11686. break;
  11687. }
  11688. case value_t::boolean:
  11689. {
  11690. if (add_prefix)
  11691. {
  11692. oa->write_character(j.m_value.boolean
  11693. ? to_char_type('T')
  11694. : to_char_type('F'));
  11695. }
  11696. break;
  11697. }
  11698. case value_t::number_integer:
  11699. {
  11700. write_number_with_ubjson_prefix(j.m_value.number_integer, add_prefix);
  11701. break;
  11702. }
  11703. case value_t::number_unsigned:
  11704. {
  11705. write_number_with_ubjson_prefix(j.m_value.number_unsigned, add_prefix);
  11706. break;
  11707. }
  11708. case value_t::number_float:
  11709. {
  11710. write_number_with_ubjson_prefix(j.m_value.number_float, add_prefix);
  11711. break;
  11712. }
  11713. case value_t::string:
  11714. {
  11715. if (add_prefix)
  11716. {
  11717. oa->write_character(to_char_type('S'));
  11718. }
  11719. write_number_with_ubjson_prefix(j.m_value.string->size(), true);
  11720. oa->write_characters(
  11721. reinterpret_cast<const CharType*>(j.m_value.string->c_str()),
  11722. j.m_value.string->size());
  11723. break;
  11724. }
  11725. case value_t::array:
  11726. {
  11727. if (add_prefix)
  11728. {
  11729. oa->write_character(to_char_type('['));
  11730. }
  11731. bool prefix_required = true;
  11732. if (use_type && !j.m_value.array->empty())
  11733. {
  11734. JSON_ASSERT(use_count);
  11735. const CharType first_prefix = ubjson_prefix(j.front());
  11736. const bool same_prefix = std::all_of(j.begin() + 1, j.end(),
  11737. [this, first_prefix](const BasicJsonType & v)
  11738. {
  11739. return ubjson_prefix(v) == first_prefix;
  11740. });
  11741. if (same_prefix)
  11742. {
  11743. prefix_required = false;
  11744. oa->write_character(to_char_type('$'));
  11745. oa->write_character(first_prefix);
  11746. }
  11747. }
  11748. if (use_count)
  11749. {
  11750. oa->write_character(to_char_type('#'));
  11751. write_number_with_ubjson_prefix(j.m_value.array->size(), true);
  11752. }
  11753. for (const auto& el : *j.m_value.array)
  11754. {
  11755. write_ubjson(el, use_count, use_type, prefix_required);
  11756. }
  11757. if (!use_count)
  11758. {
  11759. oa->write_character(to_char_type(']'));
  11760. }
  11761. break;
  11762. }
  11763. case value_t::binary:
  11764. {
  11765. if (add_prefix)
  11766. {
  11767. oa->write_character(to_char_type('['));
  11768. }
  11769. if (use_type && !j.m_value.binary->empty())
  11770. {
  11771. JSON_ASSERT(use_count);
  11772. oa->write_character(to_char_type('$'));
  11773. oa->write_character('U');
  11774. }
  11775. if (use_count)
  11776. {
  11777. oa->write_character(to_char_type('#'));
  11778. write_number_with_ubjson_prefix(j.m_value.binary->size(), true);
  11779. }
  11780. if (use_type)
  11781. {
  11782. oa->write_characters(
  11783. reinterpret_cast<const CharType*>(j.m_value.binary->data()),
  11784. j.m_value.binary->size());
  11785. }
  11786. else
  11787. {
  11788. for (size_t i = 0; i < j.m_value.binary->size(); ++i)
  11789. {
  11790. oa->write_character(to_char_type('U'));
  11791. oa->write_character(j.m_value.binary->data()[i]);
  11792. }
  11793. }
  11794. if (!use_count)
  11795. {
  11796. oa->write_character(to_char_type(']'));
  11797. }
  11798. break;
  11799. }
  11800. case value_t::object:
  11801. {
  11802. if (add_prefix)
  11803. {
  11804. oa->write_character(to_char_type('{'));
  11805. }
  11806. bool prefix_required = true;
  11807. if (use_type && !j.m_value.object->empty())
  11808. {
  11809. JSON_ASSERT(use_count);
  11810. const CharType first_prefix = ubjson_prefix(j.front());
  11811. const bool same_prefix = std::all_of(j.begin(), j.end(),
  11812. [this, first_prefix](const BasicJsonType & v)
  11813. {
  11814. return ubjson_prefix(v) == first_prefix;
  11815. });
  11816. if (same_prefix)
  11817. {
  11818. prefix_required = false;
  11819. oa->write_character(to_char_type('$'));
  11820. oa->write_character(first_prefix);
  11821. }
  11822. }
  11823. if (use_count)
  11824. {
  11825. oa->write_character(to_char_type('#'));
  11826. write_number_with_ubjson_prefix(j.m_value.object->size(), true);
  11827. }
  11828. for (const auto& el : *j.m_value.object)
  11829. {
  11830. write_number_with_ubjson_prefix(el.first.size(), true);
  11831. oa->write_characters(
  11832. reinterpret_cast<const CharType*>(el.first.c_str()),
  11833. el.first.size());
  11834. write_ubjson(el.second, use_count, use_type, prefix_required);
  11835. }
  11836. if (!use_count)
  11837. {
  11838. oa->write_character(to_char_type('}'));
  11839. }
  11840. break;
  11841. }
  11842. default:
  11843. break;
  11844. }
  11845. }
  11846. private:
  11847. //////////
  11848. // BSON //
  11849. //////////
  11850. /*!
  11851. @return The size of a BSON document entry header, including the id marker
  11852. and the entry name size (and its null-terminator).
  11853. */
  11854. static std::size_t calc_bson_entry_header_size(const string_t& name)
  11855. {
  11856. const auto it = name.find(static_cast<typename string_t::value_type>(0));
  11857. if (JSON_HEDLEY_UNLIKELY(it != BasicJsonType::string_t::npos))
  11858. {
  11859. JSON_THROW(out_of_range::create(409,
  11860. "BSON key cannot contain code point U+0000 (at byte " + std::to_string(it) + ")"));
  11861. }
  11862. return /*id*/ 1ul + name.size() + /*zero-terminator*/1u;
  11863. }
  11864. /*!
  11865. @brief Writes the given @a element_type and @a name to the output adapter
  11866. */
  11867. void write_bson_entry_header(const string_t& name,
  11868. const std::uint8_t element_type)
  11869. {
  11870. oa->write_character(to_char_type(element_type)); // boolean
  11871. oa->write_characters(
  11872. reinterpret_cast<const CharType*>(name.c_str()),
  11873. name.size() + 1u);
  11874. }
  11875. /*!
  11876. @brief Writes a BSON element with key @a name and boolean value @a value
  11877. */
  11878. void write_bson_boolean(const string_t& name,
  11879. const bool value)
  11880. {
  11881. write_bson_entry_header(name, 0x08);
  11882. oa->write_character(value ? to_char_type(0x01) : to_char_type(0x00));
  11883. }
  11884. /*!
  11885. @brief Writes a BSON element with key @a name and double value @a value
  11886. */
  11887. void write_bson_double(const string_t& name,
  11888. const double value)
  11889. {
  11890. write_bson_entry_header(name, 0x01);
  11891. write_number<double, true>(value);
  11892. }
  11893. /*!
  11894. @return The size of the BSON-encoded string in @a value
  11895. */
  11896. static std::size_t calc_bson_string_size(const string_t& value)
  11897. {
  11898. return sizeof(std::int32_t) + value.size() + 1ul;
  11899. }
  11900. /*!
  11901. @brief Writes a BSON element with key @a name and string value @a value
  11902. */
  11903. void write_bson_string(const string_t& name,
  11904. const string_t& value)
  11905. {
  11906. write_bson_entry_header(name, 0x02);
  11907. write_number<std::int32_t, true>(static_cast<std::int32_t>(value.size() + 1ul));
  11908. oa->write_characters(
  11909. reinterpret_cast<const CharType*>(value.c_str()),
  11910. value.size() + 1);
  11911. }
  11912. /*!
  11913. @brief Writes a BSON element with key @a name and null value
  11914. */
  11915. void write_bson_null(const string_t& name)
  11916. {
  11917. write_bson_entry_header(name, 0x0A);
  11918. }
  11919. /*!
  11920. @return The size of the BSON-encoded integer @a value
  11921. */
  11922. static std::size_t calc_bson_integer_size(const std::int64_t value)
  11923. {
  11924. return (std::numeric_limits<std::int32_t>::min)() <= value && value <= (std::numeric_limits<std::int32_t>::max)()
  11925. ? sizeof(std::int32_t)
  11926. : sizeof(std::int64_t);
  11927. }
  11928. /*!
  11929. @brief Writes a BSON element with key @a name and integer @a value
  11930. */
  11931. void write_bson_integer(const string_t& name,
  11932. const std::int64_t value)
  11933. {
  11934. if ((std::numeric_limits<std::int32_t>::min)() <= value && value <= (std::numeric_limits<std::int32_t>::max)())
  11935. {
  11936. write_bson_entry_header(name, 0x10); // int32
  11937. write_number<std::int32_t, true>(static_cast<std::int32_t>(value));
  11938. }
  11939. else
  11940. {
  11941. write_bson_entry_header(name, 0x12); // int64
  11942. write_number<std::int64_t, true>(static_cast<std::int64_t>(value));
  11943. }
  11944. }
  11945. /*!
  11946. @return The size of the BSON-encoded unsigned integer in @a j
  11947. */
  11948. static constexpr std::size_t calc_bson_unsigned_size(const std::uint64_t value) noexcept
  11949. {
  11950. return (value <= static_cast<std::uint64_t>((std::numeric_limits<std::int32_t>::max)()))
  11951. ? sizeof(std::int32_t)
  11952. : sizeof(std::int64_t);
  11953. }
  11954. /*!
  11955. @brief Writes a BSON element with key @a name and unsigned @a value
  11956. */
  11957. void write_bson_unsigned(const string_t& name,
  11958. const std::uint64_t value)
  11959. {
  11960. if (value <= static_cast<std::uint64_t>((std::numeric_limits<std::int32_t>::max)()))
  11961. {
  11962. write_bson_entry_header(name, 0x10 /* int32 */);
  11963. write_number<std::int32_t, true>(static_cast<std::int32_t>(value));
  11964. }
  11965. else if (value <= static_cast<std::uint64_t>((std::numeric_limits<std::int64_t>::max)()))
  11966. {
  11967. write_bson_entry_header(name, 0x12 /* int64 */);
  11968. write_number<std::int64_t, true>(static_cast<std::int64_t>(value));
  11969. }
  11970. else
  11971. {
  11972. JSON_THROW(out_of_range::create(407, "integer number " + std::to_string(value) + " cannot be represented by BSON as it does not fit int64"));
  11973. }
  11974. }
  11975. /*!
  11976. @brief Writes a BSON element with key @a name and object @a value
  11977. */
  11978. void write_bson_object_entry(const string_t& name,
  11979. const typename BasicJsonType::object_t& value)
  11980. {
  11981. write_bson_entry_header(name, 0x03); // object
  11982. write_bson_object(value);
  11983. }
  11984. /*!
  11985. @return The size of the BSON-encoded array @a value
  11986. */
  11987. static std::size_t calc_bson_array_size(const typename BasicJsonType::array_t& value)
  11988. {
  11989. std::size_t array_index = 0ul;
  11990. 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)
  11991. {
  11992. return result + calc_bson_element_size(std::to_string(array_index++), el);
  11993. });
  11994. return sizeof(std::int32_t) + embedded_document_size + 1ul;
  11995. }
  11996. /*!
  11997. @return The size of the BSON-encoded binary array @a value
  11998. */
  11999. static std::size_t calc_bson_binary_size(const typename BasicJsonType::binary_t& value)
  12000. {
  12001. return sizeof(std::int32_t) + value.size() + 1ul;
  12002. }
  12003. /*!
  12004. @brief Writes a BSON element with key @a name and array @a value
  12005. */
  12006. void write_bson_array(const string_t& name,
  12007. const typename BasicJsonType::array_t& value)
  12008. {
  12009. write_bson_entry_header(name, 0x04); // array
  12010. write_number<std::int32_t, true>(static_cast<std::int32_t>(calc_bson_array_size(value)));
  12011. std::size_t array_index = 0ul;
  12012. for (const auto& el : value)
  12013. {
  12014. write_bson_element(std::to_string(array_index++), el);
  12015. }
  12016. oa->write_character(to_char_type(0x00));
  12017. }
  12018. /*!
  12019. @brief Writes a BSON element with key @a name and binary value @a value
  12020. */
  12021. void write_bson_binary(const string_t& name,
  12022. const binary_t& value)
  12023. {
  12024. write_bson_entry_header(name, 0x05);
  12025. write_number<std::int32_t, true>(static_cast<std::int32_t>(value.size()));
  12026. write_number(value.has_subtype() ? value.subtype() : std::uint8_t(0x00));
  12027. oa->write_characters(reinterpret_cast<const CharType*>(value.data()), value.size());
  12028. }
  12029. /*!
  12030. @brief Calculates the size necessary to serialize the JSON value @a j with its @a name
  12031. @return The calculated size for the BSON document entry for @a j with the given @a name.
  12032. */
  12033. static std::size_t calc_bson_element_size(const string_t& name,
  12034. const BasicJsonType& j)
  12035. {
  12036. const auto header_size = calc_bson_entry_header_size(name);
  12037. switch (j.type())
  12038. {
  12039. case value_t::object:
  12040. return header_size + calc_bson_object_size(*j.m_value.object);
  12041. case value_t::array:
  12042. return header_size + calc_bson_array_size(*j.m_value.array);
  12043. case value_t::binary:
  12044. return header_size + calc_bson_binary_size(*j.m_value.binary);
  12045. case value_t::boolean:
  12046. return header_size + 1ul;
  12047. case value_t::number_float:
  12048. return header_size + 8ul;
  12049. case value_t::number_integer:
  12050. return header_size + calc_bson_integer_size(j.m_value.number_integer);
  12051. case value_t::number_unsigned:
  12052. return header_size + calc_bson_unsigned_size(j.m_value.number_unsigned);
  12053. case value_t::string:
  12054. return header_size + calc_bson_string_size(*j.m_value.string);
  12055. case value_t::null:
  12056. return header_size + 0ul;
  12057. // LCOV_EXCL_START
  12058. default:
  12059. JSON_ASSERT(false);
  12060. return 0ul;
  12061. // LCOV_EXCL_STOP
  12062. }
  12063. }
  12064. /*!
  12065. @brief Serializes the JSON value @a j to BSON and associates it with the
  12066. key @a name.
  12067. @param name The name to associate with the JSON entity @a j within the
  12068. current BSON document
  12069. @return The size of the BSON entry
  12070. */
  12071. void write_bson_element(const string_t& name,
  12072. const BasicJsonType& j)
  12073. {
  12074. switch (j.type())
  12075. {
  12076. case value_t::object:
  12077. return write_bson_object_entry(name, *j.m_value.object);
  12078. case value_t::array:
  12079. return write_bson_array(name, *j.m_value.array);
  12080. case value_t::binary:
  12081. return write_bson_binary(name, *j.m_value.binary);
  12082. case value_t::boolean:
  12083. return write_bson_boolean(name, j.m_value.boolean);
  12084. case value_t::number_float:
  12085. return write_bson_double(name, j.m_value.number_float);
  12086. case value_t::number_integer:
  12087. return write_bson_integer(name, j.m_value.number_integer);
  12088. case value_t::number_unsigned:
  12089. return write_bson_unsigned(name, j.m_value.number_unsigned);
  12090. case value_t::string:
  12091. return write_bson_string(name, *j.m_value.string);
  12092. case value_t::null:
  12093. return write_bson_null(name);
  12094. // LCOV_EXCL_START
  12095. default:
  12096. JSON_ASSERT(false);
  12097. return;
  12098. // LCOV_EXCL_STOP
  12099. }
  12100. }
  12101. /*!
  12102. @brief Calculates the size of the BSON serialization of the given
  12103. JSON-object @a j.
  12104. @param[in] j JSON value to serialize
  12105. @pre j.type() == value_t::object
  12106. */
  12107. static std::size_t calc_bson_object_size(const typename BasicJsonType::object_t& value)
  12108. {
  12109. std::size_t document_size = std::accumulate(value.begin(), value.end(), std::size_t(0),
  12110. [](size_t result, const typename BasicJsonType::object_t::value_type & el)
  12111. {
  12112. return result += calc_bson_element_size(el.first, el.second);
  12113. });
  12114. return sizeof(std::int32_t) + document_size + 1ul;
  12115. }
  12116. /*!
  12117. @param[in] j JSON value to serialize
  12118. @pre j.type() == value_t::object
  12119. */
  12120. void write_bson_object(const typename BasicJsonType::object_t& value)
  12121. {
  12122. write_number<std::int32_t, true>(static_cast<std::int32_t>(calc_bson_object_size(value)));
  12123. for (const auto& el : value)
  12124. {
  12125. write_bson_element(el.first, el.second);
  12126. }
  12127. oa->write_character(to_char_type(0x00));
  12128. }
  12129. //////////
  12130. // CBOR //
  12131. //////////
  12132. static constexpr CharType get_cbor_float_prefix(float /*unused*/)
  12133. {
  12134. return to_char_type(0xFA); // Single-Precision Float
  12135. }
  12136. static constexpr CharType get_cbor_float_prefix(double /*unused*/)
  12137. {
  12138. return to_char_type(0xFB); // Double-Precision Float
  12139. }
  12140. /////////////
  12141. // MsgPack //
  12142. /////////////
  12143. static constexpr CharType get_msgpack_float_prefix(float /*unused*/)
  12144. {
  12145. return to_char_type(0xCA); // float 32
  12146. }
  12147. static constexpr CharType get_msgpack_float_prefix(double /*unused*/)
  12148. {
  12149. return to_char_type(0xCB); // float 64
  12150. }
  12151. ////////////
  12152. // UBJSON //
  12153. ////////////
  12154. // UBJSON: write number (floating point)
  12155. template<typename NumberType, typename std::enable_if<
  12156. std::is_floating_point<NumberType>::value, int>::type = 0>
  12157. void write_number_with_ubjson_prefix(const NumberType n,
  12158. const bool add_prefix)
  12159. {
  12160. if (add_prefix)
  12161. {
  12162. oa->write_character(get_ubjson_float_prefix(n));
  12163. }
  12164. write_number(n);
  12165. }
  12166. // UBJSON: write number (unsigned integer)
  12167. template<typename NumberType, typename std::enable_if<
  12168. std::is_unsigned<NumberType>::value, int>::type = 0>
  12169. void write_number_with_ubjson_prefix(const NumberType n,
  12170. const bool add_prefix)
  12171. {
  12172. if (n <= static_cast<std::uint64_t>((std::numeric_limits<std::int8_t>::max)()))
  12173. {
  12174. if (add_prefix)
  12175. {
  12176. oa->write_character(to_char_type('i')); // int8
  12177. }
  12178. write_number(static_cast<std::uint8_t>(n));
  12179. }
  12180. else if (n <= (std::numeric_limits<std::uint8_t>::max)())
  12181. {
  12182. if (add_prefix)
  12183. {
  12184. oa->write_character(to_char_type('U')); // uint8
  12185. }
  12186. write_number(static_cast<std::uint8_t>(n));
  12187. }
  12188. else if (n <= static_cast<std::uint64_t>((std::numeric_limits<std::int16_t>::max)()))
  12189. {
  12190. if (add_prefix)
  12191. {
  12192. oa->write_character(to_char_type('I')); // int16
  12193. }
  12194. write_number(static_cast<std::int16_t>(n));
  12195. }
  12196. else if (n <= static_cast<std::uint64_t>((std::numeric_limits<std::int32_t>::max)()))
  12197. {
  12198. if (add_prefix)
  12199. {
  12200. oa->write_character(to_char_type('l')); // int32
  12201. }
  12202. write_number(static_cast<std::int32_t>(n));
  12203. }
  12204. else if (n <= static_cast<std::uint64_t>((std::numeric_limits<std::int64_t>::max)()))
  12205. {
  12206. if (add_prefix)
  12207. {
  12208. oa->write_character(to_char_type('L')); // int64
  12209. }
  12210. write_number(static_cast<std::int64_t>(n));
  12211. }
  12212. else
  12213. {
  12214. if (add_prefix)
  12215. {
  12216. oa->write_character(to_char_type('H')); // high-precision number
  12217. }
  12218. const auto number = BasicJsonType(n).dump();
  12219. write_number_with_ubjson_prefix(number.size(), true);
  12220. for (std::size_t i = 0; i < number.size(); ++i)
  12221. {
  12222. oa->write_character(to_char_type(static_cast<std::uint8_t>(number[i])));
  12223. }
  12224. }
  12225. }
  12226. // UBJSON: write number (signed integer)
  12227. template < typename NumberType, typename std::enable_if <
  12228. std::is_signed<NumberType>::value&&
  12229. !std::is_floating_point<NumberType>::value, int >::type = 0 >
  12230. void write_number_with_ubjson_prefix(const NumberType n,
  12231. const bool add_prefix)
  12232. {
  12233. if ((std::numeric_limits<std::int8_t>::min)() <= n && n <= (std::numeric_limits<std::int8_t>::max)())
  12234. {
  12235. if (add_prefix)
  12236. {
  12237. oa->write_character(to_char_type('i')); // int8
  12238. }
  12239. write_number(static_cast<std::int8_t>(n));
  12240. }
  12241. 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)()))
  12242. {
  12243. if (add_prefix)
  12244. {
  12245. oa->write_character(to_char_type('U')); // uint8
  12246. }
  12247. write_number(static_cast<std::uint8_t>(n));
  12248. }
  12249. else if ((std::numeric_limits<std::int16_t>::min)() <= n && n <= (std::numeric_limits<std::int16_t>::max)())
  12250. {
  12251. if (add_prefix)
  12252. {
  12253. oa->write_character(to_char_type('I')); // int16
  12254. }
  12255. write_number(static_cast<std::int16_t>(n));
  12256. }
  12257. else if ((std::numeric_limits<std::int32_t>::min)() <= n && n <= (std::numeric_limits<std::int32_t>::max)())
  12258. {
  12259. if (add_prefix)
  12260. {
  12261. oa->write_character(to_char_type('l')); // int32
  12262. }
  12263. write_number(static_cast<std::int32_t>(n));
  12264. }
  12265. else if ((std::numeric_limits<std::int64_t>::min)() <= n && n <= (std::numeric_limits<std::int64_t>::max)())
  12266. {
  12267. if (add_prefix)
  12268. {
  12269. oa->write_character(to_char_type('L')); // int64
  12270. }
  12271. write_number(static_cast<std::int64_t>(n));
  12272. }
  12273. // LCOV_EXCL_START
  12274. else
  12275. {
  12276. if (add_prefix)
  12277. {
  12278. oa->write_character(to_char_type('H')); // high-precision number
  12279. }
  12280. const auto number = BasicJsonType(n).dump();
  12281. write_number_with_ubjson_prefix(number.size(), true);
  12282. for (std::size_t i = 0; i < number.size(); ++i)
  12283. {
  12284. oa->write_character(to_char_type(static_cast<std::uint8_t>(number[i])));
  12285. }
  12286. }
  12287. // LCOV_EXCL_STOP
  12288. }
  12289. /*!
  12290. @brief determine the type prefix of container values
  12291. */
  12292. CharType ubjson_prefix(const BasicJsonType& j) const noexcept
  12293. {
  12294. switch (j.type())
  12295. {
  12296. case value_t::null:
  12297. return 'Z';
  12298. case value_t::boolean:
  12299. return j.m_value.boolean ? 'T' : 'F';
  12300. case value_t::number_integer:
  12301. {
  12302. 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)())
  12303. {
  12304. return 'i';
  12305. }
  12306. 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)())
  12307. {
  12308. return 'U';
  12309. }
  12310. 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)())
  12311. {
  12312. return 'I';
  12313. }
  12314. 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)())
  12315. {
  12316. return 'l';
  12317. }
  12318. 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)())
  12319. {
  12320. return 'L';
  12321. }
  12322. // anything else is treated as high-precision number
  12323. return 'H'; // LCOV_EXCL_LINE
  12324. }
  12325. case value_t::number_unsigned:
  12326. {
  12327. if (j.m_value.number_unsigned <= static_cast<std::uint64_t>((std::numeric_limits<std::int8_t>::max)()))
  12328. {
  12329. return 'i';
  12330. }
  12331. if (j.m_value.number_unsigned <= static_cast<std::uint64_t>((std::numeric_limits<std::uint8_t>::max)()))
  12332. {
  12333. return 'U';
  12334. }
  12335. if (j.m_value.number_unsigned <= static_cast<std::uint64_t>((std::numeric_limits<std::int16_t>::max)()))
  12336. {
  12337. return 'I';
  12338. }
  12339. if (j.m_value.number_unsigned <= static_cast<std::uint64_t>((std::numeric_limits<std::int32_t>::max)()))
  12340. {
  12341. return 'l';
  12342. }
  12343. if (j.m_value.number_unsigned <= static_cast<std::uint64_t>((std::numeric_limits<std::int64_t>::max)()))
  12344. {
  12345. return 'L';
  12346. }
  12347. // anything else is treated as high-precision number
  12348. return 'H'; // LCOV_EXCL_LINE
  12349. }
  12350. case value_t::number_float:
  12351. return get_ubjson_float_prefix(j.m_value.number_float);
  12352. case value_t::string:
  12353. return 'S';
  12354. case value_t::array: // fallthrough
  12355. case value_t::binary:
  12356. return '[';
  12357. case value_t::object:
  12358. return '{';
  12359. default: // discarded values
  12360. return 'N';
  12361. }
  12362. }
  12363. static constexpr CharType get_ubjson_float_prefix(float /*unused*/)
  12364. {
  12365. return 'd'; // float 32
  12366. }
  12367. static constexpr CharType get_ubjson_float_prefix(double /*unused*/)
  12368. {
  12369. return 'D'; // float 64
  12370. }
  12371. ///////////////////////
  12372. // Utility functions //
  12373. ///////////////////////
  12374. /*
  12375. @brief write a number to output input
  12376. @param[in] n number of type @a NumberType
  12377. @tparam NumberType the type of the number
  12378. @tparam OutputIsLittleEndian Set to true if output data is
  12379. required to be little endian
  12380. @note This function needs to respect the system's endianess, because bytes
  12381. in CBOR, MessagePack, and UBJSON are stored in network order (big
  12382. endian) and therefore need reordering on little endian systems.
  12383. */
  12384. template<typename NumberType, bool OutputIsLittleEndian = false>
  12385. void write_number(const NumberType n)
  12386. {
  12387. // step 1: write number to array of length NumberType
  12388. std::array<CharType, sizeof(NumberType)> vec;
  12389. std::memcpy(vec.data(), &n, sizeof(NumberType));
  12390. // step 2: write array to output (with possible reordering)
  12391. if (is_little_endian != OutputIsLittleEndian)
  12392. {
  12393. // reverse byte order prior to conversion if necessary
  12394. std::reverse(vec.begin(), vec.end());
  12395. }
  12396. oa->write_characters(vec.data(), sizeof(NumberType));
  12397. }
  12398. void write_compact_float(const number_float_t n, detail::input_format_t format)
  12399. {
  12400. if (static_cast<double>(n) >= static_cast<double>(std::numeric_limits<float>::lowest()) &&
  12401. static_cast<double>(n) <= static_cast<double>((std::numeric_limits<float>::max)()) &&
  12402. static_cast<double>(static_cast<float>(n)) == static_cast<double>(n))
  12403. {
  12404. oa->write_character(format == detail::input_format_t::cbor
  12405. ? get_cbor_float_prefix(static_cast<float>(n))
  12406. : get_msgpack_float_prefix(static_cast<float>(n)));
  12407. write_number(static_cast<float>(n));
  12408. }
  12409. else
  12410. {
  12411. oa->write_character(format == detail::input_format_t::cbor
  12412. ? get_cbor_float_prefix(n)
  12413. : get_msgpack_float_prefix(n));
  12414. write_number(n);
  12415. }
  12416. }
  12417. public:
  12418. // The following to_char_type functions are implement the conversion
  12419. // between uint8_t and CharType. In case CharType is not unsigned,
  12420. // such a conversion is required to allow values greater than 128.
  12421. // See <https://github.com/nlohmann/json/issues/1286> for a discussion.
  12422. template < typename C = CharType,
  12423. enable_if_t < std::is_signed<C>::value && std::is_signed<char>::value > * = nullptr >
  12424. static constexpr CharType to_char_type(std::uint8_t x) noexcept
  12425. {
  12426. return *reinterpret_cast<char*>(&x);
  12427. }
  12428. template < typename C = CharType,
  12429. enable_if_t < std::is_signed<C>::value && std::is_unsigned<char>::value > * = nullptr >
  12430. static CharType to_char_type(std::uint8_t x) noexcept
  12431. {
  12432. static_assert(sizeof(std::uint8_t) == sizeof(CharType), "size of CharType must be equal to std::uint8_t");
  12433. static_assert(std::is_trivial<CharType>::value, "CharType must be trivial");
  12434. CharType result;
  12435. std::memcpy(&result, &x, sizeof(x));
  12436. return result;
  12437. }
  12438. template<typename C = CharType,
  12439. enable_if_t<std::is_unsigned<C>::value>* = nullptr>
  12440. static constexpr CharType to_char_type(std::uint8_t x) noexcept
  12441. {
  12442. return x;
  12443. }
  12444. template < typename InputCharType, typename C = CharType,
  12445. enable_if_t <
  12446. std::is_signed<C>::value &&
  12447. std::is_signed<char>::value &&
  12448. std::is_same<char, typename std::remove_cv<InputCharType>::type>::value
  12449. > * = nullptr >
  12450. static constexpr CharType to_char_type(InputCharType x) noexcept
  12451. {
  12452. return x;
  12453. }
  12454. private:
  12455. /// whether we can assume little endianess
  12456. const bool is_little_endian = little_endianess();
  12457. /// the output
  12458. output_adapter_t<CharType> oa = nullptr;
  12459. };
  12460. } // namespace detail
  12461. } // namespace nlohmann
  12462. // #include <nlohmann/detail/output/output_adapters.hpp>
  12463. // #include <nlohmann/detail/output/serializer.hpp>
  12464. #include <algorithm> // reverse, remove, fill, find, none_of
  12465. #include <array> // array
  12466. #include <clocale> // localeconv, lconv
  12467. #include <cmath> // labs, isfinite, isnan, signbit
  12468. #include <cstddef> // size_t, ptrdiff_t
  12469. #include <cstdint> // uint8_t
  12470. #include <cstdio> // snprintf
  12471. #include <limits> // numeric_limits
  12472. #include <string> // string, char_traits
  12473. #include <type_traits> // is_same
  12474. #include <utility> // move
  12475. // #include <nlohmann/detail/conversions/to_chars.hpp>
  12476. #include <array> // array
  12477. #include <cmath> // signbit, isfinite
  12478. #include <cstdint> // intN_t, uintN_t
  12479. #include <cstring> // memcpy, memmove
  12480. #include <limits> // numeric_limits
  12481. #include <type_traits> // conditional
  12482. // #include <nlohmann/detail/macro_scope.hpp>
  12483. namespace nlohmann
  12484. {
  12485. namespace detail
  12486. {
  12487. /*!
  12488. @brief implements the Grisu2 algorithm for binary to decimal floating-point
  12489. conversion.
  12490. This implementation is a slightly modified version of the reference
  12491. implementation which may be obtained from
  12492. http://florian.loitsch.com/publications (bench.tar.gz).
  12493. The code is distributed under the MIT license, Copyright (c) 2009 Florian Loitsch.
  12494. For a detailed description of the algorithm see:
  12495. [1] Loitsch, "Printing Floating-Point Numbers Quickly and Accurately with
  12496. Integers", Proceedings of the ACM SIGPLAN 2010 Conference on Programming
  12497. Language Design and Implementation, PLDI 2010
  12498. [2] Burger, Dybvig, "Printing Floating-Point Numbers Quickly and Accurately",
  12499. Proceedings of the ACM SIGPLAN 1996 Conference on Programming Language
  12500. Design and Implementation, PLDI 1996
  12501. */
  12502. namespace dtoa_impl
  12503. {
  12504. template<typename Target, typename Source>
  12505. Target reinterpret_bits(const Source source)
  12506. {
  12507. static_assert(sizeof(Target) == sizeof(Source), "size mismatch");
  12508. Target target;
  12509. std::memcpy(&target, &source, sizeof(Source));
  12510. return target;
  12511. }
  12512. struct diyfp // f * 2^e
  12513. {
  12514. static constexpr int kPrecision = 64; // = q
  12515. std::uint64_t f = 0;
  12516. int e = 0;
  12517. constexpr diyfp(std::uint64_t f_, int e_) noexcept : f(f_), e(e_) {}
  12518. /*!
  12519. @brief returns x - y
  12520. @pre x.e == y.e and x.f >= y.f
  12521. */
  12522. static diyfp sub(const diyfp& x, const diyfp& y) noexcept
  12523. {
  12524. JSON_ASSERT(x.e == y.e);
  12525. JSON_ASSERT(x.f >= y.f);
  12526. return {x.f - y.f, x.e};
  12527. }
  12528. /*!
  12529. @brief returns x * y
  12530. @note The result is rounded. (Only the upper q bits are returned.)
  12531. */
  12532. static diyfp mul(const diyfp& x, const diyfp& y) noexcept
  12533. {
  12534. static_assert(kPrecision == 64, "internal error");
  12535. // Computes:
  12536. // f = round((x.f * y.f) / 2^q)
  12537. // e = x.e + y.e + q
  12538. // Emulate the 64-bit * 64-bit multiplication:
  12539. //
  12540. // p = u * v
  12541. // = (u_lo + 2^32 u_hi) (v_lo + 2^32 v_hi)
  12542. // = (u_lo v_lo ) + 2^32 ((u_lo v_hi ) + (u_hi v_lo )) + 2^64 (u_hi v_hi )
  12543. // = (p0 ) + 2^32 ((p1 ) + (p2 )) + 2^64 (p3 )
  12544. // = (p0_lo + 2^32 p0_hi) + 2^32 ((p1_lo + 2^32 p1_hi) + (p2_lo + 2^32 p2_hi)) + 2^64 (p3 )
  12545. // = (p0_lo ) + 2^32 (p0_hi + p1_lo + p2_lo ) + 2^64 (p1_hi + p2_hi + p3)
  12546. // = (p0_lo ) + 2^32 (Q ) + 2^64 (H )
  12547. // = (p0_lo ) + 2^32 (Q_lo + 2^32 Q_hi ) + 2^64 (H )
  12548. //
  12549. // (Since Q might be larger than 2^32 - 1)
  12550. //
  12551. // = (p0_lo + 2^32 Q_lo) + 2^64 (Q_hi + H)
  12552. //
  12553. // (Q_hi + H does not overflow a 64-bit int)
  12554. //
  12555. // = p_lo + 2^64 p_hi
  12556. const std::uint64_t u_lo = x.f & 0xFFFFFFFFu;
  12557. const std::uint64_t u_hi = x.f >> 32u;
  12558. const std::uint64_t v_lo = y.f & 0xFFFFFFFFu;
  12559. const std::uint64_t v_hi = y.f >> 32u;
  12560. const std::uint64_t p0 = u_lo * v_lo;
  12561. const std::uint64_t p1 = u_lo * v_hi;
  12562. const std::uint64_t p2 = u_hi * v_lo;
  12563. const std::uint64_t p3 = u_hi * v_hi;
  12564. const std::uint64_t p0_hi = p0 >> 32u;
  12565. const std::uint64_t p1_lo = p1 & 0xFFFFFFFFu;
  12566. const std::uint64_t p1_hi = p1 >> 32u;
  12567. const std::uint64_t p2_lo = p2 & 0xFFFFFFFFu;
  12568. const std::uint64_t p2_hi = p2 >> 32u;
  12569. std::uint64_t Q = p0_hi + p1_lo + p2_lo;
  12570. // The full product might now be computed as
  12571. //
  12572. // p_hi = p3 + p2_hi + p1_hi + (Q >> 32)
  12573. // p_lo = p0_lo + (Q << 32)
  12574. //
  12575. // But in this particular case here, the full p_lo is not required.
  12576. // Effectively we only need to add the highest bit in p_lo to p_hi (and
  12577. // Q_hi + 1 does not overflow).
  12578. Q += std::uint64_t{1} << (64u - 32u - 1u); // round, ties up
  12579. const std::uint64_t h = p3 + p2_hi + p1_hi + (Q >> 32u);
  12580. return {h, x.e + y.e + 64};
  12581. }
  12582. /*!
  12583. @brief normalize x such that the significand is >= 2^(q-1)
  12584. @pre x.f != 0
  12585. */
  12586. static diyfp normalize(diyfp x) noexcept
  12587. {
  12588. JSON_ASSERT(x.f != 0);
  12589. while ((x.f >> 63u) == 0)
  12590. {
  12591. x.f <<= 1u;
  12592. x.e--;
  12593. }
  12594. return x;
  12595. }
  12596. /*!
  12597. @brief normalize x such that the result has the exponent E
  12598. @pre e >= x.e and the upper e - x.e bits of x.f must be zero.
  12599. */
  12600. static diyfp normalize_to(const diyfp& x, const int target_exponent) noexcept
  12601. {
  12602. const int delta = x.e - target_exponent;
  12603. JSON_ASSERT(delta >= 0);
  12604. JSON_ASSERT(((x.f << delta) >> delta) == x.f);
  12605. return {x.f << delta, target_exponent};
  12606. }
  12607. };
  12608. struct boundaries
  12609. {
  12610. diyfp w;
  12611. diyfp minus;
  12612. diyfp plus;
  12613. };
  12614. /*!
  12615. Compute the (normalized) diyfp representing the input number 'value' and its
  12616. boundaries.
  12617. @pre value must be finite and positive
  12618. */
  12619. template<typename FloatType>
  12620. boundaries compute_boundaries(FloatType value)
  12621. {
  12622. JSON_ASSERT(std::isfinite(value));
  12623. JSON_ASSERT(value > 0);
  12624. // Convert the IEEE representation into a diyfp.
  12625. //
  12626. // If v is denormal:
  12627. // value = 0.F * 2^(1 - bias) = ( F) * 2^(1 - bias - (p-1))
  12628. // If v is normalized:
  12629. // value = 1.F * 2^(E - bias) = (2^(p-1) + F) * 2^(E - bias - (p-1))
  12630. static_assert(std::numeric_limits<FloatType>::is_iec559,
  12631. "internal error: dtoa_short requires an IEEE-754 floating-point implementation");
  12632. constexpr int kPrecision = std::numeric_limits<FloatType>::digits; // = p (includes the hidden bit)
  12633. constexpr int kBias = std::numeric_limits<FloatType>::max_exponent - 1 + (kPrecision - 1);
  12634. constexpr int kMinExp = 1 - kBias;
  12635. constexpr std::uint64_t kHiddenBit = std::uint64_t{1} << (kPrecision - 1); // = 2^(p-1)
  12636. using bits_type = typename std::conditional<kPrecision == 24, std::uint32_t, std::uint64_t >::type;
  12637. const std::uint64_t bits = reinterpret_bits<bits_type>(value);
  12638. const std::uint64_t E = bits >> (kPrecision - 1);
  12639. const std::uint64_t F = bits & (kHiddenBit - 1);
  12640. const bool is_denormal = E == 0;
  12641. const diyfp v = is_denormal
  12642. ? diyfp(F, kMinExp)
  12643. : diyfp(F + kHiddenBit, static_cast<int>(E) - kBias);
  12644. // Compute the boundaries m- and m+ of the floating-point value
  12645. // v = f * 2^e.
  12646. //
  12647. // Determine v- and v+, the floating-point predecessor and successor if v,
  12648. // respectively.
  12649. //
  12650. // v- = v - 2^e if f != 2^(p-1) or e == e_min (A)
  12651. // = v - 2^(e-1) if f == 2^(p-1) and e > e_min (B)
  12652. //
  12653. // v+ = v + 2^e
  12654. //
  12655. // Let m- = (v- + v) / 2 and m+ = (v + v+) / 2. All real numbers _strictly_
  12656. // between m- and m+ round to v, regardless of how the input rounding
  12657. // algorithm breaks ties.
  12658. //
  12659. // ---+-------------+-------------+-------------+-------------+--- (A)
  12660. // v- m- v m+ v+
  12661. //
  12662. // -----------------+------+------+-------------+-------------+--- (B)
  12663. // v- m- v m+ v+
  12664. const bool lower_boundary_is_closer = F == 0 && E > 1;
  12665. const diyfp m_plus = diyfp(2 * v.f + 1, v.e - 1);
  12666. const diyfp m_minus = lower_boundary_is_closer
  12667. ? diyfp(4 * v.f - 1, v.e - 2) // (B)
  12668. : diyfp(2 * v.f - 1, v.e - 1); // (A)
  12669. // Determine the normalized w+ = m+.
  12670. const diyfp w_plus = diyfp::normalize(m_plus);
  12671. // Determine w- = m- such that e_(w-) = e_(w+).
  12672. const diyfp w_minus = diyfp::normalize_to(m_minus, w_plus.e);
  12673. return {diyfp::normalize(v), w_minus, w_plus};
  12674. }
  12675. // Given normalized diyfp w, Grisu needs to find a (normalized) cached
  12676. // power-of-ten c, such that the exponent of the product c * w = f * 2^e lies
  12677. // within a certain range [alpha, gamma] (Definition 3.2 from [1])
  12678. //
  12679. // alpha <= e = e_c + e_w + q <= gamma
  12680. //
  12681. // or
  12682. //
  12683. // f_c * f_w * 2^alpha <= f_c 2^(e_c) * f_w 2^(e_w) * 2^q
  12684. // <= f_c * f_w * 2^gamma
  12685. //
  12686. // Since c and w are normalized, i.e. 2^(q-1) <= f < 2^q, this implies
  12687. //
  12688. // 2^(q-1) * 2^(q-1) * 2^alpha <= c * w * 2^q < 2^q * 2^q * 2^gamma
  12689. //
  12690. // or
  12691. //
  12692. // 2^(q - 2 + alpha) <= c * w < 2^(q + gamma)
  12693. //
  12694. // The choice of (alpha,gamma) determines the size of the table and the form of
  12695. // the digit generation procedure. Using (alpha,gamma)=(-60,-32) works out well
  12696. // in practice:
  12697. //
  12698. // The idea is to cut the number c * w = f * 2^e into two parts, which can be
  12699. // processed independently: An integral part p1, and a fractional part p2:
  12700. //
  12701. // f * 2^e = ( (f div 2^-e) * 2^-e + (f mod 2^-e) ) * 2^e
  12702. // = (f div 2^-e) + (f mod 2^-e) * 2^e
  12703. // = p1 + p2 * 2^e
  12704. //
  12705. // The conversion of p1 into decimal form requires a series of divisions and
  12706. // modulos by (a power of) 10. These operations are faster for 32-bit than for
  12707. // 64-bit integers, so p1 should ideally fit into a 32-bit integer. This can be
  12708. // achieved by choosing
  12709. //
  12710. // -e >= 32 or e <= -32 := gamma
  12711. //
  12712. // In order to convert the fractional part
  12713. //
  12714. // p2 * 2^e = p2 / 2^-e = d[-1] / 10^1 + d[-2] / 10^2 + ...
  12715. //
  12716. // into decimal form, the fraction is repeatedly multiplied by 10 and the digits
  12717. // d[-i] are extracted in order:
  12718. //
  12719. // (10 * p2) div 2^-e = d[-1]
  12720. // (10 * p2) mod 2^-e = d[-2] / 10^1 + ...
  12721. //
  12722. // The multiplication by 10 must not overflow. It is sufficient to choose
  12723. //
  12724. // 10 * p2 < 16 * p2 = 2^4 * p2 <= 2^64.
  12725. //
  12726. // Since p2 = f mod 2^-e < 2^-e,
  12727. //
  12728. // -e <= 60 or e >= -60 := alpha
  12729. constexpr int kAlpha = -60;
  12730. constexpr int kGamma = -32;
  12731. struct cached_power // c = f * 2^e ~= 10^k
  12732. {
  12733. std::uint64_t f;
  12734. int e;
  12735. int k;
  12736. };
  12737. /*!
  12738. For a normalized diyfp w = f * 2^e, this function returns a (normalized) cached
  12739. power-of-ten c = f_c * 2^e_c, such that the exponent of the product w * c
  12740. satisfies (Definition 3.2 from [1])
  12741. alpha <= e_c + e + q <= gamma.
  12742. */
  12743. inline cached_power get_cached_power_for_binary_exponent(int e)
  12744. {
  12745. // Now
  12746. //
  12747. // alpha <= e_c + e + q <= gamma (1)
  12748. // ==> f_c * 2^alpha <= c * 2^e * 2^q
  12749. //
  12750. // and since the c's are normalized, 2^(q-1) <= f_c,
  12751. //
  12752. // ==> 2^(q - 1 + alpha) <= c * 2^(e + q)
  12753. // ==> 2^(alpha - e - 1) <= c
  12754. //
  12755. // If c were an exact power of ten, i.e. c = 10^k, one may determine k as
  12756. //
  12757. // k = ceil( log_10( 2^(alpha - e - 1) ) )
  12758. // = ceil( (alpha - e - 1) * log_10(2) )
  12759. //
  12760. // From the paper:
  12761. // "In theory the result of the procedure could be wrong since c is rounded,
  12762. // and the computation itself is approximated [...]. In practice, however,
  12763. // this simple function is sufficient."
  12764. //
  12765. // For IEEE double precision floating-point numbers converted into
  12766. // normalized diyfp's w = f * 2^e, with q = 64,
  12767. //
  12768. // e >= -1022 (min IEEE exponent)
  12769. // -52 (p - 1)
  12770. // -52 (p - 1, possibly normalize denormal IEEE numbers)
  12771. // -11 (normalize the diyfp)
  12772. // = -1137
  12773. //
  12774. // and
  12775. //
  12776. // e <= +1023 (max IEEE exponent)
  12777. // -52 (p - 1)
  12778. // -11 (normalize the diyfp)
  12779. // = 960
  12780. //
  12781. // This binary exponent range [-1137,960] results in a decimal exponent
  12782. // range [-307,324]. One does not need to store a cached power for each
  12783. // k in this range. For each such k it suffices to find a cached power
  12784. // such that the exponent of the product lies in [alpha,gamma].
  12785. // This implies that the difference of the decimal exponents of adjacent
  12786. // table entries must be less than or equal to
  12787. //
  12788. // floor( (gamma - alpha) * log_10(2) ) = 8.
  12789. //
  12790. // (A smaller distance gamma-alpha would require a larger table.)
  12791. // NB:
  12792. // Actually this function returns c, such that -60 <= e_c + e + 64 <= -34.
  12793. constexpr int kCachedPowersMinDecExp = -300;
  12794. constexpr int kCachedPowersDecStep = 8;
  12795. static constexpr std::array<cached_power, 79> kCachedPowers =
  12796. {
  12797. {
  12798. { 0xAB70FE17C79AC6CA, -1060, -300 },
  12799. { 0xFF77B1FCBEBCDC4F, -1034, -292 },
  12800. { 0xBE5691EF416BD60C, -1007, -284 },
  12801. { 0x8DD01FAD907FFC3C, -980, -276 },
  12802. { 0xD3515C2831559A83, -954, -268 },
  12803. { 0x9D71AC8FADA6C9B5, -927, -260 },
  12804. { 0xEA9C227723EE8BCB, -901, -252 },
  12805. { 0xAECC49914078536D, -874, -244 },
  12806. { 0x823C12795DB6CE57, -847, -236 },
  12807. { 0xC21094364DFB5637, -821, -228 },
  12808. { 0x9096EA6F3848984F, -794, -220 },
  12809. { 0xD77485CB25823AC7, -768, -212 },
  12810. { 0xA086CFCD97BF97F4, -741, -204 },
  12811. { 0xEF340A98172AACE5, -715, -196 },
  12812. { 0xB23867FB2A35B28E, -688, -188 },
  12813. { 0x84C8D4DFD2C63F3B, -661, -180 },
  12814. { 0xC5DD44271AD3CDBA, -635, -172 },
  12815. { 0x936B9FCEBB25C996, -608, -164 },
  12816. { 0xDBAC6C247D62A584, -582, -156 },
  12817. { 0xA3AB66580D5FDAF6, -555, -148 },
  12818. { 0xF3E2F893DEC3F126, -529, -140 },
  12819. { 0xB5B5ADA8AAFF80B8, -502, -132 },
  12820. { 0x87625F056C7C4A8B, -475, -124 },
  12821. { 0xC9BCFF6034C13053, -449, -116 },
  12822. { 0x964E858C91BA2655, -422, -108 },
  12823. { 0xDFF9772470297EBD, -396, -100 },
  12824. { 0xA6DFBD9FB8E5B88F, -369, -92 },
  12825. { 0xF8A95FCF88747D94, -343, -84 },
  12826. { 0xB94470938FA89BCF, -316, -76 },
  12827. { 0x8A08F0F8BF0F156B, -289, -68 },
  12828. { 0xCDB02555653131B6, -263, -60 },
  12829. { 0x993FE2C6D07B7FAC, -236, -52 },
  12830. { 0xE45C10C42A2B3B06, -210, -44 },
  12831. { 0xAA242499697392D3, -183, -36 },
  12832. { 0xFD87B5F28300CA0E, -157, -28 },
  12833. { 0xBCE5086492111AEB, -130, -20 },
  12834. { 0x8CBCCC096F5088CC, -103, -12 },
  12835. { 0xD1B71758E219652C, -77, -4 },
  12836. { 0x9C40000000000000, -50, 4 },
  12837. { 0xE8D4A51000000000, -24, 12 },
  12838. { 0xAD78EBC5AC620000, 3, 20 },
  12839. { 0x813F3978F8940984, 30, 28 },
  12840. { 0xC097CE7BC90715B3, 56, 36 },
  12841. { 0x8F7E32CE7BEA5C70, 83, 44 },
  12842. { 0xD5D238A4ABE98068, 109, 52 },
  12843. { 0x9F4F2726179A2245, 136, 60 },
  12844. { 0xED63A231D4C4FB27, 162, 68 },
  12845. { 0xB0DE65388CC8ADA8, 189, 76 },
  12846. { 0x83C7088E1AAB65DB, 216, 84 },
  12847. { 0xC45D1DF942711D9A, 242, 92 },
  12848. { 0x924D692CA61BE758, 269, 100 },
  12849. { 0xDA01EE641A708DEA, 295, 108 },
  12850. { 0xA26DA3999AEF774A, 322, 116 },
  12851. { 0xF209787BB47D6B85, 348, 124 },
  12852. { 0xB454E4A179DD1877, 375, 132 },
  12853. { 0x865B86925B9BC5C2, 402, 140 },
  12854. { 0xC83553C5C8965D3D, 428, 148 },
  12855. { 0x952AB45CFA97A0B3, 455, 156 },
  12856. { 0xDE469FBD99A05FE3, 481, 164 },
  12857. { 0xA59BC234DB398C25, 508, 172 },
  12858. { 0xF6C69A72A3989F5C, 534, 180 },
  12859. { 0xB7DCBF5354E9BECE, 561, 188 },
  12860. { 0x88FCF317F22241E2, 588, 196 },
  12861. { 0xCC20CE9BD35C78A5, 614, 204 },
  12862. { 0x98165AF37B2153DF, 641, 212 },
  12863. { 0xE2A0B5DC971F303A, 667, 220 },
  12864. { 0xA8D9D1535CE3B396, 694, 228 },
  12865. { 0xFB9B7CD9A4A7443C, 720, 236 },
  12866. { 0xBB764C4CA7A44410, 747, 244 },
  12867. { 0x8BAB8EEFB6409C1A, 774, 252 },
  12868. { 0xD01FEF10A657842C, 800, 260 },
  12869. { 0x9B10A4E5E9913129, 827, 268 },
  12870. { 0xE7109BFBA19C0C9D, 853, 276 },
  12871. { 0xAC2820D9623BF429, 880, 284 },
  12872. { 0x80444B5E7AA7CF85, 907, 292 },
  12873. { 0xBF21E44003ACDD2D, 933, 300 },
  12874. { 0x8E679C2F5E44FF8F, 960, 308 },
  12875. { 0xD433179D9C8CB841, 986, 316 },
  12876. { 0x9E19DB92B4E31BA9, 1013, 324 },
  12877. }
  12878. };
  12879. // This computation gives exactly the same results for k as
  12880. // k = ceil((kAlpha - e - 1) * 0.30102999566398114)
  12881. // for |e| <= 1500, but doesn't require floating-point operations.
  12882. // NB: log_10(2) ~= 78913 / 2^18
  12883. JSON_ASSERT(e >= -1500);
  12884. JSON_ASSERT(e <= 1500);
  12885. const int f = kAlpha - e - 1;
  12886. const int k = (f * 78913) / (1 << 18) + static_cast<int>(f > 0);
  12887. const int index = (-kCachedPowersMinDecExp + k + (kCachedPowersDecStep - 1)) / kCachedPowersDecStep;
  12888. JSON_ASSERT(index >= 0);
  12889. JSON_ASSERT(static_cast<std::size_t>(index) < kCachedPowers.size());
  12890. const cached_power cached = kCachedPowers[static_cast<std::size_t>(index)];
  12891. JSON_ASSERT(kAlpha <= cached.e + e + 64);
  12892. JSON_ASSERT(kGamma >= cached.e + e + 64);
  12893. return cached;
  12894. }
  12895. /*!
  12896. For n != 0, returns k, such that pow10 := 10^(k-1) <= n < 10^k.
  12897. For n == 0, returns 1 and sets pow10 := 1.
  12898. */
  12899. inline int find_largest_pow10(const std::uint32_t n, std::uint32_t& pow10)
  12900. {
  12901. // LCOV_EXCL_START
  12902. if (n >= 1000000000)
  12903. {
  12904. pow10 = 1000000000;
  12905. return 10;
  12906. }
  12907. // LCOV_EXCL_STOP
  12908. else if (n >= 100000000)
  12909. {
  12910. pow10 = 100000000;
  12911. return 9;
  12912. }
  12913. else if (n >= 10000000)
  12914. {
  12915. pow10 = 10000000;
  12916. return 8;
  12917. }
  12918. else if (n >= 1000000)
  12919. {
  12920. pow10 = 1000000;
  12921. return 7;
  12922. }
  12923. else if (n >= 100000)
  12924. {
  12925. pow10 = 100000;
  12926. return 6;
  12927. }
  12928. else if (n >= 10000)
  12929. {
  12930. pow10 = 10000;
  12931. return 5;
  12932. }
  12933. else if (n >= 1000)
  12934. {
  12935. pow10 = 1000;
  12936. return 4;
  12937. }
  12938. else if (n >= 100)
  12939. {
  12940. pow10 = 100;
  12941. return 3;
  12942. }
  12943. else if (n >= 10)
  12944. {
  12945. pow10 = 10;
  12946. return 2;
  12947. }
  12948. else
  12949. {
  12950. pow10 = 1;
  12951. return 1;
  12952. }
  12953. }
  12954. inline void grisu2_round(char* buf, int len, std::uint64_t dist, std::uint64_t delta,
  12955. std::uint64_t rest, std::uint64_t ten_k)
  12956. {
  12957. JSON_ASSERT(len >= 1);
  12958. JSON_ASSERT(dist <= delta);
  12959. JSON_ASSERT(rest <= delta);
  12960. JSON_ASSERT(ten_k > 0);
  12961. // <--------------------------- delta ---->
  12962. // <---- dist --------->
  12963. // --------------[------------------+-------------------]--------------
  12964. // M- w M+
  12965. //
  12966. // ten_k
  12967. // <------>
  12968. // <---- rest ---->
  12969. // --------------[------------------+----+--------------]--------------
  12970. // w V
  12971. // = buf * 10^k
  12972. //
  12973. // ten_k represents a unit-in-the-last-place in the decimal representation
  12974. // stored in buf.
  12975. // Decrement buf by ten_k while this takes buf closer to w.
  12976. // The tests are written in this order to avoid overflow in unsigned
  12977. // integer arithmetic.
  12978. while (rest < dist
  12979. && delta - rest >= ten_k
  12980. && (rest + ten_k < dist || dist - rest > rest + ten_k - dist))
  12981. {
  12982. JSON_ASSERT(buf[len - 1] != '0');
  12983. buf[len - 1]--;
  12984. rest += ten_k;
  12985. }
  12986. }
  12987. /*!
  12988. Generates V = buffer * 10^decimal_exponent, such that M- <= V <= M+.
  12989. M- and M+ must be normalized and share the same exponent -60 <= e <= -32.
  12990. */
  12991. inline void grisu2_digit_gen(char* buffer, int& length, int& decimal_exponent,
  12992. diyfp M_minus, diyfp w, diyfp M_plus)
  12993. {
  12994. static_assert(kAlpha >= -60, "internal error");
  12995. static_assert(kGamma <= -32, "internal error");
  12996. // Generates the digits (and the exponent) of a decimal floating-point
  12997. // number V = buffer * 10^decimal_exponent in the range [M-, M+]. The diyfp's
  12998. // w, M- and M+ share the same exponent e, which satisfies alpha <= e <= gamma.
  12999. //
  13000. // <--------------------------- delta ---->
  13001. // <---- dist --------->
  13002. // --------------[------------------+-------------------]--------------
  13003. // M- w M+
  13004. //
  13005. // Grisu2 generates the digits of M+ from left to right and stops as soon as
  13006. // V is in [M-,M+].
  13007. JSON_ASSERT(M_plus.e >= kAlpha);
  13008. JSON_ASSERT(M_plus.e <= kGamma);
  13009. std::uint64_t delta = diyfp::sub(M_plus, M_minus).f; // (significand of (M+ - M-), implicit exponent is e)
  13010. std::uint64_t dist = diyfp::sub(M_plus, w ).f; // (significand of (M+ - w ), implicit exponent is e)
  13011. // Split M+ = f * 2^e into two parts p1 and p2 (note: e < 0):
  13012. //
  13013. // M+ = f * 2^e
  13014. // = ((f div 2^-e) * 2^-e + (f mod 2^-e)) * 2^e
  13015. // = ((p1 ) * 2^-e + (p2 )) * 2^e
  13016. // = p1 + p2 * 2^e
  13017. const diyfp one(std::uint64_t{1} << -M_plus.e, M_plus.e);
  13018. 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.)
  13019. std::uint64_t p2 = M_plus.f & (one.f - 1); // p2 = f mod 2^-e
  13020. // 1)
  13021. //
  13022. // Generate the digits of the integral part p1 = d[n-1]...d[1]d[0]
  13023. JSON_ASSERT(p1 > 0);
  13024. std::uint32_t pow10;
  13025. const int k = find_largest_pow10(p1, pow10);
  13026. // 10^(k-1) <= p1 < 10^k, pow10 = 10^(k-1)
  13027. //
  13028. // p1 = (p1 div 10^(k-1)) * 10^(k-1) + (p1 mod 10^(k-1))
  13029. // = (d[k-1] ) * 10^(k-1) + (p1 mod 10^(k-1))
  13030. //
  13031. // M+ = p1 + p2 * 2^e
  13032. // = d[k-1] * 10^(k-1) + (p1 mod 10^(k-1)) + p2 * 2^e
  13033. // = d[k-1] * 10^(k-1) + ((p1 mod 10^(k-1)) * 2^-e + p2) * 2^e
  13034. // = d[k-1] * 10^(k-1) + ( rest) * 2^e
  13035. //
  13036. // Now generate the digits d[n] of p1 from left to right (n = k-1,...,0)
  13037. //
  13038. // p1 = d[k-1]...d[n] * 10^n + d[n-1]...d[0]
  13039. //
  13040. // but stop as soon as
  13041. //
  13042. // rest * 2^e = (d[n-1]...d[0] * 2^-e + p2) * 2^e <= delta * 2^e
  13043. int n = k;
  13044. while (n > 0)
  13045. {
  13046. // Invariants:
  13047. // M+ = buffer * 10^n + (p1 + p2 * 2^e) (buffer = 0 for n = k)
  13048. // pow10 = 10^(n-1) <= p1 < 10^n
  13049. //
  13050. const std::uint32_t d = p1 / pow10; // d = p1 div 10^(n-1)
  13051. const std::uint32_t r = p1 % pow10; // r = p1 mod 10^(n-1)
  13052. //
  13053. // M+ = buffer * 10^n + (d * 10^(n-1) + r) + p2 * 2^e
  13054. // = (buffer * 10 + d) * 10^(n-1) + (r + p2 * 2^e)
  13055. //
  13056. JSON_ASSERT(d <= 9);
  13057. buffer[length++] = static_cast<char>('0' + d); // buffer := buffer * 10 + d
  13058. //
  13059. // M+ = buffer * 10^(n-1) + (r + p2 * 2^e)
  13060. //
  13061. p1 = r;
  13062. n--;
  13063. //
  13064. // M+ = buffer * 10^n + (p1 + p2 * 2^e)
  13065. // pow10 = 10^n
  13066. //
  13067. // Now check if enough digits have been generated.
  13068. // Compute
  13069. //
  13070. // p1 + p2 * 2^e = (p1 * 2^-e + p2) * 2^e = rest * 2^e
  13071. //
  13072. // Note:
  13073. // Since rest and delta share the same exponent e, it suffices to
  13074. // compare the significands.
  13075. const std::uint64_t rest = (std::uint64_t{p1} << -one.e) + p2;
  13076. if (rest <= delta)
  13077. {
  13078. // V = buffer * 10^n, with M- <= V <= M+.
  13079. decimal_exponent += n;
  13080. // We may now just stop. But instead look if the buffer could be
  13081. // decremented to bring V closer to w.
  13082. //
  13083. // pow10 = 10^n is now 1 ulp in the decimal representation V.
  13084. // The rounding procedure works with diyfp's with an implicit
  13085. // exponent of e.
  13086. //
  13087. // 10^n = (10^n * 2^-e) * 2^e = ulp * 2^e
  13088. //
  13089. const std::uint64_t ten_n = std::uint64_t{pow10} << -one.e;
  13090. grisu2_round(buffer, length, dist, delta, rest, ten_n);
  13091. return;
  13092. }
  13093. pow10 /= 10;
  13094. //
  13095. // pow10 = 10^(n-1) <= p1 < 10^n
  13096. // Invariants restored.
  13097. }
  13098. // 2)
  13099. //
  13100. // The digits of the integral part have been generated:
  13101. //
  13102. // M+ = d[k-1]...d[1]d[0] + p2 * 2^e
  13103. // = buffer + p2 * 2^e
  13104. //
  13105. // Now generate the digits of the fractional part p2 * 2^e.
  13106. //
  13107. // Note:
  13108. // No decimal point is generated: the exponent is adjusted instead.
  13109. //
  13110. // p2 actually represents the fraction
  13111. //
  13112. // p2 * 2^e
  13113. // = p2 / 2^-e
  13114. // = d[-1] / 10^1 + d[-2] / 10^2 + ...
  13115. //
  13116. // Now generate the digits d[-m] of p1 from left to right (m = 1,2,...)
  13117. //
  13118. // p2 * 2^e = d[-1]d[-2]...d[-m] * 10^-m
  13119. // + 10^-m * (d[-m-1] / 10^1 + d[-m-2] / 10^2 + ...)
  13120. //
  13121. // using
  13122. //
  13123. // 10^m * p2 = ((10^m * p2) div 2^-e) * 2^-e + ((10^m * p2) mod 2^-e)
  13124. // = ( d) * 2^-e + ( r)
  13125. //
  13126. // or
  13127. // 10^m * p2 * 2^e = d + r * 2^e
  13128. //
  13129. // i.e.
  13130. //
  13131. // M+ = buffer + p2 * 2^e
  13132. // = buffer + 10^-m * (d + r * 2^e)
  13133. // = (buffer * 10^m + d) * 10^-m + 10^-m * r * 2^e
  13134. //
  13135. // and stop as soon as 10^-m * r * 2^e <= delta * 2^e
  13136. JSON_ASSERT(p2 > delta);
  13137. int m = 0;
  13138. for (;;)
  13139. {
  13140. // Invariant:
  13141. // M+ = buffer * 10^-m + 10^-m * (d[-m-1] / 10 + d[-m-2] / 10^2 + ...) * 2^e
  13142. // = buffer * 10^-m + 10^-m * (p2 ) * 2^e
  13143. // = buffer * 10^-m + 10^-m * (1/10 * (10 * p2) ) * 2^e
  13144. // = buffer * 10^-m + 10^-m * (1/10 * ((10*p2 div 2^-e) * 2^-e + (10*p2 mod 2^-e)) * 2^e
  13145. //
  13146. JSON_ASSERT(p2 <= (std::numeric_limits<std::uint64_t>::max)() / 10);
  13147. p2 *= 10;
  13148. const std::uint64_t d = p2 >> -one.e; // d = (10 * p2) div 2^-e
  13149. const std::uint64_t r = p2 & (one.f - 1); // r = (10 * p2) mod 2^-e
  13150. //
  13151. // M+ = buffer * 10^-m + 10^-m * (1/10 * (d * 2^-e + r) * 2^e
  13152. // = buffer * 10^-m + 10^-m * (1/10 * (d + r * 2^e))
  13153. // = (buffer * 10 + d) * 10^(-m-1) + 10^(-m-1) * r * 2^e
  13154. //
  13155. JSON_ASSERT(d <= 9);
  13156. buffer[length++] = static_cast<char>('0' + d); // buffer := buffer * 10 + d
  13157. //
  13158. // M+ = buffer * 10^(-m-1) + 10^(-m-1) * r * 2^e
  13159. //
  13160. p2 = r;
  13161. m++;
  13162. //
  13163. // M+ = buffer * 10^-m + 10^-m * p2 * 2^e
  13164. // Invariant restored.
  13165. // Check if enough digits have been generated.
  13166. //
  13167. // 10^-m * p2 * 2^e <= delta * 2^e
  13168. // p2 * 2^e <= 10^m * delta * 2^e
  13169. // p2 <= 10^m * delta
  13170. delta *= 10;
  13171. dist *= 10;
  13172. if (p2 <= delta)
  13173. {
  13174. break;
  13175. }
  13176. }
  13177. // V = buffer * 10^-m, with M- <= V <= M+.
  13178. decimal_exponent -= m;
  13179. // 1 ulp in the decimal representation is now 10^-m.
  13180. // Since delta and dist are now scaled by 10^m, we need to do the
  13181. // same with ulp in order to keep the units in sync.
  13182. //
  13183. // 10^m * 10^-m = 1 = 2^-e * 2^e = ten_m * 2^e
  13184. //
  13185. const std::uint64_t ten_m = one.f;
  13186. grisu2_round(buffer, length, dist, delta, p2, ten_m);
  13187. // By construction this algorithm generates the shortest possible decimal
  13188. // number (Loitsch, Theorem 6.2) which rounds back to w.
  13189. // For an input number of precision p, at least
  13190. //
  13191. // N = 1 + ceil(p * log_10(2))
  13192. //
  13193. // decimal digits are sufficient to identify all binary floating-point
  13194. // numbers (Matula, "In-and-Out conversions").
  13195. // This implies that the algorithm does not produce more than N decimal
  13196. // digits.
  13197. //
  13198. // N = 17 for p = 53 (IEEE double precision)
  13199. // N = 9 for p = 24 (IEEE single precision)
  13200. }
  13201. /*!
  13202. v = buf * 10^decimal_exponent
  13203. len is the length of the buffer (number of decimal digits)
  13204. The buffer must be large enough, i.e. >= max_digits10.
  13205. */
  13206. JSON_HEDLEY_NON_NULL(1)
  13207. inline void grisu2(char* buf, int& len, int& decimal_exponent,
  13208. diyfp m_minus, diyfp v, diyfp m_plus)
  13209. {
  13210. JSON_ASSERT(m_plus.e == m_minus.e);
  13211. JSON_ASSERT(m_plus.e == v.e);
  13212. // --------(-----------------------+-----------------------)-------- (A)
  13213. // m- v m+
  13214. //
  13215. // --------------------(-----------+-----------------------)-------- (B)
  13216. // m- v m+
  13217. //
  13218. // First scale v (and m- and m+) such that the exponent is in the range
  13219. // [alpha, gamma].
  13220. const cached_power cached = get_cached_power_for_binary_exponent(m_plus.e);
  13221. const diyfp c_minus_k(cached.f, cached.e); // = c ~= 10^-k
  13222. // The exponent of the products is = v.e + c_minus_k.e + q and is in the range [alpha,gamma]
  13223. const diyfp w = diyfp::mul(v, c_minus_k);
  13224. const diyfp w_minus = diyfp::mul(m_minus, c_minus_k);
  13225. const diyfp w_plus = diyfp::mul(m_plus, c_minus_k);
  13226. // ----(---+---)---------------(---+---)---------------(---+---)----
  13227. // w- w w+
  13228. // = c*m- = c*v = c*m+
  13229. //
  13230. // diyfp::mul rounds its result and c_minus_k is approximated too. w, w- and
  13231. // w+ are now off by a small amount.
  13232. // In fact:
  13233. //
  13234. // w - v * 10^k < 1 ulp
  13235. //
  13236. // To account for this inaccuracy, add resp. subtract 1 ulp.
  13237. //
  13238. // --------+---[---------------(---+---)---------------]---+--------
  13239. // w- M- w M+ w+
  13240. //
  13241. // Now any number in [M-, M+] (bounds included) will round to w when input,
  13242. // regardless of how the input rounding algorithm breaks ties.
  13243. //
  13244. // And digit_gen generates the shortest possible such number in [M-, M+].
  13245. // Note that this does not mean that Grisu2 always generates the shortest
  13246. // possible number in the interval (m-, m+).
  13247. const diyfp M_minus(w_minus.f + 1, w_minus.e);
  13248. const diyfp M_plus (w_plus.f - 1, w_plus.e );
  13249. decimal_exponent = -cached.k; // = -(-k) = k
  13250. grisu2_digit_gen(buf, len, decimal_exponent, M_minus, w, M_plus);
  13251. }
  13252. /*!
  13253. v = buf * 10^decimal_exponent
  13254. len is the length of the buffer (number of decimal digits)
  13255. The buffer must be large enough, i.e. >= max_digits10.
  13256. */
  13257. template<typename FloatType>
  13258. JSON_HEDLEY_NON_NULL(1)
  13259. void grisu2(char* buf, int& len, int& decimal_exponent, FloatType value)
  13260. {
  13261. static_assert(diyfp::kPrecision >= std::numeric_limits<FloatType>::digits + 3,
  13262. "internal error: not enough precision");
  13263. JSON_ASSERT(std::isfinite(value));
  13264. JSON_ASSERT(value > 0);
  13265. // If the neighbors (and boundaries) of 'value' are always computed for double-precision
  13266. // numbers, all float's can be recovered using strtod (and strtof). However, the resulting
  13267. // decimal representations are not exactly "short".
  13268. //
  13269. // The documentation for 'std::to_chars' (https://en.cppreference.com/w/cpp/utility/to_chars)
  13270. // says "value is converted to a string as if by std::sprintf in the default ("C") locale"
  13271. // and since sprintf promotes float's to double's, I think this is exactly what 'std::to_chars'
  13272. // does.
  13273. // On the other hand, the documentation for 'std::to_chars' requires that "parsing the
  13274. // representation using the corresponding std::from_chars function recovers value exactly". That
  13275. // indicates that single precision floating-point numbers should be recovered using
  13276. // 'std::strtof'.
  13277. //
  13278. // NB: If the neighbors are computed for single-precision numbers, there is a single float
  13279. // (7.0385307e-26f) which can't be recovered using strtod. The resulting double precision
  13280. // value is off by 1 ulp.
  13281. #if 0
  13282. const boundaries w = compute_boundaries(static_cast<double>(value));
  13283. #else
  13284. const boundaries w = compute_boundaries(value);
  13285. #endif
  13286. grisu2(buf, len, decimal_exponent, w.minus, w.w, w.plus);
  13287. }
  13288. /*!
  13289. @brief appends a decimal representation of e to buf
  13290. @return a pointer to the element following the exponent.
  13291. @pre -1000 < e < 1000
  13292. */
  13293. JSON_HEDLEY_NON_NULL(1)
  13294. JSON_HEDLEY_RETURNS_NON_NULL
  13295. inline char* append_exponent(char* buf, int e)
  13296. {
  13297. JSON_ASSERT(e > -1000);
  13298. JSON_ASSERT(e < 1000);
  13299. if (e < 0)
  13300. {
  13301. e = -e;
  13302. *buf++ = '-';
  13303. }
  13304. else
  13305. {
  13306. *buf++ = '+';
  13307. }
  13308. auto k = static_cast<std::uint32_t>(e);
  13309. if (k < 10)
  13310. {
  13311. // Always print at least two digits in the exponent.
  13312. // This is for compatibility with printf("%g").
  13313. *buf++ = '0';
  13314. *buf++ = static_cast<char>('0' + k);
  13315. }
  13316. else if (k < 100)
  13317. {
  13318. *buf++ = static_cast<char>('0' + k / 10);
  13319. k %= 10;
  13320. *buf++ = static_cast<char>('0' + k);
  13321. }
  13322. else
  13323. {
  13324. *buf++ = static_cast<char>('0' + k / 100);
  13325. k %= 100;
  13326. *buf++ = static_cast<char>('0' + k / 10);
  13327. k %= 10;
  13328. *buf++ = static_cast<char>('0' + k);
  13329. }
  13330. return buf;
  13331. }
  13332. /*!
  13333. @brief prettify v = buf * 10^decimal_exponent
  13334. If v is in the range [10^min_exp, 10^max_exp) it will be printed in fixed-point
  13335. notation. Otherwise it will be printed in exponential notation.
  13336. @pre min_exp < 0
  13337. @pre max_exp > 0
  13338. */
  13339. JSON_HEDLEY_NON_NULL(1)
  13340. JSON_HEDLEY_RETURNS_NON_NULL
  13341. inline char* format_buffer(char* buf, int len, int decimal_exponent,
  13342. int min_exp, int max_exp)
  13343. {
  13344. JSON_ASSERT(min_exp < 0);
  13345. JSON_ASSERT(max_exp > 0);
  13346. const int k = len;
  13347. const int n = len + decimal_exponent;
  13348. // v = buf * 10^(n-k)
  13349. // k is the length of the buffer (number of decimal digits)
  13350. // n is the position of the decimal point relative to the start of the buffer.
  13351. if (k <= n && n <= max_exp)
  13352. {
  13353. // digits[000]
  13354. // len <= max_exp + 2
  13355. std::memset(buf + k, '0', static_cast<size_t>(n) - static_cast<size_t>(k));
  13356. // Make it look like a floating-point number (#362, #378)
  13357. buf[n + 0] = '.';
  13358. buf[n + 1] = '0';
  13359. return buf + (static_cast<size_t>(n) + 2);
  13360. }
  13361. if (0 < n && n <= max_exp)
  13362. {
  13363. // dig.its
  13364. // len <= max_digits10 + 1
  13365. JSON_ASSERT(k > n);
  13366. std::memmove(buf + (static_cast<size_t>(n) + 1), buf + n, static_cast<size_t>(k) - static_cast<size_t>(n));
  13367. buf[n] = '.';
  13368. return buf + (static_cast<size_t>(k) + 1U);
  13369. }
  13370. if (min_exp < n && n <= 0)
  13371. {
  13372. // 0.[000]digits
  13373. // len <= 2 + (-min_exp - 1) + max_digits10
  13374. std::memmove(buf + (2 + static_cast<size_t>(-n)), buf, static_cast<size_t>(k));
  13375. buf[0] = '0';
  13376. buf[1] = '.';
  13377. std::memset(buf + 2, '0', static_cast<size_t>(-n));
  13378. return buf + (2U + static_cast<size_t>(-n) + static_cast<size_t>(k));
  13379. }
  13380. if (k == 1)
  13381. {
  13382. // dE+123
  13383. // len <= 1 + 5
  13384. buf += 1;
  13385. }
  13386. else
  13387. {
  13388. // d.igitsE+123
  13389. // len <= max_digits10 + 1 + 5
  13390. std::memmove(buf + 2, buf + 1, static_cast<size_t>(k) - 1);
  13391. buf[1] = '.';
  13392. buf += 1 + static_cast<size_t>(k);
  13393. }
  13394. *buf++ = 'e';
  13395. return append_exponent(buf, n - 1);
  13396. }
  13397. } // namespace dtoa_impl
  13398. /*!
  13399. @brief generates a decimal representation of the floating-point number value in [first, last).
  13400. The format of the resulting decimal representation is similar to printf's %g
  13401. format. Returns an iterator pointing past-the-end of the decimal representation.
  13402. @note The input number must be finite, i.e. NaN's and Inf's are not supported.
  13403. @note The buffer must be large enough.
  13404. @note The result is NOT null-terminated.
  13405. */
  13406. template<typename FloatType>
  13407. JSON_HEDLEY_NON_NULL(1, 2)
  13408. JSON_HEDLEY_RETURNS_NON_NULL
  13409. char* to_chars(char* first, const char* last, FloatType value)
  13410. {
  13411. static_cast<void>(last); // maybe unused - fix warning
  13412. JSON_ASSERT(std::isfinite(value));
  13413. // Use signbit(value) instead of (value < 0) since signbit works for -0.
  13414. if (std::signbit(value))
  13415. {
  13416. value = -value;
  13417. *first++ = '-';
  13418. }
  13419. if (value == 0) // +-0
  13420. {
  13421. *first++ = '0';
  13422. // Make it look like a floating-point number (#362, #378)
  13423. *first++ = '.';
  13424. *first++ = '0';
  13425. return first;
  13426. }
  13427. JSON_ASSERT(last - first >= std::numeric_limits<FloatType>::max_digits10);
  13428. // Compute v = buffer * 10^decimal_exponent.
  13429. // The decimal digits are stored in the buffer, which needs to be interpreted
  13430. // as an unsigned decimal integer.
  13431. // len is the length of the buffer, i.e. the number of decimal digits.
  13432. int len = 0;
  13433. int decimal_exponent = 0;
  13434. dtoa_impl::grisu2(first, len, decimal_exponent, value);
  13435. JSON_ASSERT(len <= std::numeric_limits<FloatType>::max_digits10);
  13436. // Format the buffer like printf("%.*g", prec, value)
  13437. constexpr int kMinExp = -4;
  13438. // Use digits10 here to increase compatibility with version 2.
  13439. constexpr int kMaxExp = std::numeric_limits<FloatType>::digits10;
  13440. JSON_ASSERT(last - first >= kMaxExp + 2);
  13441. JSON_ASSERT(last - first >= 2 + (-kMinExp - 1) + std::numeric_limits<FloatType>::max_digits10);
  13442. JSON_ASSERT(last - first >= std::numeric_limits<FloatType>::max_digits10 + 6);
  13443. return dtoa_impl::format_buffer(first, len, decimal_exponent, kMinExp, kMaxExp);
  13444. }
  13445. } // namespace detail
  13446. } // namespace nlohmann
  13447. // #include <nlohmann/detail/exceptions.hpp>
  13448. // #include <nlohmann/detail/macro_scope.hpp>
  13449. // #include <nlohmann/detail/meta/cpp_future.hpp>
  13450. // #include <nlohmann/detail/output/binary_writer.hpp>
  13451. // #include <nlohmann/detail/output/output_adapters.hpp>
  13452. // #include <nlohmann/detail/value_t.hpp>
  13453. namespace nlohmann
  13454. {
  13455. namespace detail
  13456. {
  13457. ///////////////////
  13458. // serialization //
  13459. ///////////////////
  13460. /// how to treat decoding errors
  13461. enum class error_handler_t
  13462. {
  13463. strict, ///< throw a type_error exception in case of invalid UTF-8
  13464. replace, ///< replace invalid UTF-8 sequences with U+FFFD
  13465. ignore ///< ignore invalid UTF-8 sequences
  13466. };
  13467. template<typename BasicJsonType>
  13468. class serializer
  13469. {
  13470. using string_t = typename BasicJsonType::string_t;
  13471. using number_float_t = typename BasicJsonType::number_float_t;
  13472. using number_integer_t = typename BasicJsonType::number_integer_t;
  13473. using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
  13474. using binary_char_t = typename BasicJsonType::binary_t::value_type;
  13475. static constexpr std::uint8_t UTF8_ACCEPT = 0;
  13476. static constexpr std::uint8_t UTF8_REJECT = 1;
  13477. public:
  13478. /*!
  13479. @param[in] s output stream to serialize to
  13480. @param[in] ichar indentation character to use
  13481. @param[in] error_handler_ how to react on decoding errors
  13482. */
  13483. serializer(output_adapter_t<char> s, const char ichar,
  13484. error_handler_t error_handler_ = error_handler_t::strict)
  13485. : o(std::move(s))
  13486. , loc(std::localeconv())
  13487. , thousands_sep(loc->thousands_sep == nullptr ? '\0' : std::char_traits<char>::to_char_type(* (loc->thousands_sep)))
  13488. , decimal_point(loc->decimal_point == nullptr ? '\0' : std::char_traits<char>::to_char_type(* (loc->decimal_point)))
  13489. , indent_char(ichar)
  13490. , indent_string(512, indent_char)
  13491. , error_handler(error_handler_)
  13492. {}
  13493. // delete because of pointer members
  13494. serializer(const serializer&) = delete;
  13495. serializer& operator=(const serializer&) = delete;
  13496. serializer(serializer&&) = delete;
  13497. serializer& operator=(serializer&&) = delete;
  13498. ~serializer() = default;
  13499. /*!
  13500. @brief internal implementation of the serialization function
  13501. This function is called by the public member function dump and organizes
  13502. the serialization internally. The indentation level is propagated as
  13503. additional parameter. In case of arrays and objects, the function is
  13504. called recursively.
  13505. - strings and object keys are escaped using `escape_string()`
  13506. - integer numbers are converted implicitly via `operator<<`
  13507. - floating-point numbers are converted to a string using `"%g"` format
  13508. - binary values are serialized as objects containing the subtype and the
  13509. byte array
  13510. @param[in] val value to serialize
  13511. @param[in] pretty_print whether the output shall be pretty-printed
  13512. @param[in] ensure_ascii If @a ensure_ascii is true, all non-ASCII characters
  13513. in the output are escaped with `\uXXXX` sequences, and the result consists
  13514. of ASCII characters only.
  13515. @param[in] indent_step the indent level
  13516. @param[in] current_indent the current indent level (only used internally)
  13517. */
  13518. void dump(const BasicJsonType& val,
  13519. const bool pretty_print,
  13520. const bool ensure_ascii,
  13521. const unsigned int indent_step,
  13522. const unsigned int current_indent = 0)
  13523. {
  13524. switch (val.m_type)
  13525. {
  13526. case value_t::object:
  13527. {
  13528. if (val.m_value.object->empty())
  13529. {
  13530. o->write_characters("{}", 2);
  13531. return;
  13532. }
  13533. if (pretty_print)
  13534. {
  13535. o->write_characters("{\n", 2);
  13536. // variable to hold indentation for recursive calls
  13537. const auto new_indent = current_indent + indent_step;
  13538. if (JSON_HEDLEY_UNLIKELY(indent_string.size() < new_indent))
  13539. {
  13540. indent_string.resize(indent_string.size() * 2, ' ');
  13541. }
  13542. // first n-1 elements
  13543. auto i = val.m_value.object->cbegin();
  13544. for (std::size_t cnt = 0; cnt < val.m_value.object->size() - 1; ++cnt, ++i)
  13545. {
  13546. o->write_characters(indent_string.c_str(), new_indent);
  13547. o->write_character('\"');
  13548. dump_escaped(i->first, ensure_ascii);
  13549. o->write_characters("\": ", 3);
  13550. dump(i->second, true, ensure_ascii, indent_step, new_indent);
  13551. o->write_characters(",\n", 2);
  13552. }
  13553. // last element
  13554. JSON_ASSERT(i != val.m_value.object->cend());
  13555. JSON_ASSERT(std::next(i) == val.m_value.object->cend());
  13556. o->write_characters(indent_string.c_str(), new_indent);
  13557. o->write_character('\"');
  13558. dump_escaped(i->first, ensure_ascii);
  13559. o->write_characters("\": ", 3);
  13560. dump(i->second, true, ensure_ascii, indent_step, new_indent);
  13561. o->write_character('\n');
  13562. o->write_characters(indent_string.c_str(), current_indent);
  13563. o->write_character('}');
  13564. }
  13565. else
  13566. {
  13567. o->write_character('{');
  13568. // first n-1 elements
  13569. auto i = val.m_value.object->cbegin();
  13570. for (std::size_t cnt = 0; cnt < val.m_value.object->size() - 1; ++cnt, ++i)
  13571. {
  13572. o->write_character('\"');
  13573. dump_escaped(i->first, ensure_ascii);
  13574. o->write_characters("\":", 2);
  13575. dump(i->second, false, ensure_ascii, indent_step, current_indent);
  13576. o->write_character(',');
  13577. }
  13578. // last element
  13579. JSON_ASSERT(i != val.m_value.object->cend());
  13580. JSON_ASSERT(std::next(i) == val.m_value.object->cend());
  13581. o->write_character('\"');
  13582. dump_escaped(i->first, ensure_ascii);
  13583. o->write_characters("\":", 2);
  13584. dump(i->second, false, ensure_ascii, indent_step, current_indent);
  13585. o->write_character('}');
  13586. }
  13587. return;
  13588. }
  13589. case value_t::array:
  13590. {
  13591. if (val.m_value.array->empty())
  13592. {
  13593. o->write_characters("[]", 2);
  13594. return;
  13595. }
  13596. if (pretty_print)
  13597. {
  13598. o->write_characters("[\n", 2);
  13599. // variable to hold indentation for recursive calls
  13600. const auto new_indent = current_indent + indent_step;
  13601. if (JSON_HEDLEY_UNLIKELY(indent_string.size() < new_indent))
  13602. {
  13603. indent_string.resize(indent_string.size() * 2, ' ');
  13604. }
  13605. // first n-1 elements
  13606. for (auto i = val.m_value.array->cbegin();
  13607. i != val.m_value.array->cend() - 1; ++i)
  13608. {
  13609. o->write_characters(indent_string.c_str(), new_indent);
  13610. dump(*i, true, ensure_ascii, indent_step, new_indent);
  13611. o->write_characters(",\n", 2);
  13612. }
  13613. // last element
  13614. JSON_ASSERT(!val.m_value.array->empty());
  13615. o->write_characters(indent_string.c_str(), new_indent);
  13616. dump(val.m_value.array->back(), true, ensure_ascii, indent_step, new_indent);
  13617. o->write_character('\n');
  13618. o->write_characters(indent_string.c_str(), current_indent);
  13619. o->write_character(']');
  13620. }
  13621. else
  13622. {
  13623. o->write_character('[');
  13624. // first n-1 elements
  13625. for (auto i = val.m_value.array->cbegin();
  13626. i != val.m_value.array->cend() - 1; ++i)
  13627. {
  13628. dump(*i, false, ensure_ascii, indent_step, current_indent);
  13629. o->write_character(',');
  13630. }
  13631. // last element
  13632. JSON_ASSERT(!val.m_value.array->empty());
  13633. dump(val.m_value.array->back(), false, ensure_ascii, indent_step, current_indent);
  13634. o->write_character(']');
  13635. }
  13636. return;
  13637. }
  13638. case value_t::string:
  13639. {
  13640. o->write_character('\"');
  13641. dump_escaped(*val.m_value.string, ensure_ascii);
  13642. o->write_character('\"');
  13643. return;
  13644. }
  13645. case value_t::binary:
  13646. {
  13647. if (pretty_print)
  13648. {
  13649. o->write_characters("{\n", 2);
  13650. // variable to hold indentation for recursive calls
  13651. const auto new_indent = current_indent + indent_step;
  13652. if (JSON_HEDLEY_UNLIKELY(indent_string.size() < new_indent))
  13653. {
  13654. indent_string.resize(indent_string.size() * 2, ' ');
  13655. }
  13656. o->write_characters(indent_string.c_str(), new_indent);
  13657. o->write_characters("\"bytes\": [", 10);
  13658. if (!val.m_value.binary->empty())
  13659. {
  13660. for (auto i = val.m_value.binary->cbegin();
  13661. i != val.m_value.binary->cend() - 1; ++i)
  13662. {
  13663. dump_integer(*i);
  13664. o->write_characters(", ", 2);
  13665. }
  13666. dump_integer(val.m_value.binary->back());
  13667. }
  13668. o->write_characters("],\n", 3);
  13669. o->write_characters(indent_string.c_str(), new_indent);
  13670. o->write_characters("\"subtype\": ", 11);
  13671. if (val.m_value.binary->has_subtype())
  13672. {
  13673. dump_integer(val.m_value.binary->subtype());
  13674. }
  13675. else
  13676. {
  13677. o->write_characters("null", 4);
  13678. }
  13679. o->write_character('\n');
  13680. o->write_characters(indent_string.c_str(), current_indent);
  13681. o->write_character('}');
  13682. }
  13683. else
  13684. {
  13685. o->write_characters("{\"bytes\":[", 10);
  13686. if (!val.m_value.binary->empty())
  13687. {
  13688. for (auto i = val.m_value.binary->cbegin();
  13689. i != val.m_value.binary->cend() - 1; ++i)
  13690. {
  13691. dump_integer(*i);
  13692. o->write_character(',');
  13693. }
  13694. dump_integer(val.m_value.binary->back());
  13695. }
  13696. o->write_characters("],\"subtype\":", 12);
  13697. if (val.m_value.binary->has_subtype())
  13698. {
  13699. dump_integer(val.m_value.binary->subtype());
  13700. o->write_character('}');
  13701. }
  13702. else
  13703. {
  13704. o->write_characters("null}", 5);
  13705. }
  13706. }
  13707. return;
  13708. }
  13709. case value_t::boolean:
  13710. {
  13711. if (val.m_value.boolean)
  13712. {
  13713. o->write_characters("true", 4);
  13714. }
  13715. else
  13716. {
  13717. o->write_characters("false", 5);
  13718. }
  13719. return;
  13720. }
  13721. case value_t::number_integer:
  13722. {
  13723. dump_integer(val.m_value.number_integer);
  13724. return;
  13725. }
  13726. case value_t::number_unsigned:
  13727. {
  13728. dump_integer(val.m_value.number_unsigned);
  13729. return;
  13730. }
  13731. case value_t::number_float:
  13732. {
  13733. dump_float(val.m_value.number_float);
  13734. return;
  13735. }
  13736. case value_t::discarded:
  13737. {
  13738. o->write_characters("<discarded>", 11);
  13739. return;
  13740. }
  13741. case value_t::null:
  13742. {
  13743. o->write_characters("null", 4);
  13744. return;
  13745. }
  13746. default: // LCOV_EXCL_LINE
  13747. JSON_ASSERT(false); // LCOV_EXCL_LINE
  13748. }
  13749. }
  13750. private:
  13751. /*!
  13752. @brief dump escaped string
  13753. Escape a string by replacing certain special characters by a sequence of an
  13754. escape character (backslash) and another character and other control
  13755. characters by a sequence of "\u" followed by a four-digit hex
  13756. representation. The escaped string is written to output stream @a o.
  13757. @param[in] s the string to escape
  13758. @param[in] ensure_ascii whether to escape non-ASCII characters with
  13759. \uXXXX sequences
  13760. @complexity Linear in the length of string @a s.
  13761. */
  13762. void dump_escaped(const string_t& s, const bool ensure_ascii)
  13763. {
  13764. std::uint32_t codepoint;
  13765. std::uint8_t state = UTF8_ACCEPT;
  13766. std::size_t bytes = 0; // number of bytes written to string_buffer
  13767. // number of bytes written at the point of the last valid byte
  13768. std::size_t bytes_after_last_accept = 0;
  13769. std::size_t undumped_chars = 0;
  13770. for (std::size_t i = 0; i < s.size(); ++i)
  13771. {
  13772. const auto byte = static_cast<uint8_t>(s[i]);
  13773. switch (decode(state, codepoint, byte))
  13774. {
  13775. case UTF8_ACCEPT: // decode found a new code point
  13776. {
  13777. switch (codepoint)
  13778. {
  13779. case 0x08: // backspace
  13780. {
  13781. string_buffer[bytes++] = '\\';
  13782. string_buffer[bytes++] = 'b';
  13783. break;
  13784. }
  13785. case 0x09: // horizontal tab
  13786. {
  13787. string_buffer[bytes++] = '\\';
  13788. string_buffer[bytes++] = 't';
  13789. break;
  13790. }
  13791. case 0x0A: // newline
  13792. {
  13793. string_buffer[bytes++] = '\\';
  13794. string_buffer[bytes++] = 'n';
  13795. break;
  13796. }
  13797. case 0x0C: // formfeed
  13798. {
  13799. string_buffer[bytes++] = '\\';
  13800. string_buffer[bytes++] = 'f';
  13801. break;
  13802. }
  13803. case 0x0D: // carriage return
  13804. {
  13805. string_buffer[bytes++] = '\\';
  13806. string_buffer[bytes++] = 'r';
  13807. break;
  13808. }
  13809. case 0x22: // quotation mark
  13810. {
  13811. string_buffer[bytes++] = '\\';
  13812. string_buffer[bytes++] = '\"';
  13813. break;
  13814. }
  13815. case 0x5C: // reverse solidus
  13816. {
  13817. string_buffer[bytes++] = '\\';
  13818. string_buffer[bytes++] = '\\';
  13819. break;
  13820. }
  13821. default:
  13822. {
  13823. // escape control characters (0x00..0x1F) or, if
  13824. // ensure_ascii parameter is used, non-ASCII characters
  13825. if ((codepoint <= 0x1F) || (ensure_ascii && (codepoint >= 0x7F)))
  13826. {
  13827. if (codepoint <= 0xFFFF)
  13828. {
  13829. (std::snprintf)(string_buffer.data() + bytes, 7, "\\u%04x",
  13830. static_cast<std::uint16_t>(codepoint));
  13831. bytes += 6;
  13832. }
  13833. else
  13834. {
  13835. (std::snprintf)(string_buffer.data() + bytes, 13, "\\u%04x\\u%04x",
  13836. static_cast<std::uint16_t>(0xD7C0u + (codepoint >> 10u)),
  13837. static_cast<std::uint16_t>(0xDC00u + (codepoint & 0x3FFu)));
  13838. bytes += 12;
  13839. }
  13840. }
  13841. else
  13842. {
  13843. // copy byte to buffer (all previous bytes
  13844. // been copied have in default case above)
  13845. string_buffer[bytes++] = s[i];
  13846. }
  13847. break;
  13848. }
  13849. }
  13850. // write buffer and reset index; there must be 13 bytes
  13851. // left, as this is the maximal number of bytes to be
  13852. // written ("\uxxxx\uxxxx\0") for one code point
  13853. if (string_buffer.size() - bytes < 13)
  13854. {
  13855. o->write_characters(string_buffer.data(), bytes);
  13856. bytes = 0;
  13857. }
  13858. // remember the byte position of this accept
  13859. bytes_after_last_accept = bytes;
  13860. undumped_chars = 0;
  13861. break;
  13862. }
  13863. case UTF8_REJECT: // decode found invalid UTF-8 byte
  13864. {
  13865. switch (error_handler)
  13866. {
  13867. case error_handler_t::strict:
  13868. {
  13869. std::string sn(3, '\0');
  13870. (std::snprintf)(&sn[0], sn.size(), "%.2X", byte);
  13871. JSON_THROW(type_error::create(316, "invalid UTF-8 byte at index " + std::to_string(i) + ": 0x" + sn));
  13872. }
  13873. case error_handler_t::ignore:
  13874. case error_handler_t::replace:
  13875. {
  13876. // in case we saw this character the first time, we
  13877. // would like to read it again, because the byte
  13878. // may be OK for itself, but just not OK for the
  13879. // previous sequence
  13880. if (undumped_chars > 0)
  13881. {
  13882. --i;
  13883. }
  13884. // reset length buffer to the last accepted index;
  13885. // thus removing/ignoring the invalid characters
  13886. bytes = bytes_after_last_accept;
  13887. if (error_handler == error_handler_t::replace)
  13888. {
  13889. // add a replacement character
  13890. if (ensure_ascii)
  13891. {
  13892. string_buffer[bytes++] = '\\';
  13893. string_buffer[bytes++] = 'u';
  13894. string_buffer[bytes++] = 'f';
  13895. string_buffer[bytes++] = 'f';
  13896. string_buffer[bytes++] = 'f';
  13897. string_buffer[bytes++] = 'd';
  13898. }
  13899. else
  13900. {
  13901. string_buffer[bytes++] = detail::binary_writer<BasicJsonType, char>::to_char_type('\xEF');
  13902. string_buffer[bytes++] = detail::binary_writer<BasicJsonType, char>::to_char_type('\xBF');
  13903. string_buffer[bytes++] = detail::binary_writer<BasicJsonType, char>::to_char_type('\xBD');
  13904. }
  13905. // write buffer and reset index; there must be 13 bytes
  13906. // left, as this is the maximal number of bytes to be
  13907. // written ("\uxxxx\uxxxx\0") for one code point
  13908. if (string_buffer.size() - bytes < 13)
  13909. {
  13910. o->write_characters(string_buffer.data(), bytes);
  13911. bytes = 0;
  13912. }
  13913. bytes_after_last_accept = bytes;
  13914. }
  13915. undumped_chars = 0;
  13916. // continue processing the string
  13917. state = UTF8_ACCEPT;
  13918. break;
  13919. }
  13920. default: // LCOV_EXCL_LINE
  13921. JSON_ASSERT(false); // LCOV_EXCL_LINE
  13922. }
  13923. break;
  13924. }
  13925. default: // decode found yet incomplete multi-byte code point
  13926. {
  13927. if (!ensure_ascii)
  13928. {
  13929. // code point will not be escaped - copy byte to buffer
  13930. string_buffer[bytes++] = s[i];
  13931. }
  13932. ++undumped_chars;
  13933. break;
  13934. }
  13935. }
  13936. }
  13937. // we finished processing the string
  13938. if (JSON_HEDLEY_LIKELY(state == UTF8_ACCEPT))
  13939. {
  13940. // write buffer
  13941. if (bytes > 0)
  13942. {
  13943. o->write_characters(string_buffer.data(), bytes);
  13944. }
  13945. }
  13946. else
  13947. {
  13948. // we finish reading, but do not accept: string was incomplete
  13949. switch (error_handler)
  13950. {
  13951. case error_handler_t::strict:
  13952. {
  13953. std::string sn(3, '\0');
  13954. (std::snprintf)(&sn[0], sn.size(), "%.2X", static_cast<std::uint8_t>(s.back()));
  13955. JSON_THROW(type_error::create(316, "incomplete UTF-8 string; last byte: 0x" + sn));
  13956. }
  13957. case error_handler_t::ignore:
  13958. {
  13959. // write all accepted bytes
  13960. o->write_characters(string_buffer.data(), bytes_after_last_accept);
  13961. break;
  13962. }
  13963. case error_handler_t::replace:
  13964. {
  13965. // write all accepted bytes
  13966. o->write_characters(string_buffer.data(), bytes_after_last_accept);
  13967. // add a replacement character
  13968. if (ensure_ascii)
  13969. {
  13970. o->write_characters("\\ufffd", 6);
  13971. }
  13972. else
  13973. {
  13974. o->write_characters("\xEF\xBF\xBD", 3);
  13975. }
  13976. break;
  13977. }
  13978. default: // LCOV_EXCL_LINE
  13979. JSON_ASSERT(false); // LCOV_EXCL_LINE
  13980. }
  13981. }
  13982. }
  13983. /*!
  13984. @brief count digits
  13985. Count the number of decimal (base 10) digits for an input unsigned integer.
  13986. @param[in] x unsigned integer number to count its digits
  13987. @return number of decimal digits
  13988. */
  13989. inline unsigned int count_digits(number_unsigned_t x) noexcept
  13990. {
  13991. unsigned int n_digits = 1;
  13992. for (;;)
  13993. {
  13994. if (x < 10)
  13995. {
  13996. return n_digits;
  13997. }
  13998. if (x < 100)
  13999. {
  14000. return n_digits + 1;
  14001. }
  14002. if (x < 1000)
  14003. {
  14004. return n_digits + 2;
  14005. }
  14006. if (x < 10000)
  14007. {
  14008. return n_digits + 3;
  14009. }
  14010. x = x / 10000u;
  14011. n_digits += 4;
  14012. }
  14013. }
  14014. /*!
  14015. @brief dump an integer
  14016. Dump a given integer to output stream @a o. Works internally with
  14017. @a number_buffer.
  14018. @param[in] x integer number (signed or unsigned) to dump
  14019. @tparam NumberType either @a number_integer_t or @a number_unsigned_t
  14020. */
  14021. template < typename NumberType, detail::enable_if_t <
  14022. std::is_same<NumberType, number_unsigned_t>::value ||
  14023. std::is_same<NumberType, number_integer_t>::value ||
  14024. std::is_same<NumberType, binary_char_t>::value,
  14025. int > = 0 >
  14026. void dump_integer(NumberType x)
  14027. {
  14028. static constexpr std::array<std::array<char, 2>, 100> digits_to_99
  14029. {
  14030. {
  14031. {{'0', '0'}}, {{'0', '1'}}, {{'0', '2'}}, {{'0', '3'}}, {{'0', '4'}}, {{'0', '5'}}, {{'0', '6'}}, {{'0', '7'}}, {{'0', '8'}}, {{'0', '9'}},
  14032. {{'1', '0'}}, {{'1', '1'}}, {{'1', '2'}}, {{'1', '3'}}, {{'1', '4'}}, {{'1', '5'}}, {{'1', '6'}}, {{'1', '7'}}, {{'1', '8'}}, {{'1', '9'}},
  14033. {{'2', '0'}}, {{'2', '1'}}, {{'2', '2'}}, {{'2', '3'}}, {{'2', '4'}}, {{'2', '5'}}, {{'2', '6'}}, {{'2', '7'}}, {{'2', '8'}}, {{'2', '9'}},
  14034. {{'3', '0'}}, {{'3', '1'}}, {{'3', '2'}}, {{'3', '3'}}, {{'3', '4'}}, {{'3', '5'}}, {{'3', '6'}}, {{'3', '7'}}, {{'3', '8'}}, {{'3', '9'}},
  14035. {{'4', '0'}}, {{'4', '1'}}, {{'4', '2'}}, {{'4', '3'}}, {{'4', '4'}}, {{'4', '5'}}, {{'4', '6'}}, {{'4', '7'}}, {{'4', '8'}}, {{'4', '9'}},
  14036. {{'5', '0'}}, {{'5', '1'}}, {{'5', '2'}}, {{'5', '3'}}, {{'5', '4'}}, {{'5', '5'}}, {{'5', '6'}}, {{'5', '7'}}, {{'5', '8'}}, {{'5', '9'}},
  14037. {{'6', '0'}}, {{'6', '1'}}, {{'6', '2'}}, {{'6', '3'}}, {{'6', '4'}}, {{'6', '5'}}, {{'6', '6'}}, {{'6', '7'}}, {{'6', '8'}}, {{'6', '9'}},
  14038. {{'7', '0'}}, {{'7', '1'}}, {{'7', '2'}}, {{'7', '3'}}, {{'7', '4'}}, {{'7', '5'}}, {{'7', '6'}}, {{'7', '7'}}, {{'7', '8'}}, {{'7', '9'}},
  14039. {{'8', '0'}}, {{'8', '1'}}, {{'8', '2'}}, {{'8', '3'}}, {{'8', '4'}}, {{'8', '5'}}, {{'8', '6'}}, {{'8', '7'}}, {{'8', '8'}}, {{'8', '9'}},
  14040. {{'9', '0'}}, {{'9', '1'}}, {{'9', '2'}}, {{'9', '3'}}, {{'9', '4'}}, {{'9', '5'}}, {{'9', '6'}}, {{'9', '7'}}, {{'9', '8'}}, {{'9', '9'}},
  14041. }
  14042. };
  14043. // special case for "0"
  14044. if (x == 0)
  14045. {
  14046. o->write_character('0');
  14047. return;
  14048. }
  14049. // use a pointer to fill the buffer
  14050. auto buffer_ptr = number_buffer.begin();
  14051. const bool is_negative = std::is_same<NumberType, number_integer_t>::value && !(x >= 0); // see issue #755
  14052. number_unsigned_t abs_value;
  14053. unsigned int n_chars;
  14054. if (is_negative)
  14055. {
  14056. *buffer_ptr = '-';
  14057. abs_value = remove_sign(static_cast<number_integer_t>(x));
  14058. // account one more byte for the minus sign
  14059. n_chars = 1 + count_digits(abs_value);
  14060. }
  14061. else
  14062. {
  14063. abs_value = static_cast<number_unsigned_t>(x);
  14064. n_chars = count_digits(abs_value);
  14065. }
  14066. // spare 1 byte for '\0'
  14067. JSON_ASSERT(n_chars < number_buffer.size() - 1);
  14068. // jump to the end to generate the string from backward
  14069. // so we later avoid reversing the result
  14070. buffer_ptr += n_chars;
  14071. // Fast int2ascii implementation inspired by "Fastware" talk by Andrei Alexandrescu
  14072. // See: https://www.youtube.com/watch?v=o4-CwDo2zpg
  14073. while (abs_value >= 100)
  14074. {
  14075. const auto digits_index = static_cast<unsigned>((abs_value % 100));
  14076. abs_value /= 100;
  14077. *(--buffer_ptr) = digits_to_99[digits_index][1];
  14078. *(--buffer_ptr) = digits_to_99[digits_index][0];
  14079. }
  14080. if (abs_value >= 10)
  14081. {
  14082. const auto digits_index = static_cast<unsigned>(abs_value);
  14083. *(--buffer_ptr) = digits_to_99[digits_index][1];
  14084. *(--buffer_ptr) = digits_to_99[digits_index][0];
  14085. }
  14086. else
  14087. {
  14088. *(--buffer_ptr) = static_cast<char>('0' + abs_value);
  14089. }
  14090. o->write_characters(number_buffer.data(), n_chars);
  14091. }
  14092. /*!
  14093. @brief dump a floating-point number
  14094. Dump a given floating-point number to output stream @a o. Works internally
  14095. with @a number_buffer.
  14096. @param[in] x floating-point number to dump
  14097. */
  14098. void dump_float(number_float_t x)
  14099. {
  14100. // NaN / inf
  14101. if (!std::isfinite(x))
  14102. {
  14103. o->write_characters("null", 4);
  14104. return;
  14105. }
  14106. // If number_float_t is an IEEE-754 single or double precision number,
  14107. // use the Grisu2 algorithm to produce short numbers which are
  14108. // guaranteed to round-trip, using strtof and strtod, resp.
  14109. //
  14110. // NB: The test below works if <long double> == <double>.
  14111. static constexpr bool is_ieee_single_or_double
  14112. = (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) ||
  14113. (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);
  14114. dump_float(x, std::integral_constant<bool, is_ieee_single_or_double>());
  14115. }
  14116. void dump_float(number_float_t x, std::true_type /*is_ieee_single_or_double*/)
  14117. {
  14118. char* begin = number_buffer.data();
  14119. char* end = ::nlohmann::detail::to_chars(begin, begin + number_buffer.size(), x);
  14120. o->write_characters(begin, static_cast<size_t>(end - begin));
  14121. }
  14122. void dump_float(number_float_t x, std::false_type /*is_ieee_single_or_double*/)
  14123. {
  14124. // get number of digits for a float -> text -> float round-trip
  14125. static constexpr auto d = std::numeric_limits<number_float_t>::max_digits10;
  14126. // the actual conversion
  14127. std::ptrdiff_t len = (std::snprintf)(number_buffer.data(), number_buffer.size(), "%.*g", d, x);
  14128. // negative value indicates an error
  14129. JSON_ASSERT(len > 0);
  14130. // check if buffer was large enough
  14131. JSON_ASSERT(static_cast<std::size_t>(len) < number_buffer.size());
  14132. // erase thousands separator
  14133. if (thousands_sep != '\0')
  14134. {
  14135. const auto end = std::remove(number_buffer.begin(),
  14136. number_buffer.begin() + len, thousands_sep);
  14137. std::fill(end, number_buffer.end(), '\0');
  14138. JSON_ASSERT((end - number_buffer.begin()) <= len);
  14139. len = (end - number_buffer.begin());
  14140. }
  14141. // convert decimal point to '.'
  14142. if (decimal_point != '\0' && decimal_point != '.')
  14143. {
  14144. const auto dec_pos = std::find(number_buffer.begin(), number_buffer.end(), decimal_point);
  14145. if (dec_pos != number_buffer.end())
  14146. {
  14147. *dec_pos = '.';
  14148. }
  14149. }
  14150. o->write_characters(number_buffer.data(), static_cast<std::size_t>(len));
  14151. // determine if need to append ".0"
  14152. const bool value_is_int_like =
  14153. std::none_of(number_buffer.begin(), number_buffer.begin() + len + 1,
  14154. [](char c)
  14155. {
  14156. return c == '.' || c == 'e';
  14157. });
  14158. if (value_is_int_like)
  14159. {
  14160. o->write_characters(".0", 2);
  14161. }
  14162. }
  14163. /*!
  14164. @brief check whether a string is UTF-8 encoded
  14165. The function checks each byte of a string whether it is UTF-8 encoded. The
  14166. result of the check is stored in the @a state parameter. The function must
  14167. be called initially with state 0 (accept). State 1 means the string must
  14168. be rejected, because the current byte is not allowed. If the string is
  14169. completely processed, but the state is non-zero, the string ended
  14170. prematurely; that is, the last byte indicated more bytes should have
  14171. followed.
  14172. @param[in,out] state the state of the decoding
  14173. @param[in,out] codep codepoint (valid only if resulting state is UTF8_ACCEPT)
  14174. @param[in] byte next byte to decode
  14175. @return new state
  14176. @note The function has been edited: a std::array is used.
  14177. @copyright Copyright (c) 2008-2009 Bjoern Hoehrmann <bjoern@hoehrmann.de>
  14178. @sa http://bjoern.hoehrmann.de/utf-8/decoder/dfa/
  14179. */
  14180. static std::uint8_t decode(std::uint8_t& state, std::uint32_t& codep, const std::uint8_t byte) noexcept
  14181. {
  14182. static const std::array<std::uint8_t, 400> utf8d =
  14183. {
  14184. {
  14185. 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
  14186. 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
  14187. 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
  14188. 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
  14189. 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
  14190. 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
  14191. 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
  14192. 0xA, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x4, 0x3, 0x3, // E0..EF
  14193. 0xB, 0x6, 0x6, 0x6, 0x5, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, // F0..FF
  14194. 0x0, 0x1, 0x2, 0x3, 0x5, 0x8, 0x7, 0x1, 0x1, 0x1, 0x4, 0x6, 0x1, 0x1, 0x1, 0x1, // s0..s0
  14195. 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
  14196. 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
  14197. 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
  14198. 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
  14199. }
  14200. };
  14201. const std::uint8_t type = utf8d[byte];
  14202. codep = (state != UTF8_ACCEPT)
  14203. ? (byte & 0x3fu) | (codep << 6u)
  14204. : (0xFFu >> type) & (byte);
  14205. std::size_t index = 256u + static_cast<size_t>(state) * 16u + static_cast<size_t>(type);
  14206. JSON_ASSERT(index < 400);
  14207. state = utf8d[index];
  14208. return state;
  14209. }
  14210. /*
  14211. * Overload to make the compiler happy while it is instantiating
  14212. * dump_integer for number_unsigned_t.
  14213. * Must never be called.
  14214. */
  14215. number_unsigned_t remove_sign(number_unsigned_t x)
  14216. {
  14217. JSON_ASSERT(false); // LCOV_EXCL_LINE
  14218. return x; // LCOV_EXCL_LINE
  14219. }
  14220. /*
  14221. * Helper function for dump_integer
  14222. *
  14223. * This function takes a negative signed integer and returns its absolute
  14224. * value as unsigned integer. The plus/minus shuffling is necessary as we can
  14225. * not directly remove the sign of an arbitrary signed integer as the
  14226. * absolute values of INT_MIN and INT_MAX are usually not the same. See
  14227. * #1708 for details.
  14228. */
  14229. inline number_unsigned_t remove_sign(number_integer_t x) noexcept
  14230. {
  14231. JSON_ASSERT(x < 0 && x < (std::numeric_limits<number_integer_t>::max)());
  14232. return static_cast<number_unsigned_t>(-(x + 1)) + 1;
  14233. }
  14234. private:
  14235. /// the output of the serializer
  14236. output_adapter_t<char> o = nullptr;
  14237. /// a (hopefully) large enough character buffer
  14238. std::array<char, 64> number_buffer{{}};
  14239. /// the locale
  14240. const std::lconv* loc = nullptr;
  14241. /// the locale's thousand separator character
  14242. const char thousands_sep = '\0';
  14243. /// the locale's decimal point character
  14244. const char decimal_point = '\0';
  14245. /// string buffer
  14246. std::array<char, 512> string_buffer{{}};
  14247. /// the indentation character
  14248. const char indent_char;
  14249. /// the indentation string
  14250. string_t indent_string;
  14251. /// error_handler how to react on decoding errors
  14252. const error_handler_t error_handler;
  14253. };
  14254. } // namespace detail
  14255. } // namespace nlohmann
  14256. // #include <nlohmann/detail/value_t.hpp>
  14257. // #include <nlohmann/json_fwd.hpp>
  14258. // #include <nlohmann/ordered_map.hpp>
  14259. #include <functional> // less
  14260. #include <memory> // allocator
  14261. #include <utility> // pair
  14262. #include <vector> // vector
  14263. namespace nlohmann
  14264. {
  14265. /// ordered_map: a minimal map-like container that preserves insertion order
  14266. /// for use within nlohmann::basic_json<ordered_map>
  14267. template <class Key, class T, class IgnoredLess = std::less<Key>,
  14268. class Allocator = std::allocator<std::pair<const Key, T>>>
  14269. struct ordered_map : std::vector<std::pair<const Key, T>, Allocator>
  14270. {
  14271. using key_type = Key;
  14272. using mapped_type = T;
  14273. using Container = std::vector<std::pair<const Key, T>, Allocator>;
  14274. using typename Container::iterator;
  14275. using typename Container::const_iterator;
  14276. using typename Container::size_type;
  14277. using typename Container::value_type;
  14278. // Explicit constructors instead of `using Container::Container`
  14279. // otherwise older compilers choke on it (GCC <= 5.5, xcode <= 9.4)
  14280. ordered_map(const Allocator& alloc = Allocator()) : Container{alloc} {}
  14281. template <class It>
  14282. ordered_map(It first, It last, const Allocator& alloc = Allocator())
  14283. : Container{first, last, alloc} {}
  14284. ordered_map(std::initializer_list<T> init, const Allocator& alloc = Allocator() )
  14285. : Container{init, alloc} {}
  14286. std::pair<iterator, bool> emplace(const key_type& key, T&& t)
  14287. {
  14288. for (auto it = this->begin(); it != this->end(); ++it)
  14289. {
  14290. if (it->first == key)
  14291. {
  14292. return {it, false};
  14293. }
  14294. }
  14295. Container::emplace_back(key, t);
  14296. return {--this->end(), true};
  14297. }
  14298. T& operator[](const Key& key)
  14299. {
  14300. return emplace(key, T{}).first->second;
  14301. }
  14302. const T& operator[](const Key& key) const
  14303. {
  14304. return at(key);
  14305. }
  14306. T& at(const Key& key)
  14307. {
  14308. for (auto it = this->begin(); it != this->end(); ++it)
  14309. {
  14310. if (it->first == key)
  14311. {
  14312. return it->second;
  14313. }
  14314. }
  14315. throw std::out_of_range("key not found");
  14316. }
  14317. const T& at(const Key& key) const
  14318. {
  14319. for (auto it = this->begin(); it != this->end(); ++it)
  14320. {
  14321. if (it->first == key)
  14322. {
  14323. return it->second;
  14324. }
  14325. }
  14326. throw std::out_of_range("key not found");
  14327. }
  14328. size_type erase(const Key& key)
  14329. {
  14330. for (auto it = this->begin(); it != this->end(); ++it)
  14331. {
  14332. if (it->first == key)
  14333. {
  14334. // Since we cannot move const Keys, re-construct them in place
  14335. for (auto next = it; ++next != this->end(); ++it)
  14336. {
  14337. it->~value_type(); // Destroy but keep allocation
  14338. new (&*it) value_type{std::move(*next)};
  14339. }
  14340. Container::pop_back();
  14341. return 1;
  14342. }
  14343. }
  14344. return 0;
  14345. }
  14346. iterator erase(iterator pos)
  14347. {
  14348. auto it = pos;
  14349. // Since we cannot move const Keys, re-construct them in place
  14350. for (auto next = it; ++next != this->end(); ++it)
  14351. {
  14352. it->~value_type(); // Destroy but keep allocation
  14353. new (&*it) value_type{std::move(*next)};
  14354. }
  14355. Container::pop_back();
  14356. return pos;
  14357. }
  14358. size_type count(const Key& key) const
  14359. {
  14360. for (auto it = this->begin(); it != this->end(); ++it)
  14361. {
  14362. if (it->first == key)
  14363. {
  14364. return 1;
  14365. }
  14366. }
  14367. return 0;
  14368. }
  14369. iterator find(const Key& key)
  14370. {
  14371. for (auto it = this->begin(); it != this->end(); ++it)
  14372. {
  14373. if (it->first == key)
  14374. {
  14375. return it;
  14376. }
  14377. }
  14378. return Container::end();
  14379. }
  14380. const_iterator find(const Key& key) const
  14381. {
  14382. for (auto it = this->begin(); it != this->end(); ++it)
  14383. {
  14384. if (it->first == key)
  14385. {
  14386. return it;
  14387. }
  14388. }
  14389. return Container::end();
  14390. }
  14391. std::pair<iterator, bool> insert( value_type&& value )
  14392. {
  14393. return emplace(value.first, std::move(value.second));
  14394. }
  14395. std::pair<iterator, bool> insert( const value_type& value )
  14396. {
  14397. for (auto it = this->begin(); it != this->end(); ++it)
  14398. {
  14399. if (it->first == value.first)
  14400. {
  14401. return {it, false};
  14402. }
  14403. }
  14404. Container::push_back(value);
  14405. return {--this->end(), true};
  14406. }
  14407. };
  14408. } // namespace nlohmann
  14409. /*!
  14410. @brief namespace for Niels Lohmann
  14411. @see https://github.com/nlohmann
  14412. @since version 1.0.0
  14413. */
  14414. namespace nlohmann
  14415. {
  14416. /*!
  14417. @brief a class to store JSON values
  14418. @tparam ObjectType type for JSON objects (`std::map` by default; will be used
  14419. in @ref object_t)
  14420. @tparam ArrayType type for JSON arrays (`std::vector` by default; will be used
  14421. in @ref array_t)
  14422. @tparam StringType type for JSON strings and object keys (`std::string` by
  14423. default; will be used in @ref string_t)
  14424. @tparam BooleanType type for JSON booleans (`bool` by default; will be used
  14425. in @ref boolean_t)
  14426. @tparam NumberIntegerType type for JSON integer numbers (`int64_t` by
  14427. default; will be used in @ref number_integer_t)
  14428. @tparam NumberUnsignedType type for JSON unsigned integer numbers (@c
  14429. `uint64_t` by default; will be used in @ref number_unsigned_t)
  14430. @tparam NumberFloatType type for JSON floating-point numbers (`double` by
  14431. default; will be used in @ref number_float_t)
  14432. @tparam BinaryType type for packed binary data for compatibility with binary
  14433. serialization formats (`std::vector<std::uint8_t>` by default; will be used in
  14434. @ref binary_t)
  14435. @tparam AllocatorType type of the allocator to use (`std::allocator` by
  14436. default)
  14437. @tparam JSONSerializer the serializer to resolve internal calls to `to_json()`
  14438. and `from_json()` (@ref adl_serializer by default)
  14439. @requirement The class satisfies the following concept requirements:
  14440. - Basic
  14441. - [DefaultConstructible](https://en.cppreference.com/w/cpp/named_req/DefaultConstructible):
  14442. JSON values can be default constructed. The result will be a JSON null
  14443. value.
  14444. - [MoveConstructible](https://en.cppreference.com/w/cpp/named_req/MoveConstructible):
  14445. A JSON value can be constructed from an rvalue argument.
  14446. - [CopyConstructible](https://en.cppreference.com/w/cpp/named_req/CopyConstructible):
  14447. A JSON value can be copy-constructed from an lvalue expression.
  14448. - [MoveAssignable](https://en.cppreference.com/w/cpp/named_req/MoveAssignable):
  14449. A JSON value van be assigned from an rvalue argument.
  14450. - [CopyAssignable](https://en.cppreference.com/w/cpp/named_req/CopyAssignable):
  14451. A JSON value can be copy-assigned from an lvalue expression.
  14452. - [Destructible](https://en.cppreference.com/w/cpp/named_req/Destructible):
  14453. JSON values can be destructed.
  14454. - Layout
  14455. - [StandardLayoutType](https://en.cppreference.com/w/cpp/named_req/StandardLayoutType):
  14456. JSON values have
  14457. [standard layout](https://en.cppreference.com/w/cpp/language/data_members#Standard_layout):
  14458. All non-static data members are private and standard layout types, the
  14459. class has no virtual functions or (virtual) base classes.
  14460. - Library-wide
  14461. - [EqualityComparable](https://en.cppreference.com/w/cpp/named_req/EqualityComparable):
  14462. JSON values can be compared with `==`, see @ref
  14463. operator==(const_reference,const_reference).
  14464. - [LessThanComparable](https://en.cppreference.com/w/cpp/named_req/LessThanComparable):
  14465. JSON values can be compared with `<`, see @ref
  14466. operator<(const_reference,const_reference).
  14467. - [Swappable](https://en.cppreference.com/w/cpp/named_req/Swappable):
  14468. Any JSON lvalue or rvalue of can be swapped with any lvalue or rvalue of
  14469. other compatible types, using unqualified function call @ref swap().
  14470. - [NullablePointer](https://en.cppreference.com/w/cpp/named_req/NullablePointer):
  14471. JSON values can be compared against `std::nullptr_t` objects which are used
  14472. to model the `null` value.
  14473. - Container
  14474. - [Container](https://en.cppreference.com/w/cpp/named_req/Container):
  14475. JSON values can be used like STL containers and provide iterator access.
  14476. - [ReversibleContainer](https://en.cppreference.com/w/cpp/named_req/ReversibleContainer);
  14477. JSON values can be used like STL containers and provide reverse iterator
  14478. access.
  14479. @invariant The member variables @a m_value and @a m_type have the following
  14480. relationship:
  14481. - If `m_type == value_t::object`, then `m_value.object != nullptr`.
  14482. - If `m_type == value_t::array`, then `m_value.array != nullptr`.
  14483. - If `m_type == value_t::string`, then `m_value.string != nullptr`.
  14484. The invariants are checked by member function assert_invariant().
  14485. @internal
  14486. @note ObjectType trick from https://stackoverflow.com/a/9860911
  14487. @endinternal
  14488. @see [RFC 7159: The JavaScript Object Notation (JSON) Data Interchange
  14489. Format](http://rfc7159.net/rfc7159)
  14490. @since version 1.0.0
  14491. @nosubgrouping
  14492. */
  14493. NLOHMANN_BASIC_JSON_TPL_DECLARATION
  14494. class basic_json
  14495. {
  14496. private:
  14497. template<detail::value_t> friend struct detail::external_constructor;
  14498. friend ::nlohmann::json_pointer<basic_json>;
  14499. template<typename BasicJsonType, typename InputType>
  14500. friend class ::nlohmann::detail::parser;
  14501. friend ::nlohmann::detail::serializer<basic_json>;
  14502. template<typename BasicJsonType>
  14503. friend class ::nlohmann::detail::iter_impl;
  14504. template<typename BasicJsonType, typename CharType>
  14505. friend class ::nlohmann::detail::binary_writer;
  14506. template<typename BasicJsonType, typename InputType, typename SAX>
  14507. friend class ::nlohmann::detail::binary_reader;
  14508. template<typename BasicJsonType>
  14509. friend class ::nlohmann::detail::json_sax_dom_parser;
  14510. template<typename BasicJsonType>
  14511. friend class ::nlohmann::detail::json_sax_dom_callback_parser;
  14512. /// workaround type for MSVC
  14513. using basic_json_t = NLOHMANN_BASIC_JSON_TPL;
  14514. // convenience aliases for types residing in namespace detail;
  14515. using lexer = ::nlohmann::detail::lexer_base<basic_json>;
  14516. template<typename InputAdapterType>
  14517. static ::nlohmann::detail::parser<basic_json, InputAdapterType> parser(
  14518. InputAdapterType adapter,
  14519. detail::parser_callback_t<basic_json>cb = nullptr,
  14520. const bool allow_exceptions = true,
  14521. const bool ignore_comments = false
  14522. )
  14523. {
  14524. return ::nlohmann::detail::parser<basic_json, InputAdapterType>(std::move(adapter),
  14525. std::move(cb), allow_exceptions, ignore_comments);
  14526. }
  14527. using primitive_iterator_t = ::nlohmann::detail::primitive_iterator_t;
  14528. template<typename BasicJsonType>
  14529. using internal_iterator = ::nlohmann::detail::internal_iterator<BasicJsonType>;
  14530. template<typename BasicJsonType>
  14531. using iter_impl = ::nlohmann::detail::iter_impl<BasicJsonType>;
  14532. template<typename Iterator>
  14533. using iteration_proxy = ::nlohmann::detail::iteration_proxy<Iterator>;
  14534. template<typename Base> using json_reverse_iterator = ::nlohmann::detail::json_reverse_iterator<Base>;
  14535. template<typename CharType>
  14536. using output_adapter_t = ::nlohmann::detail::output_adapter_t<CharType>;
  14537. template<typename InputType>
  14538. using binary_reader = ::nlohmann::detail::binary_reader<basic_json, InputType>;
  14539. template<typename CharType> using binary_writer = ::nlohmann::detail::binary_writer<basic_json, CharType>;
  14540. using serializer = ::nlohmann::detail::serializer<basic_json>;
  14541. public:
  14542. using value_t = detail::value_t;
  14543. /// JSON Pointer, see @ref nlohmann::json_pointer
  14544. using json_pointer = ::nlohmann::json_pointer<basic_json>;
  14545. template<typename T, typename SFINAE>
  14546. using json_serializer = JSONSerializer<T, SFINAE>;
  14547. /// how to treat decoding errors
  14548. using error_handler_t = detail::error_handler_t;
  14549. /// how to treat CBOR tags
  14550. using cbor_tag_handler_t = detail::cbor_tag_handler_t;
  14551. /// helper type for initializer lists of basic_json values
  14552. using initializer_list_t = std::initializer_list<detail::json_ref<basic_json>>;
  14553. using input_format_t = detail::input_format_t;
  14554. /// SAX interface type, see @ref nlohmann::json_sax
  14555. using json_sax_t = json_sax<basic_json>;
  14556. ////////////////
  14557. // exceptions //
  14558. ////////////////
  14559. /// @name exceptions
  14560. /// Classes to implement user-defined exceptions.
  14561. /// @{
  14562. /// @copydoc detail::exception
  14563. using exception = detail::exception;
  14564. /// @copydoc detail::parse_error
  14565. using parse_error = detail::parse_error;
  14566. /// @copydoc detail::invalid_iterator
  14567. using invalid_iterator = detail::invalid_iterator;
  14568. /// @copydoc detail::type_error
  14569. using type_error = detail::type_error;
  14570. /// @copydoc detail::out_of_range
  14571. using out_of_range = detail::out_of_range;
  14572. /// @copydoc detail::other_error
  14573. using other_error = detail::other_error;
  14574. /// @}
  14575. /////////////////////
  14576. // container types //
  14577. /////////////////////
  14578. /// @name container types
  14579. /// The canonic container types to use @ref basic_json like any other STL
  14580. /// container.
  14581. /// @{
  14582. /// the type of elements in a basic_json container
  14583. using value_type = basic_json;
  14584. /// the type of an element reference
  14585. using reference = value_type&;
  14586. /// the type of an element const reference
  14587. using const_reference = const value_type&;
  14588. /// a type to represent differences between iterators
  14589. using difference_type = std::ptrdiff_t;
  14590. /// a type to represent container sizes
  14591. using size_type = std::size_t;
  14592. /// the allocator type
  14593. using allocator_type = AllocatorType<basic_json>;
  14594. /// the type of an element pointer
  14595. using pointer = typename std::allocator_traits<allocator_type>::pointer;
  14596. /// the type of an element const pointer
  14597. using const_pointer = typename std::allocator_traits<allocator_type>::const_pointer;
  14598. /// an iterator for a basic_json container
  14599. using iterator = iter_impl<basic_json>;
  14600. /// a const iterator for a basic_json container
  14601. using const_iterator = iter_impl<const basic_json>;
  14602. /// a reverse iterator for a basic_json container
  14603. using reverse_iterator = json_reverse_iterator<typename basic_json::iterator>;
  14604. /// a const reverse iterator for a basic_json container
  14605. using const_reverse_iterator = json_reverse_iterator<typename basic_json::const_iterator>;
  14606. /// @}
  14607. /*!
  14608. @brief returns the allocator associated with the container
  14609. */
  14610. static allocator_type get_allocator()
  14611. {
  14612. return allocator_type();
  14613. }
  14614. /*!
  14615. @brief returns version information on the library
  14616. This function returns a JSON object with information about the library,
  14617. including the version number and information on the platform and compiler.
  14618. @return JSON object holding version information
  14619. key | description
  14620. ----------- | ---------------
  14621. `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).
  14622. `copyright` | The copyright line for the library as string.
  14623. `name` | The name of the library as string.
  14624. `platform` | The used platform as string. Possible values are `win32`, `linux`, `apple`, `unix`, and `unknown`.
  14625. `url` | The URL of the project as string.
  14626. `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).
  14627. @liveexample{The following code shows an example output of the `meta()`
  14628. function.,meta}
  14629. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  14630. changes to any JSON value.
  14631. @complexity Constant.
  14632. @since 2.1.0
  14633. */
  14634. JSON_HEDLEY_WARN_UNUSED_RESULT
  14635. static basic_json meta()
  14636. {
  14637. basic_json result;
  14638. result["copyright"] = "(C) 2013-2020 Niels Lohmann";
  14639. result["name"] = "JSON for Modern C++";
  14640. result["url"] = "https://github.com/nlohmann/json";
  14641. result["version"]["string"] =
  14642. std::to_string(NLOHMANN_JSON_VERSION_MAJOR) + "." +
  14643. std::to_string(NLOHMANN_JSON_VERSION_MINOR) + "." +
  14644. std::to_string(NLOHMANN_JSON_VERSION_PATCH);
  14645. result["version"]["major"] = NLOHMANN_JSON_VERSION_MAJOR;
  14646. result["version"]["minor"] = NLOHMANN_JSON_VERSION_MINOR;
  14647. result["version"]["patch"] = NLOHMANN_JSON_VERSION_PATCH;
  14648. #ifdef _WIN32
  14649. result["platform"] = "win32";
  14650. #elif defined __linux__
  14651. result["platform"] = "linux";
  14652. #elif defined __APPLE__
  14653. result["platform"] = "apple";
  14654. #elif defined __unix__
  14655. result["platform"] = "unix";
  14656. #else
  14657. result["platform"] = "unknown";
  14658. #endif
  14659. #if defined(__ICC) || defined(__INTEL_COMPILER)
  14660. result["compiler"] = {{"family", "icc"}, {"version", __INTEL_COMPILER}};
  14661. #elif defined(__clang__)
  14662. result["compiler"] = {{"family", "clang"}, {"version", __clang_version__}};
  14663. #elif defined(__GNUC__) || defined(__GNUG__)
  14664. result["compiler"] = {{"family", "gcc"}, {"version", std::to_string(__GNUC__) + "." + std::to_string(__GNUC_MINOR__) + "." + std::to_string(__GNUC_PATCHLEVEL__)}};
  14665. #elif defined(__HP_cc) || defined(__HP_aCC)
  14666. result["compiler"] = "hp"
  14667. #elif defined(__IBMCPP__)
  14668. result["compiler"] = {{"family", "ilecpp"}, {"version", __IBMCPP__}};
  14669. #elif defined(_MSC_VER)
  14670. result["compiler"] = {{"family", "msvc"}, {"version", _MSC_VER}};
  14671. #elif defined(__PGI)
  14672. result["compiler"] = {{"family", "pgcpp"}, {"version", __PGI}};
  14673. #elif defined(__SUNPRO_CC)
  14674. result["compiler"] = {{"family", "sunpro"}, {"version", __SUNPRO_CC}};
  14675. #else
  14676. result["compiler"] = {{"family", "unknown"}, {"version", "unknown"}};
  14677. #endif
  14678. #ifdef __cplusplus
  14679. result["compiler"]["c++"] = std::to_string(__cplusplus);
  14680. #else
  14681. result["compiler"]["c++"] = "unknown";
  14682. #endif
  14683. return result;
  14684. }
  14685. ///////////////////////////
  14686. // JSON value data types //
  14687. ///////////////////////////
  14688. /// @name JSON value data types
  14689. /// The data types to store a JSON value. These types are derived from
  14690. /// the template arguments passed to class @ref basic_json.
  14691. /// @{
  14692. #if defined(JSON_HAS_CPP_14)
  14693. // Use transparent comparator if possible, combined with perfect forwarding
  14694. // on find() and count() calls prevents unnecessary string construction.
  14695. using object_comparator_t = std::less<>;
  14696. #else
  14697. using object_comparator_t = std::less<StringType>;
  14698. #endif
  14699. /*!
  14700. @brief a type for an object
  14701. [RFC 7159](http://rfc7159.net/rfc7159) describes JSON objects as follows:
  14702. > An object is an unordered collection of zero or more name/value pairs,
  14703. > where a name is a string and a value is a string, number, boolean, null,
  14704. > object, or array.
  14705. To store objects in C++, a type is defined by the template parameters
  14706. described below.
  14707. @tparam ObjectType the container to store objects (e.g., `std::map` or
  14708. `std::unordered_map`)
  14709. @tparam StringType the type of the keys or names (e.g., `std::string`).
  14710. The comparison function `std::less<StringType>` is used to order elements
  14711. inside the container.
  14712. @tparam AllocatorType the allocator to use for objects (e.g.,
  14713. `std::allocator`)
  14714. #### Default type
  14715. With the default values for @a ObjectType (`std::map`), @a StringType
  14716. (`std::string`), and @a AllocatorType (`std::allocator`), the default
  14717. value for @a object_t is:
  14718. @code {.cpp}
  14719. std::map<
  14720. std::string, // key_type
  14721. basic_json, // value_type
  14722. std::less<std::string>, // key_compare
  14723. std::allocator<std::pair<const std::string, basic_json>> // allocator_type
  14724. >
  14725. @endcode
  14726. #### Behavior
  14727. The choice of @a object_t influences the behavior of the JSON class. With
  14728. the default type, objects have the following behavior:
  14729. - When all names are unique, objects will be interoperable in the sense
  14730. that all software implementations receiving that object will agree on
  14731. the name-value mappings.
  14732. - When the names within an object are not unique, it is unspecified which
  14733. one of the values for a given key will be chosen. For instance,
  14734. `{"key": 2, "key": 1}` could be equal to either `{"key": 1}` or
  14735. `{"key": 2}`.
  14736. - Internally, name/value pairs are stored in lexicographical order of the
  14737. names. Objects will also be serialized (see @ref dump) in this order.
  14738. For instance, `{"b": 1, "a": 2}` and `{"a": 2, "b": 1}` will be stored
  14739. and serialized as `{"a": 2, "b": 1}`.
  14740. - When comparing objects, the order of the name/value pairs is irrelevant.
  14741. This makes objects interoperable in the sense that they will not be
  14742. affected by these differences. For instance, `{"b": 1, "a": 2}` and
  14743. `{"a": 2, "b": 1}` will be treated as equal.
  14744. #### Limits
  14745. [RFC 7159](http://rfc7159.net/rfc7159) specifies:
  14746. > An implementation may set limits on the maximum depth of nesting.
  14747. In this class, the object's limit of nesting is not explicitly constrained.
  14748. However, a maximum depth of nesting may be introduced by the compiler or
  14749. runtime environment. A theoretical limit can be queried by calling the
  14750. @ref max_size function of a JSON object.
  14751. #### Storage
  14752. Objects are stored as pointers in a @ref basic_json type. That is, for any
  14753. access to object values, a pointer of type `object_t*` must be
  14754. dereferenced.
  14755. @sa @ref array_t -- type for an array value
  14756. @since version 1.0.0
  14757. @note The order name/value pairs are added to the object is *not*
  14758. preserved by the library. Therefore, iterating an object may return
  14759. name/value pairs in a different order than they were originally stored. In
  14760. fact, keys will be traversed in alphabetical order as `std::map` with
  14761. `std::less` is used by default. Please note this behavior conforms to [RFC
  14762. 7159](http://rfc7159.net/rfc7159), because any order implements the
  14763. specified "unordered" nature of JSON objects.
  14764. */
  14765. using object_t = ObjectType<StringType,
  14766. basic_json,
  14767. object_comparator_t,
  14768. AllocatorType<std::pair<const StringType,
  14769. basic_json>>>;
  14770. /*!
  14771. @brief a type for an array
  14772. [RFC 7159](http://rfc7159.net/rfc7159) describes JSON arrays as follows:
  14773. > An array is an ordered sequence of zero or more values.
  14774. To store objects in C++, a type is defined by the template parameters
  14775. explained below.
  14776. @tparam ArrayType container type to store arrays (e.g., `std::vector` or
  14777. `std::list`)
  14778. @tparam AllocatorType allocator to use for arrays (e.g., `std::allocator`)
  14779. #### Default type
  14780. With the default values for @a ArrayType (`std::vector`) and @a
  14781. AllocatorType (`std::allocator`), the default value for @a array_t is:
  14782. @code {.cpp}
  14783. std::vector<
  14784. basic_json, // value_type
  14785. std::allocator<basic_json> // allocator_type
  14786. >
  14787. @endcode
  14788. #### Limits
  14789. [RFC 7159](http://rfc7159.net/rfc7159) specifies:
  14790. > An implementation may set limits on the maximum depth of nesting.
  14791. In this class, the array's limit of nesting is not explicitly constrained.
  14792. However, a maximum depth of nesting may be introduced by the compiler or
  14793. runtime environment. A theoretical limit can be queried by calling the
  14794. @ref max_size function of a JSON array.
  14795. #### Storage
  14796. Arrays are stored as pointers in a @ref basic_json type. That is, for any
  14797. access to array values, a pointer of type `array_t*` must be dereferenced.
  14798. @sa @ref object_t -- type for an object value
  14799. @since version 1.0.0
  14800. */
  14801. using array_t = ArrayType<basic_json, AllocatorType<basic_json>>;
  14802. /*!
  14803. @brief a type for a string
  14804. [RFC 7159](http://rfc7159.net/rfc7159) describes JSON strings as follows:
  14805. > A string is a sequence of zero or more Unicode characters.
  14806. To store objects in C++, a type is defined by the template parameter
  14807. described below. Unicode values are split by the JSON class into
  14808. byte-sized characters during deserialization.
  14809. @tparam StringType the container to store strings (e.g., `std::string`).
  14810. Note this container is used for keys/names in objects, see @ref object_t.
  14811. #### Default type
  14812. With the default values for @a StringType (`std::string`), the default
  14813. value for @a string_t is:
  14814. @code {.cpp}
  14815. std::string
  14816. @endcode
  14817. #### Encoding
  14818. Strings are stored in UTF-8 encoding. Therefore, functions like
  14819. `std::string::size()` or `std::string::length()` return the number of
  14820. bytes in the string rather than the number of characters or glyphs.
  14821. #### String comparison
  14822. [RFC 7159](http://rfc7159.net/rfc7159) states:
  14823. > Software implementations are typically required to test names of object
  14824. > members for equality. Implementations that transform the textual
  14825. > representation into sequences of Unicode code units and then perform the
  14826. > comparison numerically, code unit by code unit, are interoperable in the
  14827. > sense that implementations will agree in all cases on equality or
  14828. > inequality of two strings. For example, implementations that compare
  14829. > strings with escaped characters unconverted may incorrectly find that
  14830. > `"a\\b"` and `"a\u005Cb"` are not equal.
  14831. This implementation is interoperable as it does compare strings code unit
  14832. by code unit.
  14833. #### Storage
  14834. String values are stored as pointers in a @ref basic_json type. That is,
  14835. for any access to string values, a pointer of type `string_t*` must be
  14836. dereferenced.
  14837. @since version 1.0.0
  14838. */
  14839. using string_t = StringType;
  14840. /*!
  14841. @brief a type for a boolean
  14842. [RFC 7159](http://rfc7159.net/rfc7159) implicitly describes a boolean as a
  14843. type which differentiates the two literals `true` and `false`.
  14844. To store objects in C++, a type is defined by the template parameter @a
  14845. BooleanType which chooses the type to use.
  14846. #### Default type
  14847. With the default values for @a BooleanType (`bool`), the default value for
  14848. @a boolean_t is:
  14849. @code {.cpp}
  14850. bool
  14851. @endcode
  14852. #### Storage
  14853. Boolean values are stored directly inside a @ref basic_json type.
  14854. @since version 1.0.0
  14855. */
  14856. using boolean_t = BooleanType;
  14857. /*!
  14858. @brief a type for a number (integer)
  14859. [RFC 7159](http://rfc7159.net/rfc7159) describes numbers as follows:
  14860. > The representation of numbers is similar to that used in most
  14861. > programming languages. A number is represented in base 10 using decimal
  14862. > digits. It contains an integer component that may be prefixed with an
  14863. > optional minus sign, which may be followed by a fraction part and/or an
  14864. > exponent part. Leading zeros are not allowed. (...) Numeric values that
  14865. > cannot be represented in the grammar below (such as Infinity and NaN)
  14866. > are not permitted.
  14867. This description includes both integer and floating-point numbers.
  14868. However, C++ allows more precise storage if it is known whether the number
  14869. is a signed integer, an unsigned integer or a floating-point number.
  14870. Therefore, three different types, @ref number_integer_t, @ref
  14871. number_unsigned_t and @ref number_float_t are used.
  14872. To store integer numbers in C++, a type is defined by the template
  14873. parameter @a NumberIntegerType which chooses the type to use.
  14874. #### Default type
  14875. With the default values for @a NumberIntegerType (`int64_t`), the default
  14876. value for @a number_integer_t is:
  14877. @code {.cpp}
  14878. int64_t
  14879. @endcode
  14880. #### Default behavior
  14881. - The restrictions about leading zeros is not enforced in C++. Instead,
  14882. leading zeros in integer literals lead to an interpretation as octal
  14883. number. Internally, the value will be stored as decimal number. For
  14884. instance, the C++ integer literal `010` will be serialized to `8`.
  14885. During deserialization, leading zeros yield an error.
  14886. - Not-a-number (NaN) values will be serialized to `null`.
  14887. #### Limits
  14888. [RFC 7159](http://rfc7159.net/rfc7159) specifies:
  14889. > An implementation may set limits on the range and precision of numbers.
  14890. When the default type is used, the maximal integer number that can be
  14891. stored is `9223372036854775807` (INT64_MAX) and the minimal integer number
  14892. that can be stored is `-9223372036854775808` (INT64_MIN). Integer numbers
  14893. that are out of range will yield over/underflow when used in a
  14894. constructor. During deserialization, too large or small integer numbers
  14895. will be automatically be stored as @ref number_unsigned_t or @ref
  14896. number_float_t.
  14897. [RFC 7159](http://rfc7159.net/rfc7159) further states:
  14898. > Note that when such software is used, numbers that are integers and are
  14899. > in the range \f$[-2^{53}+1, 2^{53}-1]\f$ are interoperable in the sense
  14900. > that implementations will agree exactly on their numeric values.
  14901. As this range is a subrange of the exactly supported range [INT64_MIN,
  14902. INT64_MAX], this class's integer type is interoperable.
  14903. #### Storage
  14904. Integer number values are stored directly inside a @ref basic_json type.
  14905. @sa @ref number_float_t -- type for number values (floating-point)
  14906. @sa @ref number_unsigned_t -- type for number values (unsigned integer)
  14907. @since version 1.0.0
  14908. */
  14909. using number_integer_t = NumberIntegerType;
  14910. /*!
  14911. @brief a type for a number (unsigned)
  14912. [RFC 7159](http://rfc7159.net/rfc7159) describes numbers as follows:
  14913. > The representation of numbers is similar to that used in most
  14914. > programming languages. A number is represented in base 10 using decimal
  14915. > digits. It contains an integer component that may be prefixed with an
  14916. > optional minus sign, which may be followed by a fraction part and/or an
  14917. > exponent part. Leading zeros are not allowed. (...) Numeric values that
  14918. > cannot be represented in the grammar below (such as Infinity and NaN)
  14919. > are not permitted.
  14920. This description includes both integer and floating-point numbers.
  14921. However, C++ allows more precise storage if it is known whether the number
  14922. is a signed integer, an unsigned integer or a floating-point number.
  14923. Therefore, three different types, @ref number_integer_t, @ref
  14924. number_unsigned_t and @ref number_float_t are used.
  14925. To store unsigned integer numbers in C++, a type is defined by the
  14926. template parameter @a NumberUnsignedType which chooses the type to use.
  14927. #### Default type
  14928. With the default values for @a NumberUnsignedType (`uint64_t`), the
  14929. default value for @a number_unsigned_t is:
  14930. @code {.cpp}
  14931. uint64_t
  14932. @endcode
  14933. #### Default behavior
  14934. - The restrictions about leading zeros is not enforced in C++. Instead,
  14935. leading zeros in integer literals lead to an interpretation as octal
  14936. number. Internally, the value will be stored as decimal number. For
  14937. instance, the C++ integer literal `010` will be serialized to `8`.
  14938. During deserialization, leading zeros yield an error.
  14939. - Not-a-number (NaN) values will be serialized to `null`.
  14940. #### Limits
  14941. [RFC 7159](http://rfc7159.net/rfc7159) specifies:
  14942. > An implementation may set limits on the range and precision of numbers.
  14943. When the default type is used, the maximal integer number that can be
  14944. stored is `18446744073709551615` (UINT64_MAX) and the minimal integer
  14945. number that can be stored is `0`. Integer numbers that are out of range
  14946. will yield over/underflow when used in a constructor. During
  14947. deserialization, too large or small integer numbers will be automatically
  14948. be stored as @ref number_integer_t or @ref number_float_t.
  14949. [RFC 7159](http://rfc7159.net/rfc7159) further states:
  14950. > Note that when such software is used, numbers that are integers and are
  14951. > in the range \f$[-2^{53}+1, 2^{53}-1]\f$ are interoperable in the sense
  14952. > that implementations will agree exactly on their numeric values.
  14953. As this range is a subrange (when considered in conjunction with the
  14954. number_integer_t type) of the exactly supported range [0, UINT64_MAX],
  14955. this class's integer type is interoperable.
  14956. #### Storage
  14957. Integer number values are stored directly inside a @ref basic_json type.
  14958. @sa @ref number_float_t -- type for number values (floating-point)
  14959. @sa @ref number_integer_t -- type for number values (integer)
  14960. @since version 2.0.0
  14961. */
  14962. using number_unsigned_t = NumberUnsignedType;
  14963. /*!
  14964. @brief a type for a number (floating-point)
  14965. [RFC 7159](http://rfc7159.net/rfc7159) describes numbers as follows:
  14966. > The representation of numbers is similar to that used in most
  14967. > programming languages. A number is represented in base 10 using decimal
  14968. > digits. It contains an integer component that may be prefixed with an
  14969. > optional minus sign, which may be followed by a fraction part and/or an
  14970. > exponent part. Leading zeros are not allowed. (...) Numeric values that
  14971. > cannot be represented in the grammar below (such as Infinity and NaN)
  14972. > are not permitted.
  14973. This description includes both integer and floating-point numbers.
  14974. However, C++ allows more precise storage if it is known whether the number
  14975. is a signed integer, an unsigned integer or a floating-point number.
  14976. Therefore, three different types, @ref number_integer_t, @ref
  14977. number_unsigned_t and @ref number_float_t are used.
  14978. To store floating-point numbers in C++, a type is defined by the template
  14979. parameter @a NumberFloatType which chooses the type to use.
  14980. #### Default type
  14981. With the default values for @a NumberFloatType (`double`), the default
  14982. value for @a number_float_t is:
  14983. @code {.cpp}
  14984. double
  14985. @endcode
  14986. #### Default behavior
  14987. - The restrictions about leading zeros is not enforced in C++. Instead,
  14988. leading zeros in floating-point literals will be ignored. Internally,
  14989. the value will be stored as decimal number. For instance, the C++
  14990. floating-point literal `01.2` will be serialized to `1.2`. During
  14991. deserialization, leading zeros yield an error.
  14992. - Not-a-number (NaN) values will be serialized to `null`.
  14993. #### Limits
  14994. [RFC 7159](http://rfc7159.net/rfc7159) states:
  14995. > This specification allows implementations to set limits on the range and
  14996. > precision of numbers accepted. Since software that implements IEEE
  14997. > 754-2008 binary64 (double precision) numbers is generally available and
  14998. > widely used, good interoperability can be achieved by implementations
  14999. > that expect no more precision or range than these provide, in the sense
  15000. > that implementations will approximate JSON numbers within the expected
  15001. > precision.
  15002. This implementation does exactly follow this approach, as it uses double
  15003. precision floating-point numbers. Note values smaller than
  15004. `-1.79769313486232e+308` and values greater than `1.79769313486232e+308`
  15005. will be stored as NaN internally and be serialized to `null`.
  15006. #### Storage
  15007. Floating-point number values are stored directly inside a @ref basic_json
  15008. type.
  15009. @sa @ref number_integer_t -- type for number values (integer)
  15010. @sa @ref number_unsigned_t -- type for number values (unsigned integer)
  15011. @since version 1.0.0
  15012. */
  15013. using number_float_t = NumberFloatType;
  15014. /*!
  15015. @brief a type for a packed binary type
  15016. This type is a type designed to carry binary data that appears in various
  15017. serialized formats, such as CBOR's Major Type 2, MessagePack's bin, and
  15018. BSON's generic binary subtype. This type is NOT a part of standard JSON and
  15019. exists solely for compatibility with these binary types. As such, it is
  15020. simply defined as an ordered sequence of zero or more byte values.
  15021. Additionally, as an implementation detail, the subtype of the binary data is
  15022. carried around as a `std::uint8_t`, which is compatible with both of the
  15023. binary data formats that use binary subtyping, (though the specific
  15024. numbering is incompatible with each other, and it is up to the user to
  15025. translate between them).
  15026. [CBOR's RFC 7049](https://tools.ietf.org/html/rfc7049) describes this type
  15027. as:
  15028. > Major type 2: a byte string. The string's length in bytes is represented
  15029. > following the rules for positive integers (major type 0).
  15030. [MessagePack's documentation on the bin type
  15031. family](https://github.com/msgpack/msgpack/blob/master/spec.md#bin-format-family)
  15032. describes this type as:
  15033. > Bin format family stores an byte array in 2, 3, or 5 bytes of extra bytes
  15034. > in addition to the size of the byte array.
  15035. [BSON's specifications](http://bsonspec.org/spec.html) describe several
  15036. binary types; however, this type is intended to represent the generic binary
  15037. type which has the description:
  15038. > Generic binary subtype - This is the most commonly used binary subtype and
  15039. > should be the 'default' for drivers and tools.
  15040. None of these impose any limitations on the internal representation other
  15041. than the basic unit of storage be some type of array whose parts are
  15042. decomposable into bytes.
  15043. The default representation of this binary format is a
  15044. `std::vector<std::uint8_t>`, which is a very common way to represent a byte
  15045. array in modern C++.
  15046. #### Default type
  15047. The default values for @a BinaryType is `std::vector<std::uint8_t>`
  15048. #### Storage
  15049. Binary Arrays are stored as pointers in a @ref basic_json type. That is,
  15050. for any access to array values, a pointer of the type `binary_t*` must be
  15051. dereferenced.
  15052. #### Notes on subtypes
  15053. - CBOR
  15054. - Binary values are represented as byte strings. No subtypes are
  15055. supported and will be ignored when CBOR is written.
  15056. - MessagePack
  15057. - If a subtype is given and the binary array contains exactly 1, 2, 4, 8,
  15058. or 16 elements, the fixext family (fixext1, fixext2, fixext4, fixext8)
  15059. is used. For other sizes, the ext family (ext8, ext16, ext32) is used.
  15060. The subtype is then added as singed 8-bit integer.
  15061. - If no subtype is given, the bin family (bin8, bin16, bin32) is used.
  15062. - BSON
  15063. - If a subtype is given, it is used and added as unsigned 8-bit integer.
  15064. - If no subtype is given, the generic binary subtype 0x00 is used.
  15065. @sa @ref binary -- create a binary array
  15066. @since version 3.8.0
  15067. */
  15068. using binary_t = nlohmann::byte_container_with_subtype<BinaryType>;
  15069. /// @}
  15070. private:
  15071. /// helper for exception-safe object creation
  15072. template<typename T, typename... Args>
  15073. JSON_HEDLEY_RETURNS_NON_NULL
  15074. static T* create(Args&& ... args)
  15075. {
  15076. AllocatorType<T> alloc;
  15077. using AllocatorTraits = std::allocator_traits<AllocatorType<T>>;
  15078. auto deleter = [&](T * object)
  15079. {
  15080. AllocatorTraits::deallocate(alloc, object, 1);
  15081. };
  15082. std::unique_ptr<T, decltype(deleter)> object(AllocatorTraits::allocate(alloc, 1), deleter);
  15083. AllocatorTraits::construct(alloc, object.get(), std::forward<Args>(args)...);
  15084. JSON_ASSERT(object != nullptr);
  15085. return object.release();
  15086. }
  15087. ////////////////////////
  15088. // JSON value storage //
  15089. ////////////////////////
  15090. /*!
  15091. @brief a JSON value
  15092. The actual storage for a JSON value of the @ref basic_json class. This
  15093. union combines the different storage types for the JSON value types
  15094. defined in @ref value_t.
  15095. JSON type | value_t type | used type
  15096. --------- | --------------- | ------------------------
  15097. object | object | pointer to @ref object_t
  15098. array | array | pointer to @ref array_t
  15099. string | string | pointer to @ref string_t
  15100. boolean | boolean | @ref boolean_t
  15101. number | number_integer | @ref number_integer_t
  15102. number | number_unsigned | @ref number_unsigned_t
  15103. number | number_float | @ref number_float_t
  15104. binary | binary | pointer to @ref binary_t
  15105. null | null | *no value is stored*
  15106. @note Variable-length types (objects, arrays, and strings) are stored as
  15107. pointers. The size of the union should not exceed 64 bits if the default
  15108. value types are used.
  15109. @since version 1.0.0
  15110. */
  15111. union json_value
  15112. {
  15113. /// object (stored with pointer to save storage)
  15114. object_t* object;
  15115. /// array (stored with pointer to save storage)
  15116. array_t* array;
  15117. /// string (stored with pointer to save storage)
  15118. string_t* string;
  15119. /// binary (stored with pointer to save storage)
  15120. binary_t* binary;
  15121. /// boolean
  15122. boolean_t boolean;
  15123. /// number (integer)
  15124. number_integer_t number_integer;
  15125. /// number (unsigned integer)
  15126. number_unsigned_t number_unsigned;
  15127. /// number (floating-point)
  15128. number_float_t number_float;
  15129. /// default constructor (for null values)
  15130. json_value() = default;
  15131. /// constructor for booleans
  15132. json_value(boolean_t v) noexcept : boolean(v) {}
  15133. /// constructor for numbers (integer)
  15134. json_value(number_integer_t v) noexcept : number_integer(v) {}
  15135. /// constructor for numbers (unsigned)
  15136. json_value(number_unsigned_t v) noexcept : number_unsigned(v) {}
  15137. /// constructor for numbers (floating-point)
  15138. json_value(number_float_t v) noexcept : number_float(v) {}
  15139. /// constructor for empty values of a given type
  15140. json_value(value_t t)
  15141. {
  15142. switch (t)
  15143. {
  15144. case value_t::object:
  15145. {
  15146. object = create<object_t>();
  15147. break;
  15148. }
  15149. case value_t::array:
  15150. {
  15151. array = create<array_t>();
  15152. break;
  15153. }
  15154. case value_t::string:
  15155. {
  15156. string = create<string_t>("");
  15157. break;
  15158. }
  15159. case value_t::binary:
  15160. {
  15161. binary = create<binary_t>();
  15162. break;
  15163. }
  15164. case value_t::boolean:
  15165. {
  15166. boolean = boolean_t(false);
  15167. break;
  15168. }
  15169. case value_t::number_integer:
  15170. {
  15171. number_integer = number_integer_t(0);
  15172. break;
  15173. }
  15174. case value_t::number_unsigned:
  15175. {
  15176. number_unsigned = number_unsigned_t(0);
  15177. break;
  15178. }
  15179. case value_t::number_float:
  15180. {
  15181. number_float = number_float_t(0.0);
  15182. break;
  15183. }
  15184. case value_t::null:
  15185. {
  15186. object = nullptr; // silence warning, see #821
  15187. break;
  15188. }
  15189. default:
  15190. {
  15191. object = nullptr; // silence warning, see #821
  15192. if (JSON_HEDLEY_UNLIKELY(t == value_t::null))
  15193. {
  15194. JSON_THROW(other_error::create(500, "961c151d2e87f2686a955a9be24d316f1362bf21 3.9.1")); // LCOV_EXCL_LINE
  15195. }
  15196. break;
  15197. }
  15198. }
  15199. }
  15200. /// constructor for strings
  15201. json_value(const string_t& value)
  15202. {
  15203. string = create<string_t>(value);
  15204. }
  15205. /// constructor for rvalue strings
  15206. json_value(string_t&& value)
  15207. {
  15208. string = create<string_t>(std::move(value));
  15209. }
  15210. /// constructor for objects
  15211. json_value(const object_t& value)
  15212. {
  15213. object = create<object_t>(value);
  15214. }
  15215. /// constructor for rvalue objects
  15216. json_value(object_t&& value)
  15217. {
  15218. object = create<object_t>(std::move(value));
  15219. }
  15220. /// constructor for arrays
  15221. json_value(const array_t& value)
  15222. {
  15223. array = create<array_t>(value);
  15224. }
  15225. /// constructor for rvalue arrays
  15226. json_value(array_t&& value)
  15227. {
  15228. array = create<array_t>(std::move(value));
  15229. }
  15230. /// constructor for binary arrays
  15231. json_value(const typename binary_t::container_type& value)
  15232. {
  15233. binary = create<binary_t>(value);
  15234. }
  15235. /// constructor for rvalue binary arrays
  15236. json_value(typename binary_t::container_type&& value)
  15237. {
  15238. binary = create<binary_t>(std::move(value));
  15239. }
  15240. /// constructor for binary arrays (internal type)
  15241. json_value(const binary_t& value)
  15242. {
  15243. binary = create<binary_t>(value);
  15244. }
  15245. /// constructor for rvalue binary arrays (internal type)
  15246. json_value(binary_t&& value)
  15247. {
  15248. binary = create<binary_t>(std::move(value));
  15249. }
  15250. void destroy(value_t t) noexcept
  15251. {
  15252. // flatten the current json_value to a heap-allocated stack
  15253. std::vector<basic_json> stack;
  15254. // move the top-level items to stack
  15255. if (t == value_t::array)
  15256. {
  15257. stack.reserve(array->size());
  15258. std::move(array->begin(), array->end(), std::back_inserter(stack));
  15259. }
  15260. else if (t == value_t::object)
  15261. {
  15262. stack.reserve(object->size());
  15263. for (auto&& it : *object)
  15264. {
  15265. stack.push_back(std::move(it.second));
  15266. }
  15267. }
  15268. while (!stack.empty())
  15269. {
  15270. // move the last item to local variable to be processed
  15271. basic_json current_item(std::move(stack.back()));
  15272. stack.pop_back();
  15273. // if current_item is array/object, move
  15274. // its children to the stack to be processed later
  15275. if (current_item.is_array())
  15276. {
  15277. std::move(current_item.m_value.array->begin(), current_item.m_value.array->end(),
  15278. std::back_inserter(stack));
  15279. current_item.m_value.array->clear();
  15280. }
  15281. else if (current_item.is_object())
  15282. {
  15283. for (auto&& it : *current_item.m_value.object)
  15284. {
  15285. stack.push_back(std::move(it.second));
  15286. }
  15287. current_item.m_value.object->clear();
  15288. }
  15289. // it's now safe that current_item get destructed
  15290. // since it doesn't have any children
  15291. }
  15292. switch (t)
  15293. {
  15294. case value_t::object:
  15295. {
  15296. AllocatorType<object_t> alloc;
  15297. std::allocator_traits<decltype(alloc)>::destroy(alloc, object);
  15298. std::allocator_traits<decltype(alloc)>::deallocate(alloc, object, 1);
  15299. break;
  15300. }
  15301. case value_t::array:
  15302. {
  15303. AllocatorType<array_t> alloc;
  15304. std::allocator_traits<decltype(alloc)>::destroy(alloc, array);
  15305. std::allocator_traits<decltype(alloc)>::deallocate(alloc, array, 1);
  15306. break;
  15307. }
  15308. case value_t::string:
  15309. {
  15310. AllocatorType<string_t> alloc;
  15311. std::allocator_traits<decltype(alloc)>::destroy(alloc, string);
  15312. std::allocator_traits<decltype(alloc)>::deallocate(alloc, string, 1);
  15313. break;
  15314. }
  15315. case value_t::binary:
  15316. {
  15317. AllocatorType<binary_t> alloc;
  15318. std::allocator_traits<decltype(alloc)>::destroy(alloc, binary);
  15319. std::allocator_traits<decltype(alloc)>::deallocate(alloc, binary, 1);
  15320. break;
  15321. }
  15322. default:
  15323. {
  15324. break;
  15325. }
  15326. }
  15327. }
  15328. };
  15329. /*!
  15330. @brief checks the class invariants
  15331. This function asserts the class invariants. It needs to be called at the
  15332. end of every constructor to make sure that created objects respect the
  15333. invariant. Furthermore, it has to be called each time the type of a JSON
  15334. value is changed, because the invariant expresses a relationship between
  15335. @a m_type and @a m_value.
  15336. */
  15337. void assert_invariant() const noexcept
  15338. {
  15339. JSON_ASSERT(m_type != value_t::object || m_value.object != nullptr);
  15340. JSON_ASSERT(m_type != value_t::array || m_value.array != nullptr);
  15341. JSON_ASSERT(m_type != value_t::string || m_value.string != nullptr);
  15342. JSON_ASSERT(m_type != value_t::binary || m_value.binary != nullptr);
  15343. }
  15344. public:
  15345. //////////////////////////
  15346. // JSON parser callback //
  15347. //////////////////////////
  15348. /*!
  15349. @brief parser event types
  15350. The parser callback distinguishes the following events:
  15351. - `object_start`: the parser read `{` and started to process a JSON object
  15352. - `key`: the parser read a key of a value in an object
  15353. - `object_end`: the parser read `}` and finished processing a JSON object
  15354. - `array_start`: the parser read `[` and started to process a JSON array
  15355. - `array_end`: the parser read `]` and finished processing a JSON array
  15356. - `value`: the parser finished reading a JSON value
  15357. @image html callback_events.png "Example when certain parse events are triggered"
  15358. @sa @ref parser_callback_t for more information and examples
  15359. */
  15360. using parse_event_t = detail::parse_event_t;
  15361. /*!
  15362. @brief per-element parser callback type
  15363. With a parser callback function, the result of parsing a JSON text can be
  15364. influenced. When passed to @ref parse, it is called on certain events
  15365. (passed as @ref parse_event_t via parameter @a event) with a set recursion
  15366. depth @a depth and context JSON value @a parsed. The return value of the
  15367. callback function is a boolean indicating whether the element that emitted
  15368. the callback shall be kept or not.
  15369. We distinguish six scenarios (determined by the event type) in which the
  15370. callback function can be called. The following table describes the values
  15371. of the parameters @a depth, @a event, and @a parsed.
  15372. parameter @a event | description | parameter @a depth | parameter @a parsed
  15373. ------------------ | ----------- | ------------------ | -------------------
  15374. 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
  15375. 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
  15376. 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
  15377. 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
  15378. 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
  15379. parse_event_t::value | the parser finished reading a JSON value | depth of the value | the parsed JSON value
  15380. @image html callback_events.png "Example when certain parse events are triggered"
  15381. Discarding a value (i.e., returning `false`) has different effects
  15382. depending on the context in which function was called:
  15383. - Discarded values in structured types are skipped. That is, the parser
  15384. will behave as if the discarded value was never read.
  15385. - In case a value outside a structured type is skipped, it is replaced
  15386. with `null`. This case happens if the top-level element is skipped.
  15387. @param[in] depth the depth of the recursion during parsing
  15388. @param[in] event an event of type parse_event_t indicating the context in
  15389. the callback function has been called
  15390. @param[in,out] parsed the current intermediate parse result; note that
  15391. writing to this value has no effect for parse_event_t::key events
  15392. @return Whether the JSON value which called the function during parsing
  15393. should be kept (`true`) or not (`false`). In the latter case, it is either
  15394. skipped completely or replaced by an empty discarded object.
  15395. @sa @ref parse for examples
  15396. @since version 1.0.0
  15397. */
  15398. using parser_callback_t = detail::parser_callback_t<basic_json>;
  15399. //////////////////
  15400. // constructors //
  15401. //////////////////
  15402. /// @name constructors and destructors
  15403. /// Constructors of class @ref basic_json, copy/move constructor, copy
  15404. /// assignment, static functions creating objects, and the destructor.
  15405. /// @{
  15406. /*!
  15407. @brief create an empty value with a given type
  15408. Create an empty JSON value with a given type. The value will be default
  15409. initialized with an empty value which depends on the type:
  15410. Value type | initial value
  15411. ----------- | -------------
  15412. null | `null`
  15413. boolean | `false`
  15414. string | `""`
  15415. number | `0`
  15416. object | `{}`
  15417. array | `[]`
  15418. binary | empty array
  15419. @param[in] v the type of the value to create
  15420. @complexity Constant.
  15421. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  15422. changes to any JSON value.
  15423. @liveexample{The following code shows the constructor for different @ref
  15424. value_t values,basic_json__value_t}
  15425. @sa @ref clear() -- restores the postcondition of this constructor
  15426. @since version 1.0.0
  15427. */
  15428. basic_json(const value_t v)
  15429. : m_type(v), m_value(v)
  15430. {
  15431. assert_invariant();
  15432. }
  15433. /*!
  15434. @brief create a null object
  15435. Create a `null` JSON value. It either takes a null pointer as parameter
  15436. (explicitly creating `null`) or no parameter (implicitly creating `null`).
  15437. The passed null pointer itself is not read -- it is only used to choose
  15438. the right constructor.
  15439. @complexity Constant.
  15440. @exceptionsafety No-throw guarantee: this constructor never throws
  15441. exceptions.
  15442. @liveexample{The following code shows the constructor with and without a
  15443. null pointer parameter.,basic_json__nullptr_t}
  15444. @since version 1.0.0
  15445. */
  15446. basic_json(std::nullptr_t = nullptr) noexcept
  15447. : basic_json(value_t::null)
  15448. {
  15449. assert_invariant();
  15450. }
  15451. /*!
  15452. @brief create a JSON value
  15453. This is a "catch all" constructor for all compatible JSON types; that is,
  15454. types for which a `to_json()` method exists. The constructor forwards the
  15455. parameter @a val to that method (to `json_serializer<U>::to_json` method
  15456. with `U = uncvref_t<CompatibleType>`, to be exact).
  15457. Template type @a CompatibleType includes, but is not limited to, the
  15458. following types:
  15459. - **arrays**: @ref array_t and all kinds of compatible containers such as
  15460. `std::vector`, `std::deque`, `std::list`, `std::forward_list`,
  15461. `std::array`, `std::valarray`, `std::set`, `std::unordered_set`,
  15462. `std::multiset`, and `std::unordered_multiset` with a `value_type` from
  15463. which a @ref basic_json value can be constructed.
  15464. - **objects**: @ref object_t and all kinds of compatible associative
  15465. containers such as `std::map`, `std::unordered_map`, `std::multimap`,
  15466. and `std::unordered_multimap` with a `key_type` compatible to
  15467. @ref string_t and a `value_type` from which a @ref basic_json value can
  15468. be constructed.
  15469. - **strings**: @ref string_t, string literals, and all compatible string
  15470. containers can be used.
  15471. - **numbers**: @ref number_integer_t, @ref number_unsigned_t,
  15472. @ref number_float_t, and all convertible number types such as `int`,
  15473. `size_t`, `int64_t`, `float` or `double` can be used.
  15474. - **boolean**: @ref boolean_t / `bool` can be used.
  15475. - **binary**: @ref binary_t / `std::vector<uint8_t>` may be used,
  15476. unfortunately because string literals cannot be distinguished from binary
  15477. character arrays by the C++ type system, all types compatible with `const
  15478. char*` will be directed to the string constructor instead. This is both
  15479. for backwards compatibility, and due to the fact that a binary type is not
  15480. a standard JSON type.
  15481. See the examples below.
  15482. @tparam CompatibleType a type such that:
  15483. - @a CompatibleType is not derived from `std::istream`,
  15484. - @a CompatibleType is not @ref basic_json (to avoid hijacking copy/move
  15485. constructors),
  15486. - @a CompatibleType is not a different @ref basic_json type (i.e. with different template arguments)
  15487. - @a CompatibleType is not a @ref basic_json nested type (e.g.,
  15488. @ref json_pointer, @ref iterator, etc ...)
  15489. - @ref @ref json_serializer<U> has a
  15490. `to_json(basic_json_t&, CompatibleType&&)` method
  15491. @tparam U = `uncvref_t<CompatibleType>`
  15492. @param[in] val the value to be forwarded to the respective constructor
  15493. @complexity Usually linear in the size of the passed @a val, also
  15494. depending on the implementation of the called `to_json()`
  15495. method.
  15496. @exceptionsafety Depends on the called constructor. For types directly
  15497. supported by the library (i.e., all types for which no `to_json()` function
  15498. was provided), strong guarantee holds: if an exception is thrown, there are
  15499. no changes to any JSON value.
  15500. @liveexample{The following code shows the constructor with several
  15501. compatible types.,basic_json__CompatibleType}
  15502. @since version 2.1.0
  15503. */
  15504. template < typename CompatibleType,
  15505. typename U = detail::uncvref_t<CompatibleType>,
  15506. detail::enable_if_t <
  15507. !detail::is_basic_json<U>::value && detail::is_compatible_type<basic_json_t, U>::value, int > = 0 >
  15508. basic_json(CompatibleType && val) noexcept(noexcept(
  15509. JSONSerializer<U>::to_json(std::declval<basic_json_t&>(),
  15510. std::forward<CompatibleType>(val))))
  15511. {
  15512. JSONSerializer<U>::to_json(*this, std::forward<CompatibleType>(val));
  15513. assert_invariant();
  15514. }
  15515. /*!
  15516. @brief create a JSON value from an existing one
  15517. This is a constructor for existing @ref basic_json types.
  15518. It does not hijack copy/move constructors, since the parameter has different
  15519. template arguments than the current ones.
  15520. The constructor tries to convert the internal @ref m_value of the parameter.
  15521. @tparam BasicJsonType a type such that:
  15522. - @a BasicJsonType is a @ref basic_json type.
  15523. - @a BasicJsonType has different template arguments than @ref basic_json_t.
  15524. @param[in] val the @ref basic_json value to be converted.
  15525. @complexity Usually linear in the size of the passed @a val, also
  15526. depending on the implementation of the called `to_json()`
  15527. method.
  15528. @exceptionsafety Depends on the called constructor. For types directly
  15529. supported by the library (i.e., all types for which no `to_json()` function
  15530. was provided), strong guarantee holds: if an exception is thrown, there are
  15531. no changes to any JSON value.
  15532. @since version 3.2.0
  15533. */
  15534. template < typename BasicJsonType,
  15535. detail::enable_if_t <
  15536. detail::is_basic_json<BasicJsonType>::value&& !std::is_same<basic_json, BasicJsonType>::value, int > = 0 >
  15537. basic_json(const BasicJsonType& val)
  15538. {
  15539. using other_boolean_t = typename BasicJsonType::boolean_t;
  15540. using other_number_float_t = typename BasicJsonType::number_float_t;
  15541. using other_number_integer_t = typename BasicJsonType::number_integer_t;
  15542. using other_number_unsigned_t = typename BasicJsonType::number_unsigned_t;
  15543. using other_string_t = typename BasicJsonType::string_t;
  15544. using other_object_t = typename BasicJsonType::object_t;
  15545. using other_array_t = typename BasicJsonType::array_t;
  15546. using other_binary_t = typename BasicJsonType::binary_t;
  15547. switch (val.type())
  15548. {
  15549. case value_t::boolean:
  15550. JSONSerializer<other_boolean_t>::to_json(*this, val.template get<other_boolean_t>());
  15551. break;
  15552. case value_t::number_float:
  15553. JSONSerializer<other_number_float_t>::to_json(*this, val.template get<other_number_float_t>());
  15554. break;
  15555. case value_t::number_integer:
  15556. JSONSerializer<other_number_integer_t>::to_json(*this, val.template get<other_number_integer_t>());
  15557. break;
  15558. case value_t::number_unsigned:
  15559. JSONSerializer<other_number_unsigned_t>::to_json(*this, val.template get<other_number_unsigned_t>());
  15560. break;
  15561. case value_t::string:
  15562. JSONSerializer<other_string_t>::to_json(*this, val.template get_ref<const other_string_t&>());
  15563. break;
  15564. case value_t::object:
  15565. JSONSerializer<other_object_t>::to_json(*this, val.template get_ref<const other_object_t&>());
  15566. break;
  15567. case value_t::array:
  15568. JSONSerializer<other_array_t>::to_json(*this, val.template get_ref<const other_array_t&>());
  15569. break;
  15570. case value_t::binary:
  15571. JSONSerializer<other_binary_t>::to_json(*this, val.template get_ref<const other_binary_t&>());
  15572. break;
  15573. case value_t::null:
  15574. *this = nullptr;
  15575. break;
  15576. case value_t::discarded:
  15577. m_type = value_t::discarded;
  15578. break;
  15579. default: // LCOV_EXCL_LINE
  15580. JSON_ASSERT(false); // LCOV_EXCL_LINE
  15581. }
  15582. assert_invariant();
  15583. }
  15584. /*!
  15585. @brief create a container (array or object) from an initializer list
  15586. Creates a JSON value of type array or object from the passed initializer
  15587. list @a init. In case @a type_deduction is `true` (default), the type of
  15588. the JSON value to be created is deducted from the initializer list @a init
  15589. according to the following rules:
  15590. 1. If the list is empty, an empty JSON object value `{}` is created.
  15591. 2. If the list consists of pairs whose first element is a string, a JSON
  15592. object value is created where the first elements of the pairs are
  15593. treated as keys and the second elements are as values.
  15594. 3. In all other cases, an array is created.
  15595. The rules aim to create the best fit between a C++ initializer list and
  15596. JSON values. The rationale is as follows:
  15597. 1. The empty initializer list is written as `{}` which is exactly an empty
  15598. JSON object.
  15599. 2. C++ has no way of describing mapped types other than to list a list of
  15600. pairs. As JSON requires that keys must be of type string, rule 2 is the
  15601. weakest constraint one can pose on initializer lists to interpret them
  15602. as an object.
  15603. 3. In all other cases, the initializer list could not be interpreted as
  15604. JSON object type, so interpreting it as JSON array type is safe.
  15605. With the rules described above, the following JSON values cannot be
  15606. expressed by an initializer list:
  15607. - the empty array (`[]`): use @ref array(initializer_list_t)
  15608. with an empty initializer list in this case
  15609. - arrays whose elements satisfy rule 2: use @ref
  15610. array(initializer_list_t) with the same initializer list
  15611. in this case
  15612. @note When used without parentheses around an empty initializer list, @ref
  15613. basic_json() is called instead of this function, yielding the JSON null
  15614. value.
  15615. @param[in] init initializer list with JSON values
  15616. @param[in] type_deduction internal parameter; when set to `true`, the type
  15617. of the JSON value is deducted from the initializer list @a init; when set
  15618. to `false`, the type provided via @a manual_type is forced. This mode is
  15619. used by the functions @ref array(initializer_list_t) and
  15620. @ref object(initializer_list_t).
  15621. @param[in] manual_type internal parameter; when @a type_deduction is set
  15622. to `false`, the created JSON value will use the provided type (only @ref
  15623. value_t::array and @ref value_t::object are valid); when @a type_deduction
  15624. is set to `true`, this parameter has no effect
  15625. @throw type_error.301 if @a type_deduction is `false`, @a manual_type is
  15626. `value_t::object`, but @a init contains an element which is not a pair
  15627. whose first element is a string. In this case, the constructor could not
  15628. create an object. If @a type_deduction would have be `true`, an array
  15629. would have been created. See @ref object(initializer_list_t)
  15630. for an example.
  15631. @complexity Linear in the size of the initializer list @a init.
  15632. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  15633. changes to any JSON value.
  15634. @liveexample{The example below shows how JSON values are created from
  15635. initializer lists.,basic_json__list_init_t}
  15636. @sa @ref array(initializer_list_t) -- create a JSON array
  15637. value from an initializer list
  15638. @sa @ref object(initializer_list_t) -- create a JSON object
  15639. value from an initializer list
  15640. @since version 1.0.0
  15641. */
  15642. basic_json(initializer_list_t init,
  15643. bool type_deduction = true,
  15644. value_t manual_type = value_t::array)
  15645. {
  15646. // check if each element is an array with two elements whose first
  15647. // element is a string
  15648. bool is_an_object = std::all_of(init.begin(), init.end(),
  15649. [](const detail::json_ref<basic_json>& element_ref)
  15650. {
  15651. return element_ref->is_array() && element_ref->size() == 2 && (*element_ref)[0].is_string();
  15652. });
  15653. // adjust type if type deduction is not wanted
  15654. if (!type_deduction)
  15655. {
  15656. // if array is wanted, do not create an object though possible
  15657. if (manual_type == value_t::array)
  15658. {
  15659. is_an_object = false;
  15660. }
  15661. // if object is wanted but impossible, throw an exception
  15662. if (JSON_HEDLEY_UNLIKELY(manual_type == value_t::object && !is_an_object))
  15663. {
  15664. JSON_THROW(type_error::create(301, "cannot create object from initializer list"));
  15665. }
  15666. }
  15667. if (is_an_object)
  15668. {
  15669. // the initializer list is a list of pairs -> create object
  15670. m_type = value_t::object;
  15671. m_value = value_t::object;
  15672. std::for_each(init.begin(), init.end(), [this](const detail::json_ref<basic_json>& element_ref)
  15673. {
  15674. auto element = element_ref.moved_or_copied();
  15675. m_value.object->emplace(
  15676. std::move(*((*element.m_value.array)[0].m_value.string)),
  15677. std::move((*element.m_value.array)[1]));
  15678. });
  15679. }
  15680. else
  15681. {
  15682. // the initializer list describes an array -> create array
  15683. m_type = value_t::array;
  15684. m_value.array = create<array_t>(init.begin(), init.end());
  15685. }
  15686. assert_invariant();
  15687. }
  15688. /*!
  15689. @brief explicitly create a binary array (without subtype)
  15690. Creates a JSON binary array value from a given binary container. Binary
  15691. values are part of various binary formats, such as CBOR, MessagePack, and
  15692. BSON. This constructor is used to create a value for serialization to those
  15693. formats.
  15694. @note Note, this function exists because of the difficulty in correctly
  15695. specifying the correct template overload in the standard value ctor, as both
  15696. JSON arrays and JSON binary arrays are backed with some form of a
  15697. `std::vector`. Because JSON binary arrays are a non-standard extension it
  15698. was decided that it would be best to prevent automatic initialization of a
  15699. binary array type, for backwards compatibility and so it does not happen on
  15700. accident.
  15701. @param[in] init container containing bytes to use as binary type
  15702. @return JSON binary array value
  15703. @complexity Linear in the size of @a init.
  15704. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  15705. changes to any JSON value.
  15706. @since version 3.8.0
  15707. */
  15708. JSON_HEDLEY_WARN_UNUSED_RESULT
  15709. static basic_json binary(const typename binary_t::container_type& init)
  15710. {
  15711. auto res = basic_json();
  15712. res.m_type = value_t::binary;
  15713. res.m_value = init;
  15714. return res;
  15715. }
  15716. /*!
  15717. @brief explicitly create a binary array (with subtype)
  15718. Creates a JSON binary array value from a given binary container. Binary
  15719. values are part of various binary formats, such as CBOR, MessagePack, and
  15720. BSON. This constructor is used to create a value for serialization to those
  15721. formats.
  15722. @note Note, this function exists because of the difficulty in correctly
  15723. specifying the correct template overload in the standard value ctor, as both
  15724. JSON arrays and JSON binary arrays are backed with some form of a
  15725. `std::vector`. Because JSON binary arrays are a non-standard extension it
  15726. was decided that it would be best to prevent automatic initialization of a
  15727. binary array type, for backwards compatibility and so it does not happen on
  15728. accident.
  15729. @param[in] init container containing bytes to use as binary type
  15730. @param[in] subtype subtype to use in MessagePack and BSON
  15731. @return JSON binary array value
  15732. @complexity Linear in the size of @a init.
  15733. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  15734. changes to any JSON value.
  15735. @since version 3.8.0
  15736. */
  15737. JSON_HEDLEY_WARN_UNUSED_RESULT
  15738. static basic_json binary(const typename binary_t::container_type& init, std::uint8_t subtype)
  15739. {
  15740. auto res = basic_json();
  15741. res.m_type = value_t::binary;
  15742. res.m_value = binary_t(init, subtype);
  15743. return res;
  15744. }
  15745. /// @copydoc binary(const typename binary_t::container_type&)
  15746. JSON_HEDLEY_WARN_UNUSED_RESULT
  15747. static basic_json binary(typename binary_t::container_type&& init)
  15748. {
  15749. auto res = basic_json();
  15750. res.m_type = value_t::binary;
  15751. res.m_value = std::move(init);
  15752. return res;
  15753. }
  15754. /// @copydoc binary(const typename binary_t::container_type&, std::uint8_t)
  15755. JSON_HEDLEY_WARN_UNUSED_RESULT
  15756. static basic_json binary(typename binary_t::container_type&& init, std::uint8_t subtype)
  15757. {
  15758. auto res = basic_json();
  15759. res.m_type = value_t::binary;
  15760. res.m_value = binary_t(std::move(init), subtype);
  15761. return res;
  15762. }
  15763. /*!
  15764. @brief explicitly create an array from an initializer list
  15765. Creates a JSON array value from a given initializer list. That is, given a
  15766. list of values `a, b, c`, creates the JSON value `[a, b, c]`. If the
  15767. initializer list is empty, the empty array `[]` is created.
  15768. @note This function is only needed to express two edge cases that cannot
  15769. be realized with the initializer list constructor (@ref
  15770. basic_json(initializer_list_t, bool, value_t)). These cases
  15771. are:
  15772. 1. creating an array whose elements are all pairs whose first element is a
  15773. string -- in this case, the initializer list constructor would create an
  15774. object, taking the first elements as keys
  15775. 2. creating an empty array -- passing the empty initializer list to the
  15776. initializer list constructor yields an empty object
  15777. @param[in] init initializer list with JSON values to create an array from
  15778. (optional)
  15779. @return JSON array value
  15780. @complexity Linear in the size of @a init.
  15781. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  15782. changes to any JSON value.
  15783. @liveexample{The following code shows an example for the `array`
  15784. function.,array}
  15785. @sa @ref basic_json(initializer_list_t, bool, value_t) --
  15786. create a JSON value from an initializer list
  15787. @sa @ref object(initializer_list_t) -- create a JSON object
  15788. value from an initializer list
  15789. @since version 1.0.0
  15790. */
  15791. JSON_HEDLEY_WARN_UNUSED_RESULT
  15792. static basic_json array(initializer_list_t init = {})
  15793. {
  15794. return basic_json(init, false, value_t::array);
  15795. }
  15796. /*!
  15797. @brief explicitly create an object from an initializer list
  15798. Creates a JSON object value from a given initializer list. The initializer
  15799. lists elements must be pairs, and their first elements must be strings. If
  15800. the initializer list is empty, the empty object `{}` is created.
  15801. @note This function is only added for symmetry reasons. In contrast to the
  15802. related function @ref array(initializer_list_t), there are
  15803. no cases which can only be expressed by this function. That is, any
  15804. initializer list @a init can also be passed to the initializer list
  15805. constructor @ref basic_json(initializer_list_t, bool, value_t).
  15806. @param[in] init initializer list to create an object from (optional)
  15807. @return JSON object value
  15808. @throw type_error.301 if @a init is not a list of pairs whose first
  15809. elements are strings. In this case, no object can be created. When such a
  15810. value is passed to @ref basic_json(initializer_list_t, bool, value_t),
  15811. an array would have been created from the passed initializer list @a init.
  15812. See example below.
  15813. @complexity Linear in the size of @a init.
  15814. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  15815. changes to any JSON value.
  15816. @liveexample{The following code shows an example for the `object`
  15817. function.,object}
  15818. @sa @ref basic_json(initializer_list_t, bool, value_t) --
  15819. create a JSON value from an initializer list
  15820. @sa @ref array(initializer_list_t) -- create a JSON array
  15821. value from an initializer list
  15822. @since version 1.0.0
  15823. */
  15824. JSON_HEDLEY_WARN_UNUSED_RESULT
  15825. static basic_json object(initializer_list_t init = {})
  15826. {
  15827. return basic_json(init, false, value_t::object);
  15828. }
  15829. /*!
  15830. @brief construct an array with count copies of given value
  15831. Constructs a JSON array value by creating @a cnt copies of a passed value.
  15832. In case @a cnt is `0`, an empty array is created.
  15833. @param[in] cnt the number of JSON copies of @a val to create
  15834. @param[in] val the JSON value to copy
  15835. @post `std::distance(begin(),end()) == cnt` holds.
  15836. @complexity Linear in @a cnt.
  15837. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  15838. changes to any JSON value.
  15839. @liveexample{The following code shows examples for the @ref
  15840. basic_json(size_type\, const basic_json&)
  15841. constructor.,basic_json__size_type_basic_json}
  15842. @since version 1.0.0
  15843. */
  15844. basic_json(size_type cnt, const basic_json& val)
  15845. : m_type(value_t::array)
  15846. {
  15847. m_value.array = create<array_t>(cnt, val);
  15848. assert_invariant();
  15849. }
  15850. /*!
  15851. @brief construct a JSON container given an iterator range
  15852. Constructs the JSON value with the contents of the range `[first, last)`.
  15853. The semantics depends on the different types a JSON value can have:
  15854. - In case of a null type, invalid_iterator.206 is thrown.
  15855. - In case of other primitive types (number, boolean, or string), @a first
  15856. must be `begin()` and @a last must be `end()`. In this case, the value is
  15857. copied. Otherwise, invalid_iterator.204 is thrown.
  15858. - In case of structured types (array, object), the constructor behaves as
  15859. similar versions for `std::vector` or `std::map`; that is, a JSON array
  15860. or object is constructed from the values in the range.
  15861. @tparam InputIT an input iterator type (@ref iterator or @ref
  15862. const_iterator)
  15863. @param[in] first begin of the range to copy from (included)
  15864. @param[in] last end of the range to copy from (excluded)
  15865. @pre Iterators @a first and @a last must be initialized. **This
  15866. precondition is enforced with an assertion (see warning).** If
  15867. assertions are switched off, a violation of this precondition yields
  15868. undefined behavior.
  15869. @pre Range `[first, last)` is valid. Usually, this precondition cannot be
  15870. checked efficiently. Only certain edge cases are detected; see the
  15871. description of the exceptions below. A violation of this precondition
  15872. yields undefined behavior.
  15873. @warning A precondition is enforced with a runtime assertion that will
  15874. result in calling `std::abort` if this precondition is not met.
  15875. Assertions can be disabled by defining `NDEBUG` at compile time.
  15876. See https://en.cppreference.com/w/cpp/error/assert for more
  15877. information.
  15878. @throw invalid_iterator.201 if iterators @a first and @a last are not
  15879. compatible (i.e., do not belong to the same JSON value). In this case,
  15880. the range `[first, last)` is undefined.
  15881. @throw invalid_iterator.204 if iterators @a first and @a last belong to a
  15882. primitive type (number, boolean, or string), but @a first does not point
  15883. to the first element any more. In this case, the range `[first, last)` is
  15884. undefined. See example code below.
  15885. @throw invalid_iterator.206 if iterators @a first and @a last belong to a
  15886. null value. In this case, the range `[first, last)` is undefined.
  15887. @complexity Linear in distance between @a first and @a last.
  15888. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  15889. changes to any JSON value.
  15890. @liveexample{The example below shows several ways to create JSON values by
  15891. specifying a subrange with iterators.,basic_json__InputIt_InputIt}
  15892. @since version 1.0.0
  15893. */
  15894. template < class InputIT, typename std::enable_if <
  15895. std::is_same<InputIT, typename basic_json_t::iterator>::value ||
  15896. std::is_same<InputIT, typename basic_json_t::const_iterator>::value, int >::type = 0 >
  15897. basic_json(InputIT first, InputIT last)
  15898. {
  15899. JSON_ASSERT(first.m_object != nullptr);
  15900. JSON_ASSERT(last.m_object != nullptr);
  15901. // make sure iterator fits the current value
  15902. if (JSON_HEDLEY_UNLIKELY(first.m_object != last.m_object))
  15903. {
  15904. JSON_THROW(invalid_iterator::create(201, "iterators are not compatible"));
  15905. }
  15906. // copy type from first iterator
  15907. m_type = first.m_object->m_type;
  15908. // check if iterator range is complete for primitive values
  15909. switch (m_type)
  15910. {
  15911. case value_t::boolean:
  15912. case value_t::number_float:
  15913. case value_t::number_integer:
  15914. case value_t::number_unsigned:
  15915. case value_t::string:
  15916. {
  15917. if (JSON_HEDLEY_UNLIKELY(!first.m_it.primitive_iterator.is_begin()
  15918. || !last.m_it.primitive_iterator.is_end()))
  15919. {
  15920. JSON_THROW(invalid_iterator::create(204, "iterators out of range"));
  15921. }
  15922. break;
  15923. }
  15924. default:
  15925. break;
  15926. }
  15927. switch (m_type)
  15928. {
  15929. case value_t::number_integer:
  15930. {
  15931. m_value.number_integer = first.m_object->m_value.number_integer;
  15932. break;
  15933. }
  15934. case value_t::number_unsigned:
  15935. {
  15936. m_value.number_unsigned = first.m_object->m_value.number_unsigned;
  15937. break;
  15938. }
  15939. case value_t::number_float:
  15940. {
  15941. m_value.number_float = first.m_object->m_value.number_float;
  15942. break;
  15943. }
  15944. case value_t::boolean:
  15945. {
  15946. m_value.boolean = first.m_object->m_value.boolean;
  15947. break;
  15948. }
  15949. case value_t::string:
  15950. {
  15951. m_value = *first.m_object->m_value.string;
  15952. break;
  15953. }
  15954. case value_t::object:
  15955. {
  15956. m_value.object = create<object_t>(first.m_it.object_iterator,
  15957. last.m_it.object_iterator);
  15958. break;
  15959. }
  15960. case value_t::array:
  15961. {
  15962. m_value.array = create<array_t>(first.m_it.array_iterator,
  15963. last.m_it.array_iterator);
  15964. break;
  15965. }
  15966. case value_t::binary:
  15967. {
  15968. m_value = *first.m_object->m_value.binary;
  15969. break;
  15970. }
  15971. default:
  15972. JSON_THROW(invalid_iterator::create(206, "cannot construct with iterators from " +
  15973. std::string(first.m_object->type_name())));
  15974. }
  15975. assert_invariant();
  15976. }
  15977. ///////////////////////////////////////
  15978. // other constructors and destructor //
  15979. ///////////////////////////////////////
  15980. template<typename JsonRef,
  15981. detail::enable_if_t<detail::conjunction<detail::is_json_ref<JsonRef>,
  15982. std::is_same<typename JsonRef::value_type, basic_json>>::value, int> = 0 >
  15983. basic_json(const JsonRef& ref) : basic_json(ref.moved_or_copied()) {}
  15984. /*!
  15985. @brief copy constructor
  15986. Creates a copy of a given JSON value.
  15987. @param[in] other the JSON value to copy
  15988. @post `*this == other`
  15989. @complexity Linear in the size of @a other.
  15990. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  15991. changes to any JSON value.
  15992. @requirement This function helps `basic_json` satisfying the
  15993. [Container](https://en.cppreference.com/w/cpp/named_req/Container)
  15994. requirements:
  15995. - The complexity is linear.
  15996. - As postcondition, it holds: `other == basic_json(other)`.
  15997. @liveexample{The following code shows an example for the copy
  15998. constructor.,basic_json__basic_json}
  15999. @since version 1.0.0
  16000. */
  16001. basic_json(const basic_json& other)
  16002. : m_type(other.m_type)
  16003. {
  16004. // check of passed value is valid
  16005. other.assert_invariant();
  16006. switch (m_type)
  16007. {
  16008. case value_t::object:
  16009. {
  16010. m_value = *other.m_value.object;
  16011. break;
  16012. }
  16013. case value_t::array:
  16014. {
  16015. m_value = *other.m_value.array;
  16016. break;
  16017. }
  16018. case value_t::string:
  16019. {
  16020. m_value = *other.m_value.string;
  16021. break;
  16022. }
  16023. case value_t::boolean:
  16024. {
  16025. m_value = other.m_value.boolean;
  16026. break;
  16027. }
  16028. case value_t::number_integer:
  16029. {
  16030. m_value = other.m_value.number_integer;
  16031. break;
  16032. }
  16033. case value_t::number_unsigned:
  16034. {
  16035. m_value = other.m_value.number_unsigned;
  16036. break;
  16037. }
  16038. case value_t::number_float:
  16039. {
  16040. m_value = other.m_value.number_float;
  16041. break;
  16042. }
  16043. case value_t::binary:
  16044. {
  16045. m_value = *other.m_value.binary;
  16046. break;
  16047. }
  16048. default:
  16049. break;
  16050. }
  16051. assert_invariant();
  16052. }
  16053. /*!
  16054. @brief move constructor
  16055. Move constructor. Constructs a JSON value with the contents of the given
  16056. value @a other using move semantics. It "steals" the resources from @a
  16057. other and leaves it as JSON null value.
  16058. @param[in,out] other value to move to this object
  16059. @post `*this` has the same value as @a other before the call.
  16060. @post @a other is a JSON null value.
  16061. @complexity Constant.
  16062. @exceptionsafety No-throw guarantee: this constructor never throws
  16063. exceptions.
  16064. @requirement This function helps `basic_json` satisfying the
  16065. [MoveConstructible](https://en.cppreference.com/w/cpp/named_req/MoveConstructible)
  16066. requirements.
  16067. @liveexample{The code below shows the move constructor explicitly called
  16068. via std::move.,basic_json__moveconstructor}
  16069. @since version 1.0.0
  16070. */
  16071. basic_json(basic_json&& other) noexcept
  16072. : m_type(std::move(other.m_type)),
  16073. m_value(std::move(other.m_value))
  16074. {
  16075. // check that passed value is valid
  16076. other.assert_invariant();
  16077. // invalidate payload
  16078. other.m_type = value_t::null;
  16079. other.m_value = {};
  16080. assert_invariant();
  16081. }
  16082. /*!
  16083. @brief copy assignment
  16084. Copy assignment operator. Copies a JSON value via the "copy and swap"
  16085. strategy: It is expressed in terms of the copy constructor, destructor,
  16086. and the `swap()` member function.
  16087. @param[in] other value to copy from
  16088. @complexity Linear.
  16089. @requirement This function helps `basic_json` satisfying the
  16090. [Container](https://en.cppreference.com/w/cpp/named_req/Container)
  16091. requirements:
  16092. - The complexity is linear.
  16093. @liveexample{The code below shows and example for the copy assignment. It
  16094. creates a copy of value `a` which is then swapped with `b`. Finally\, the
  16095. copy of `a` (which is the null value after the swap) is
  16096. destroyed.,basic_json__copyassignment}
  16097. @since version 1.0.0
  16098. */
  16099. basic_json& operator=(basic_json other) noexcept (
  16100. std::is_nothrow_move_constructible<value_t>::value&&
  16101. std::is_nothrow_move_assignable<value_t>::value&&
  16102. std::is_nothrow_move_constructible<json_value>::value&&
  16103. std::is_nothrow_move_assignable<json_value>::value
  16104. )
  16105. {
  16106. // check that passed value is valid
  16107. other.assert_invariant();
  16108. using std::swap;
  16109. swap(m_type, other.m_type);
  16110. swap(m_value, other.m_value);
  16111. assert_invariant();
  16112. return *this;
  16113. }
  16114. /*!
  16115. @brief destructor
  16116. Destroys the JSON value and frees all allocated memory.
  16117. @complexity Linear.
  16118. @requirement This function helps `basic_json` satisfying the
  16119. [Container](https://en.cppreference.com/w/cpp/named_req/Container)
  16120. requirements:
  16121. - The complexity is linear.
  16122. - All stored elements are destroyed and all memory is freed.
  16123. @since version 1.0.0
  16124. */
  16125. ~basic_json() noexcept
  16126. {
  16127. assert_invariant();
  16128. m_value.destroy(m_type);
  16129. }
  16130. /// @}
  16131. public:
  16132. ///////////////////////
  16133. // object inspection //
  16134. ///////////////////////
  16135. /// @name object inspection
  16136. /// Functions to inspect the type of a JSON value.
  16137. /// @{
  16138. /*!
  16139. @brief serialization
  16140. Serialization function for JSON values. The function tries to mimic
  16141. Python's `json.dumps()` function, and currently supports its @a indent
  16142. and @a ensure_ascii parameters.
  16143. @param[in] indent If indent is nonnegative, then array elements and object
  16144. members will be pretty-printed with that indent level. An indent level of
  16145. `0` will only insert newlines. `-1` (the default) selects the most compact
  16146. representation.
  16147. @param[in] indent_char The character to use for indentation if @a indent is
  16148. greater than `0`. The default is ` ` (space).
  16149. @param[in] ensure_ascii If @a ensure_ascii is true, all non-ASCII characters
  16150. in the output are escaped with `\uXXXX` sequences, and the result consists
  16151. of ASCII characters only.
  16152. @param[in] error_handler how to react on decoding errors; there are three
  16153. possible values: `strict` (throws and exception in case a decoding error
  16154. occurs; default), `replace` (replace invalid UTF-8 sequences with U+FFFD),
  16155. and `ignore` (ignore invalid UTF-8 sequences during serialization; all
  16156. bytes are copied to the output unchanged).
  16157. @return string containing the serialization of the JSON value
  16158. @throw type_error.316 if a string stored inside the JSON value is not
  16159. UTF-8 encoded and @a error_handler is set to strict
  16160. @note Binary values are serialized as object containing two keys:
  16161. - "bytes": an array of bytes as integers
  16162. - "subtype": the subtype as integer or "null" if the binary has no subtype
  16163. @complexity Linear.
  16164. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  16165. changes in the JSON value.
  16166. @liveexample{The following example shows the effect of different @a indent\,
  16167. @a indent_char\, and @a ensure_ascii parameters to the result of the
  16168. serialization.,dump}
  16169. @see https://docs.python.org/2/library/json.html#json.dump
  16170. @since version 1.0.0; indentation character @a indent_char, option
  16171. @a ensure_ascii and exceptions added in version 3.0.0; error
  16172. handlers added in version 3.4.0; serialization of binary values added
  16173. in version 3.8.0.
  16174. */
  16175. string_t dump(const int indent = -1,
  16176. const char indent_char = ' ',
  16177. const bool ensure_ascii = false,
  16178. const error_handler_t error_handler = error_handler_t::strict) const
  16179. {
  16180. string_t result;
  16181. serializer s(detail::output_adapter<char, string_t>(result), indent_char, error_handler);
  16182. if (indent >= 0)
  16183. {
  16184. s.dump(*this, true, ensure_ascii, static_cast<unsigned int>(indent));
  16185. }
  16186. else
  16187. {
  16188. s.dump(*this, false, ensure_ascii, 0);
  16189. }
  16190. return result;
  16191. }
  16192. /*!
  16193. @brief return the type of the JSON value (explicit)
  16194. Return the type of the JSON value as a value from the @ref value_t
  16195. enumeration.
  16196. @return the type of the JSON value
  16197. Value type | return value
  16198. ------------------------- | -------------------------
  16199. null | value_t::null
  16200. boolean | value_t::boolean
  16201. string | value_t::string
  16202. number (integer) | value_t::number_integer
  16203. number (unsigned integer) | value_t::number_unsigned
  16204. number (floating-point) | value_t::number_float
  16205. object | value_t::object
  16206. array | value_t::array
  16207. binary | value_t::binary
  16208. discarded | value_t::discarded
  16209. @complexity Constant.
  16210. @exceptionsafety No-throw guarantee: this member function never throws
  16211. exceptions.
  16212. @liveexample{The following code exemplifies `type()` for all JSON
  16213. types.,type}
  16214. @sa @ref operator value_t() -- return the type of the JSON value (implicit)
  16215. @sa @ref type_name() -- return the type as string
  16216. @since version 1.0.0
  16217. */
  16218. constexpr value_t type() const noexcept
  16219. {
  16220. return m_type;
  16221. }
  16222. /*!
  16223. @brief return whether type is primitive
  16224. This function returns true if and only if the JSON type is primitive
  16225. (string, number, boolean, or null).
  16226. @return `true` if type is primitive (string, number, boolean, or null),
  16227. `false` otherwise.
  16228. @complexity Constant.
  16229. @exceptionsafety No-throw guarantee: this member function never throws
  16230. exceptions.
  16231. @liveexample{The following code exemplifies `is_primitive()` for all JSON
  16232. types.,is_primitive}
  16233. @sa @ref is_structured() -- returns whether JSON value is structured
  16234. @sa @ref is_null() -- returns whether JSON value is `null`
  16235. @sa @ref is_string() -- returns whether JSON value is a string
  16236. @sa @ref is_boolean() -- returns whether JSON value is a boolean
  16237. @sa @ref is_number() -- returns whether JSON value is a number
  16238. @sa @ref is_binary() -- returns whether JSON value is a binary array
  16239. @since version 1.0.0
  16240. */
  16241. constexpr bool is_primitive() const noexcept
  16242. {
  16243. return is_null() || is_string() || is_boolean() || is_number() || is_binary();
  16244. }
  16245. /*!
  16246. @brief return whether type is structured
  16247. This function returns true if and only if the JSON type is structured
  16248. (array or object).
  16249. @return `true` if type is structured (array or object), `false` otherwise.
  16250. @complexity Constant.
  16251. @exceptionsafety No-throw guarantee: this member function never throws
  16252. exceptions.
  16253. @liveexample{The following code exemplifies `is_structured()` for all JSON
  16254. types.,is_structured}
  16255. @sa @ref is_primitive() -- returns whether value is primitive
  16256. @sa @ref is_array() -- returns whether value is an array
  16257. @sa @ref is_object() -- returns whether value is an object
  16258. @since version 1.0.0
  16259. */
  16260. constexpr bool is_structured() const noexcept
  16261. {
  16262. return is_array() || is_object();
  16263. }
  16264. /*!
  16265. @brief return whether value is null
  16266. This function returns true if and only if the JSON value is null.
  16267. @return `true` if type is null, `false` otherwise.
  16268. @complexity Constant.
  16269. @exceptionsafety No-throw guarantee: this member function never throws
  16270. exceptions.
  16271. @liveexample{The following code exemplifies `is_null()` for all JSON
  16272. types.,is_null}
  16273. @since version 1.0.0
  16274. */
  16275. constexpr bool is_null() const noexcept
  16276. {
  16277. return m_type == value_t::null;
  16278. }
  16279. /*!
  16280. @brief return whether value is a boolean
  16281. This function returns true if and only if the JSON value is a boolean.
  16282. @return `true` if type is boolean, `false` otherwise.
  16283. @complexity Constant.
  16284. @exceptionsafety No-throw guarantee: this member function never throws
  16285. exceptions.
  16286. @liveexample{The following code exemplifies `is_boolean()` for all JSON
  16287. types.,is_boolean}
  16288. @since version 1.0.0
  16289. */
  16290. constexpr bool is_boolean() const noexcept
  16291. {
  16292. return m_type == value_t::boolean;
  16293. }
  16294. /*!
  16295. @brief return whether value is a number
  16296. This function returns true if and only if the JSON value is a number. This
  16297. includes both integer (signed and unsigned) and floating-point values.
  16298. @return `true` if type is number (regardless whether integer, unsigned
  16299. integer or floating-type), `false` otherwise.
  16300. @complexity Constant.
  16301. @exceptionsafety No-throw guarantee: this member function never throws
  16302. exceptions.
  16303. @liveexample{The following code exemplifies `is_number()` for all JSON
  16304. types.,is_number}
  16305. @sa @ref is_number_integer() -- check if value is an integer or unsigned
  16306. integer number
  16307. @sa @ref is_number_unsigned() -- check if value is an unsigned integer
  16308. number
  16309. @sa @ref is_number_float() -- check if value is a floating-point number
  16310. @since version 1.0.0
  16311. */
  16312. constexpr bool is_number() const noexcept
  16313. {
  16314. return is_number_integer() || is_number_float();
  16315. }
  16316. /*!
  16317. @brief return whether value is an integer number
  16318. This function returns true if and only if the JSON value is a signed or
  16319. unsigned integer number. This excludes floating-point values.
  16320. @return `true` if type is an integer or unsigned integer number, `false`
  16321. otherwise.
  16322. @complexity Constant.
  16323. @exceptionsafety No-throw guarantee: this member function never throws
  16324. exceptions.
  16325. @liveexample{The following code exemplifies `is_number_integer()` for all
  16326. JSON types.,is_number_integer}
  16327. @sa @ref is_number() -- check if value is a number
  16328. @sa @ref is_number_unsigned() -- check if value is an unsigned integer
  16329. number
  16330. @sa @ref is_number_float() -- check if value is a floating-point number
  16331. @since version 1.0.0
  16332. */
  16333. constexpr bool is_number_integer() const noexcept
  16334. {
  16335. return m_type == value_t::number_integer || m_type == value_t::number_unsigned;
  16336. }
  16337. /*!
  16338. @brief return whether value is an unsigned integer number
  16339. This function returns true if and only if the JSON value is an unsigned
  16340. integer number. This excludes floating-point and signed integer values.
  16341. @return `true` if type is an unsigned integer number, `false` otherwise.
  16342. @complexity Constant.
  16343. @exceptionsafety No-throw guarantee: this member function never throws
  16344. exceptions.
  16345. @liveexample{The following code exemplifies `is_number_unsigned()` for all
  16346. JSON types.,is_number_unsigned}
  16347. @sa @ref is_number() -- check if value is a number
  16348. @sa @ref is_number_integer() -- check if value is an integer or unsigned
  16349. integer number
  16350. @sa @ref is_number_float() -- check if value is a floating-point number
  16351. @since version 2.0.0
  16352. */
  16353. constexpr bool is_number_unsigned() const noexcept
  16354. {
  16355. return m_type == value_t::number_unsigned;
  16356. }
  16357. /*!
  16358. @brief return whether value is a floating-point number
  16359. This function returns true if and only if the JSON value is a
  16360. floating-point number. This excludes signed and unsigned integer values.
  16361. @return `true` if type is a floating-point number, `false` otherwise.
  16362. @complexity Constant.
  16363. @exceptionsafety No-throw guarantee: this member function never throws
  16364. exceptions.
  16365. @liveexample{The following code exemplifies `is_number_float()` for all
  16366. JSON types.,is_number_float}
  16367. @sa @ref is_number() -- check if value is number
  16368. @sa @ref is_number_integer() -- check if value is an integer number
  16369. @sa @ref is_number_unsigned() -- check if value is an unsigned integer
  16370. number
  16371. @since version 1.0.0
  16372. */
  16373. constexpr bool is_number_float() const noexcept
  16374. {
  16375. return m_type == value_t::number_float;
  16376. }
  16377. /*!
  16378. @brief return whether value is an object
  16379. This function returns true if and only if the JSON value is an object.
  16380. @return `true` if type is object, `false` otherwise.
  16381. @complexity Constant.
  16382. @exceptionsafety No-throw guarantee: this member function never throws
  16383. exceptions.
  16384. @liveexample{The following code exemplifies `is_object()` for all JSON
  16385. types.,is_object}
  16386. @since version 1.0.0
  16387. */
  16388. constexpr bool is_object() const noexcept
  16389. {
  16390. return m_type == value_t::object;
  16391. }
  16392. /*!
  16393. @brief return whether value is an array
  16394. This function returns true if and only if the JSON value is an array.
  16395. @return `true` if type is array, `false` otherwise.
  16396. @complexity Constant.
  16397. @exceptionsafety No-throw guarantee: this member function never throws
  16398. exceptions.
  16399. @liveexample{The following code exemplifies `is_array()` for all JSON
  16400. types.,is_array}
  16401. @since version 1.0.0
  16402. */
  16403. constexpr bool is_array() const noexcept
  16404. {
  16405. return m_type == value_t::array;
  16406. }
  16407. /*!
  16408. @brief return whether value is a string
  16409. This function returns true if and only if the JSON value is a string.
  16410. @return `true` if type is string, `false` otherwise.
  16411. @complexity Constant.
  16412. @exceptionsafety No-throw guarantee: this member function never throws
  16413. exceptions.
  16414. @liveexample{The following code exemplifies `is_string()` for all JSON
  16415. types.,is_string}
  16416. @since version 1.0.0
  16417. */
  16418. constexpr bool is_string() const noexcept
  16419. {
  16420. return m_type == value_t::string;
  16421. }
  16422. /*!
  16423. @brief return whether value is a binary array
  16424. This function returns true if and only if the JSON value is a binary array.
  16425. @return `true` if type is binary array, `false` otherwise.
  16426. @complexity Constant.
  16427. @exceptionsafety No-throw guarantee: this member function never throws
  16428. exceptions.
  16429. @liveexample{The following code exemplifies `is_binary()` for all JSON
  16430. types.,is_binary}
  16431. @since version 3.8.0
  16432. */
  16433. constexpr bool is_binary() const noexcept
  16434. {
  16435. return m_type == value_t::binary;
  16436. }
  16437. /*!
  16438. @brief return whether value is discarded
  16439. This function returns true if and only if the JSON value was discarded
  16440. during parsing with a callback function (see @ref parser_callback_t).
  16441. @note This function will always be `false` for JSON values after parsing.
  16442. That is, discarded values can only occur during parsing, but will be
  16443. removed when inside a structured value or replaced by null in other cases.
  16444. @return `true` if type is discarded, `false` otherwise.
  16445. @complexity Constant.
  16446. @exceptionsafety No-throw guarantee: this member function never throws
  16447. exceptions.
  16448. @liveexample{The following code exemplifies `is_discarded()` for all JSON
  16449. types.,is_discarded}
  16450. @since version 1.0.0
  16451. */
  16452. constexpr bool is_discarded() const noexcept
  16453. {
  16454. return m_type == value_t::discarded;
  16455. }
  16456. /*!
  16457. @brief return the type of the JSON value (implicit)
  16458. Implicitly return the type of the JSON value as a value from the @ref
  16459. value_t enumeration.
  16460. @return the type of the JSON value
  16461. @complexity Constant.
  16462. @exceptionsafety No-throw guarantee: this member function never throws
  16463. exceptions.
  16464. @liveexample{The following code exemplifies the @ref value_t operator for
  16465. all JSON types.,operator__value_t}
  16466. @sa @ref type() -- return the type of the JSON value (explicit)
  16467. @sa @ref type_name() -- return the type as string
  16468. @since version 1.0.0
  16469. */
  16470. constexpr operator value_t() const noexcept
  16471. {
  16472. return m_type;
  16473. }
  16474. /// @}
  16475. private:
  16476. //////////////////
  16477. // value access //
  16478. //////////////////
  16479. /// get a boolean (explicit)
  16480. boolean_t get_impl(boolean_t* /*unused*/) const
  16481. {
  16482. if (JSON_HEDLEY_LIKELY(is_boolean()))
  16483. {
  16484. return m_value.boolean;
  16485. }
  16486. JSON_THROW(type_error::create(302, "type must be boolean, but is " + std::string(type_name())));
  16487. }
  16488. /// get a pointer to the value (object)
  16489. object_t* get_impl_ptr(object_t* /*unused*/) noexcept
  16490. {
  16491. return is_object() ? m_value.object : nullptr;
  16492. }
  16493. /// get a pointer to the value (object)
  16494. constexpr const object_t* get_impl_ptr(const object_t* /*unused*/) const noexcept
  16495. {
  16496. return is_object() ? m_value.object : nullptr;
  16497. }
  16498. /// get a pointer to the value (array)
  16499. array_t* get_impl_ptr(array_t* /*unused*/) noexcept
  16500. {
  16501. return is_array() ? m_value.array : nullptr;
  16502. }
  16503. /// get a pointer to the value (array)
  16504. constexpr const array_t* get_impl_ptr(const array_t* /*unused*/) const noexcept
  16505. {
  16506. return is_array() ? m_value.array : nullptr;
  16507. }
  16508. /// get a pointer to the value (string)
  16509. string_t* get_impl_ptr(string_t* /*unused*/) noexcept
  16510. {
  16511. return is_string() ? m_value.string : nullptr;
  16512. }
  16513. /// get a pointer to the value (string)
  16514. constexpr const string_t* get_impl_ptr(const string_t* /*unused*/) const noexcept
  16515. {
  16516. return is_string() ? m_value.string : nullptr;
  16517. }
  16518. /// get a pointer to the value (boolean)
  16519. boolean_t* get_impl_ptr(boolean_t* /*unused*/) noexcept
  16520. {
  16521. return is_boolean() ? &m_value.boolean : nullptr;
  16522. }
  16523. /// get a pointer to the value (boolean)
  16524. constexpr const boolean_t* get_impl_ptr(const boolean_t* /*unused*/) const noexcept
  16525. {
  16526. return is_boolean() ? &m_value.boolean : nullptr;
  16527. }
  16528. /// get a pointer to the value (integer number)
  16529. number_integer_t* get_impl_ptr(number_integer_t* /*unused*/) noexcept
  16530. {
  16531. return is_number_integer() ? &m_value.number_integer : nullptr;
  16532. }
  16533. /// get a pointer to the value (integer number)
  16534. constexpr const number_integer_t* get_impl_ptr(const number_integer_t* /*unused*/) const noexcept
  16535. {
  16536. return is_number_integer() ? &m_value.number_integer : nullptr;
  16537. }
  16538. /// get a pointer to the value (unsigned number)
  16539. number_unsigned_t* get_impl_ptr(number_unsigned_t* /*unused*/) noexcept
  16540. {
  16541. return is_number_unsigned() ? &m_value.number_unsigned : nullptr;
  16542. }
  16543. /// get a pointer to the value (unsigned number)
  16544. constexpr const number_unsigned_t* get_impl_ptr(const number_unsigned_t* /*unused*/) const noexcept
  16545. {
  16546. return is_number_unsigned() ? &m_value.number_unsigned : nullptr;
  16547. }
  16548. /// get a pointer to the value (floating-point number)
  16549. number_float_t* get_impl_ptr(number_float_t* /*unused*/) noexcept
  16550. {
  16551. return is_number_float() ? &m_value.number_float : nullptr;
  16552. }
  16553. /// get a pointer to the value (floating-point number)
  16554. constexpr const number_float_t* get_impl_ptr(const number_float_t* /*unused*/) const noexcept
  16555. {
  16556. return is_number_float() ? &m_value.number_float : nullptr;
  16557. }
  16558. /// get a pointer to the value (binary)
  16559. binary_t* get_impl_ptr(binary_t* /*unused*/) noexcept
  16560. {
  16561. return is_binary() ? m_value.binary : nullptr;
  16562. }
  16563. /// get a pointer to the value (binary)
  16564. constexpr const binary_t* get_impl_ptr(const binary_t* /*unused*/) const noexcept
  16565. {
  16566. return is_binary() ? m_value.binary : nullptr;
  16567. }
  16568. /*!
  16569. @brief helper function to implement get_ref()
  16570. This function helps to implement get_ref() without code duplication for
  16571. const and non-const overloads
  16572. @tparam ThisType will be deduced as `basic_json` or `const basic_json`
  16573. @throw type_error.303 if ReferenceType does not match underlying value
  16574. type of the current JSON
  16575. */
  16576. template<typename ReferenceType, typename ThisType>
  16577. static ReferenceType get_ref_impl(ThisType& obj)
  16578. {
  16579. // delegate the call to get_ptr<>()
  16580. auto ptr = obj.template get_ptr<typename std::add_pointer<ReferenceType>::type>();
  16581. if (JSON_HEDLEY_LIKELY(ptr != nullptr))
  16582. {
  16583. return *ptr;
  16584. }
  16585. JSON_THROW(type_error::create(303, "incompatible ReferenceType for get_ref, actual type is " + std::string(obj.type_name())));
  16586. }
  16587. public:
  16588. /// @name value access
  16589. /// Direct access to the stored value of a JSON value.
  16590. /// @{
  16591. /*!
  16592. @brief get special-case overload
  16593. This overloads avoids a lot of template boilerplate, it can be seen as the
  16594. identity method
  16595. @tparam BasicJsonType == @ref basic_json
  16596. @return a copy of *this
  16597. @complexity Constant.
  16598. @since version 2.1.0
  16599. */
  16600. template<typename BasicJsonType, detail::enable_if_t<
  16601. std::is_same<typename std::remove_const<BasicJsonType>::type, basic_json_t>::value,
  16602. int> = 0>
  16603. basic_json get() const
  16604. {
  16605. return *this;
  16606. }
  16607. /*!
  16608. @brief get special-case overload
  16609. This overloads converts the current @ref basic_json in a different
  16610. @ref basic_json type
  16611. @tparam BasicJsonType == @ref basic_json
  16612. @return a copy of *this, converted into @tparam BasicJsonType
  16613. @complexity Depending on the implementation of the called `from_json()`
  16614. method.
  16615. @since version 3.2.0
  16616. */
  16617. template < typename BasicJsonType, detail::enable_if_t <
  16618. !std::is_same<BasicJsonType, basic_json>::value&&
  16619. detail::is_basic_json<BasicJsonType>::value, int > = 0 >
  16620. BasicJsonType get() const
  16621. {
  16622. return *this;
  16623. }
  16624. /*!
  16625. @brief get a value (explicit)
  16626. Explicit type conversion between the JSON value and a compatible value
  16627. which is [CopyConstructible](https://en.cppreference.com/w/cpp/named_req/CopyConstructible)
  16628. and [DefaultConstructible](https://en.cppreference.com/w/cpp/named_req/DefaultConstructible).
  16629. The value is converted by calling the @ref json_serializer<ValueType>
  16630. `from_json()` method.
  16631. The function is equivalent to executing
  16632. @code {.cpp}
  16633. ValueType ret;
  16634. JSONSerializer<ValueType>::from_json(*this, ret);
  16635. return ret;
  16636. @endcode
  16637. This overloads is chosen if:
  16638. - @a ValueType is not @ref basic_json,
  16639. - @ref json_serializer<ValueType> has a `from_json()` method of the form
  16640. `void from_json(const basic_json&, ValueType&)`, and
  16641. - @ref json_serializer<ValueType> does not have a `from_json()` method of
  16642. the form `ValueType from_json(const basic_json&)`
  16643. @tparam ValueTypeCV the provided value type
  16644. @tparam ValueType the returned value type
  16645. @return copy of the JSON value, converted to @a ValueType
  16646. @throw what @ref json_serializer<ValueType> `from_json()` method throws
  16647. @liveexample{The example below shows several conversions from JSON values
  16648. to other types. There a few things to note: (1) Floating-point numbers can
  16649. be converted to integers\, (2) A JSON array can be converted to a standard
  16650. `std::vector<short>`\, (3) A JSON object can be converted to C++
  16651. associative containers such as `std::unordered_map<std::string\,
  16652. json>`.,get__ValueType_const}
  16653. @since version 2.1.0
  16654. */
  16655. template < typename ValueTypeCV, typename ValueType = detail::uncvref_t<ValueTypeCV>,
  16656. detail::enable_if_t <
  16657. !detail::is_basic_json<ValueType>::value &&
  16658. detail::has_from_json<basic_json_t, ValueType>::value &&
  16659. !detail::has_non_default_from_json<basic_json_t, ValueType>::value,
  16660. int > = 0 >
  16661. ValueType get() const noexcept(noexcept(
  16662. JSONSerializer<ValueType>::from_json(std::declval<const basic_json_t&>(), std::declval<ValueType&>())))
  16663. {
  16664. // we cannot static_assert on ValueTypeCV being non-const, because
  16665. // there is support for get<const basic_json_t>(), which is why we
  16666. // still need the uncvref
  16667. static_assert(!std::is_reference<ValueTypeCV>::value,
  16668. "get() cannot be used with reference types, you might want to use get_ref()");
  16669. static_assert(std::is_default_constructible<ValueType>::value,
  16670. "types must be DefaultConstructible when used with get()");
  16671. ValueType ret;
  16672. JSONSerializer<ValueType>::from_json(*this, ret);
  16673. return ret;
  16674. }
  16675. /*!
  16676. @brief get a value (explicit); special case
  16677. Explicit type conversion between the JSON value and a compatible value
  16678. which is **not** [CopyConstructible](https://en.cppreference.com/w/cpp/named_req/CopyConstructible)
  16679. and **not** [DefaultConstructible](https://en.cppreference.com/w/cpp/named_req/DefaultConstructible).
  16680. The value is converted by calling the @ref json_serializer<ValueType>
  16681. `from_json()` method.
  16682. The function is equivalent to executing
  16683. @code {.cpp}
  16684. return JSONSerializer<ValueTypeCV>::from_json(*this);
  16685. @endcode
  16686. This overloads is chosen if:
  16687. - @a ValueType is not @ref basic_json and
  16688. - @ref json_serializer<ValueType> has a `from_json()` method of the form
  16689. `ValueType from_json(const basic_json&)`
  16690. @note If @ref json_serializer<ValueType> has both overloads of
  16691. `from_json()`, this one is chosen.
  16692. @tparam ValueTypeCV the provided value type
  16693. @tparam ValueType the returned value type
  16694. @return copy of the JSON value, converted to @a ValueType
  16695. @throw what @ref json_serializer<ValueType> `from_json()` method throws
  16696. @since version 2.1.0
  16697. */
  16698. template < typename ValueTypeCV, typename ValueType = detail::uncvref_t<ValueTypeCV>,
  16699. detail::enable_if_t < !std::is_same<basic_json_t, ValueType>::value &&
  16700. detail::has_non_default_from_json<basic_json_t, ValueType>::value,
  16701. int > = 0 >
  16702. ValueType get() const noexcept(noexcept(
  16703. JSONSerializer<ValueType>::from_json(std::declval<const basic_json_t&>())))
  16704. {
  16705. static_assert(!std::is_reference<ValueTypeCV>::value,
  16706. "get() cannot be used with reference types, you might want to use get_ref()");
  16707. return JSONSerializer<ValueType>::from_json(*this);
  16708. }
  16709. /*!
  16710. @brief get a value (explicit)
  16711. Explicit type conversion between the JSON value and a compatible value.
  16712. The value is filled into the input parameter by calling the @ref json_serializer<ValueType>
  16713. `from_json()` method.
  16714. The function is equivalent to executing
  16715. @code {.cpp}
  16716. ValueType v;
  16717. JSONSerializer<ValueType>::from_json(*this, v);
  16718. @endcode
  16719. This overloads is chosen if:
  16720. - @a ValueType is not @ref basic_json,
  16721. - @ref json_serializer<ValueType> has a `from_json()` method of the form
  16722. `void from_json(const basic_json&, ValueType&)`, and
  16723. @tparam ValueType the input parameter type.
  16724. @return the input parameter, allowing chaining calls.
  16725. @throw what @ref json_serializer<ValueType> `from_json()` method throws
  16726. @liveexample{The example below shows several conversions from JSON values
  16727. to other types. There a few things to note: (1) Floating-point numbers can
  16728. be converted to integers\, (2) A JSON array can be converted to a standard
  16729. `std::vector<short>`\, (3) A JSON object can be converted to C++
  16730. associative containers such as `std::unordered_map<std::string\,
  16731. json>`.,get_to}
  16732. @since version 3.3.0
  16733. */
  16734. template < typename ValueType,
  16735. detail::enable_if_t <
  16736. !detail::is_basic_json<ValueType>::value&&
  16737. detail::has_from_json<basic_json_t, ValueType>::value,
  16738. int > = 0 >
  16739. ValueType & get_to(ValueType& v) const noexcept(noexcept(
  16740. JSONSerializer<ValueType>::from_json(std::declval<const basic_json_t&>(), v)))
  16741. {
  16742. JSONSerializer<ValueType>::from_json(*this, v);
  16743. return v;
  16744. }
  16745. // specialization to allow to call get_to with a basic_json value
  16746. // see https://github.com/nlohmann/json/issues/2175
  16747. template<typename ValueType,
  16748. detail::enable_if_t <
  16749. detail::is_basic_json<ValueType>::value,
  16750. int> = 0>
  16751. ValueType & get_to(ValueType& v) const
  16752. {
  16753. v = *this;
  16754. return v;
  16755. }
  16756. template <
  16757. typename T, std::size_t N,
  16758. typename Array = T (&)[N],
  16759. detail::enable_if_t <
  16760. detail::has_from_json<basic_json_t, Array>::value, int > = 0 >
  16761. Array get_to(T (&v)[N]) const
  16762. noexcept(noexcept(JSONSerializer<Array>::from_json(
  16763. std::declval<const basic_json_t&>(), v)))
  16764. {
  16765. JSONSerializer<Array>::from_json(*this, v);
  16766. return v;
  16767. }
  16768. /*!
  16769. @brief get a pointer value (implicit)
  16770. Implicit pointer access to the internally stored JSON value. No copies are
  16771. made.
  16772. @warning Writing data to the pointee of the result yields an undefined
  16773. state.
  16774. @tparam PointerType pointer type; must be a pointer to @ref array_t, @ref
  16775. object_t, @ref string_t, @ref boolean_t, @ref number_integer_t,
  16776. @ref number_unsigned_t, or @ref number_float_t. Enforced by a static
  16777. assertion.
  16778. @return pointer to the internally stored JSON value if the requested
  16779. pointer type @a PointerType fits to the JSON value; `nullptr` otherwise
  16780. @complexity Constant.
  16781. @liveexample{The example below shows how pointers to internal values of a
  16782. JSON value can be requested. Note that no type conversions are made and a
  16783. `nullptr` is returned if the value and the requested pointer type does not
  16784. match.,get_ptr}
  16785. @since version 1.0.0
  16786. */
  16787. template<typename PointerType, typename std::enable_if<
  16788. std::is_pointer<PointerType>::value, int>::type = 0>
  16789. auto get_ptr() noexcept -> decltype(std::declval<basic_json_t&>().get_impl_ptr(std::declval<PointerType>()))
  16790. {
  16791. // delegate the call to get_impl_ptr<>()
  16792. return get_impl_ptr(static_cast<PointerType>(nullptr));
  16793. }
  16794. /*!
  16795. @brief get a pointer value (implicit)
  16796. @copydoc get_ptr()
  16797. */
  16798. template < typename PointerType, typename std::enable_if <
  16799. std::is_pointer<PointerType>::value&&
  16800. std::is_const<typename std::remove_pointer<PointerType>::type>::value, int >::type = 0 >
  16801. constexpr auto get_ptr() const noexcept -> decltype(std::declval<const basic_json_t&>().get_impl_ptr(std::declval<PointerType>()))
  16802. {
  16803. // delegate the call to get_impl_ptr<>() const
  16804. return get_impl_ptr(static_cast<PointerType>(nullptr));
  16805. }
  16806. /*!
  16807. @brief get a pointer value (explicit)
  16808. Explicit pointer access to the internally stored JSON value. No copies are
  16809. made.
  16810. @warning The pointer becomes invalid if the underlying JSON object
  16811. changes.
  16812. @tparam PointerType pointer type; must be a pointer to @ref array_t, @ref
  16813. object_t, @ref string_t, @ref boolean_t, @ref number_integer_t,
  16814. @ref number_unsigned_t, or @ref number_float_t.
  16815. @return pointer to the internally stored JSON value if the requested
  16816. pointer type @a PointerType fits to the JSON value; `nullptr` otherwise
  16817. @complexity Constant.
  16818. @liveexample{The example below shows how pointers to internal values of a
  16819. JSON value can be requested. Note that no type conversions are made and a
  16820. `nullptr` is returned if the value and the requested pointer type does not
  16821. match.,get__PointerType}
  16822. @sa @ref get_ptr() for explicit pointer-member access
  16823. @since version 1.0.0
  16824. */
  16825. template<typename PointerType, typename std::enable_if<
  16826. std::is_pointer<PointerType>::value, int>::type = 0>
  16827. auto get() noexcept -> decltype(std::declval<basic_json_t&>().template get_ptr<PointerType>())
  16828. {
  16829. // delegate the call to get_ptr
  16830. return get_ptr<PointerType>();
  16831. }
  16832. /*!
  16833. @brief get a pointer value (explicit)
  16834. @copydoc get()
  16835. */
  16836. template<typename PointerType, typename std::enable_if<
  16837. std::is_pointer<PointerType>::value, int>::type = 0>
  16838. constexpr auto get() const noexcept -> decltype(std::declval<const basic_json_t&>().template get_ptr<PointerType>())
  16839. {
  16840. // delegate the call to get_ptr
  16841. return get_ptr<PointerType>();
  16842. }
  16843. /*!
  16844. @brief get a reference value (implicit)
  16845. Implicit reference access to the internally stored JSON value. No copies
  16846. are made.
  16847. @warning Writing data to the referee of the result yields an undefined
  16848. state.
  16849. @tparam ReferenceType reference type; must be a reference to @ref array_t,
  16850. @ref object_t, @ref string_t, @ref boolean_t, @ref number_integer_t, or
  16851. @ref number_float_t. Enforced by static assertion.
  16852. @return reference to the internally stored JSON value if the requested
  16853. reference type @a ReferenceType fits to the JSON value; throws
  16854. type_error.303 otherwise
  16855. @throw type_error.303 in case passed type @a ReferenceType is incompatible
  16856. with the stored JSON value; see example below
  16857. @complexity Constant.
  16858. @liveexample{The example shows several calls to `get_ref()`.,get_ref}
  16859. @since version 1.1.0
  16860. */
  16861. template<typename ReferenceType, typename std::enable_if<
  16862. std::is_reference<ReferenceType>::value, int>::type = 0>
  16863. ReferenceType get_ref()
  16864. {
  16865. // delegate call to get_ref_impl
  16866. return get_ref_impl<ReferenceType>(*this);
  16867. }
  16868. /*!
  16869. @brief get a reference value (implicit)
  16870. @copydoc get_ref()
  16871. */
  16872. template < typename ReferenceType, typename std::enable_if <
  16873. std::is_reference<ReferenceType>::value&&
  16874. std::is_const<typename std::remove_reference<ReferenceType>::type>::value, int >::type = 0 >
  16875. ReferenceType get_ref() const
  16876. {
  16877. // delegate call to get_ref_impl
  16878. return get_ref_impl<ReferenceType>(*this);
  16879. }
  16880. /*!
  16881. @brief get a value (implicit)
  16882. Implicit type conversion between the JSON value and a compatible value.
  16883. The call is realized by calling @ref get() const.
  16884. @tparam ValueType non-pointer type compatible to the JSON value, for
  16885. instance `int` for JSON integer numbers, `bool` for JSON booleans, or
  16886. `std::vector` types for JSON arrays. The character type of @ref string_t
  16887. as well as an initializer list of this type is excluded to avoid
  16888. ambiguities as these types implicitly convert to `std::string`.
  16889. @return copy of the JSON value, converted to type @a ValueType
  16890. @throw type_error.302 in case passed type @a ValueType is incompatible
  16891. to the JSON value type (e.g., the JSON value is of type boolean, but a
  16892. string is requested); see example below
  16893. @complexity Linear in the size of the JSON value.
  16894. @liveexample{The example below shows several conversions from JSON values
  16895. to other types. There a few things to note: (1) Floating-point numbers can
  16896. be converted to integers\, (2) A JSON array can be converted to a standard
  16897. `std::vector<short>`\, (3) A JSON object can be converted to C++
  16898. associative containers such as `std::unordered_map<std::string\,
  16899. json>`.,operator__ValueType}
  16900. @since version 1.0.0
  16901. */
  16902. template < typename ValueType, typename std::enable_if <
  16903. !std::is_pointer<ValueType>::value&&
  16904. !std::is_same<ValueType, detail::json_ref<basic_json>>::value&&
  16905. !std::is_same<ValueType, typename string_t::value_type>::value&&
  16906. !detail::is_basic_json<ValueType>::value
  16907. && !std::is_same<ValueType, std::initializer_list<typename string_t::value_type>>::value
  16908. #if defined(JSON_HAS_CPP_17) && (defined(__GNUC__) || (defined(_MSC_VER) && _MSC_VER >= 1910 && _MSC_VER <= 1914))
  16909. && !std::is_same<ValueType, typename std::string_view>::value
  16910. #endif
  16911. && detail::is_detected<detail::get_template_function, const basic_json_t&, ValueType>::value
  16912. , int >::type = 0 >
  16913. JSON_EXPLICIT operator ValueType() const
  16914. {
  16915. // delegate the call to get<>() const
  16916. return get<ValueType>();
  16917. }
  16918. /*!
  16919. @return reference to the binary value
  16920. @throw type_error.302 if the value is not binary
  16921. @sa @ref is_binary() to check if the value is binary
  16922. @since version 3.8.0
  16923. */
  16924. binary_t& get_binary()
  16925. {
  16926. if (!is_binary())
  16927. {
  16928. JSON_THROW(type_error::create(302, "type must be binary, but is " + std::string(type_name())));
  16929. }
  16930. return *get_ptr<binary_t*>();
  16931. }
  16932. /// @copydoc get_binary()
  16933. const binary_t& get_binary() const
  16934. {
  16935. if (!is_binary())
  16936. {
  16937. JSON_THROW(type_error::create(302, "type must be binary, but is " + std::string(type_name())));
  16938. }
  16939. return *get_ptr<const binary_t*>();
  16940. }
  16941. /// @}
  16942. ////////////////////
  16943. // element access //
  16944. ////////////////////
  16945. /// @name element access
  16946. /// Access to the JSON value.
  16947. /// @{
  16948. /*!
  16949. @brief access specified array element with bounds checking
  16950. Returns a reference to the element at specified location @a idx, with
  16951. bounds checking.
  16952. @param[in] idx index of the element to access
  16953. @return reference to the element at index @a idx
  16954. @throw type_error.304 if the JSON value is not an array; in this case,
  16955. calling `at` with an index makes no sense. See example below.
  16956. @throw out_of_range.401 if the index @a idx is out of range of the array;
  16957. that is, `idx >= size()`. See example below.
  16958. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  16959. changes in the JSON value.
  16960. @complexity Constant.
  16961. @since version 1.0.0
  16962. @liveexample{The example below shows how array elements can be read and
  16963. written using `at()`. It also demonstrates the different exceptions that
  16964. can be thrown.,at__size_type}
  16965. */
  16966. reference at(size_type idx)
  16967. {
  16968. // at only works for arrays
  16969. if (JSON_HEDLEY_LIKELY(is_array()))
  16970. {
  16971. JSON_TRY
  16972. {
  16973. return m_value.array->at(idx);
  16974. }
  16975. JSON_CATCH (std::out_of_range&)
  16976. {
  16977. // create better exception explanation
  16978. JSON_THROW(out_of_range::create(401, "array index " + std::to_string(idx) + " is out of range"));
  16979. }
  16980. }
  16981. else
  16982. {
  16983. JSON_THROW(type_error::create(304, "cannot use at() with " + std::string(type_name())));
  16984. }
  16985. }
  16986. /*!
  16987. @brief access specified array element with bounds checking
  16988. Returns a const reference to the element at specified location @a idx,
  16989. with bounds checking.
  16990. @param[in] idx index of the element to access
  16991. @return const reference to the element at index @a idx
  16992. @throw type_error.304 if the JSON value is not an array; in this case,
  16993. calling `at` with an index makes no sense. See example below.
  16994. @throw out_of_range.401 if the index @a idx is out of range of the array;
  16995. that is, `idx >= size()`. See example below.
  16996. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  16997. changes in the JSON value.
  16998. @complexity Constant.
  16999. @since version 1.0.0
  17000. @liveexample{The example below shows how array elements can be read using
  17001. `at()`. It also demonstrates the different exceptions that can be thrown.,
  17002. at__size_type_const}
  17003. */
  17004. const_reference at(size_type idx) const
  17005. {
  17006. // at only works for arrays
  17007. if (JSON_HEDLEY_LIKELY(is_array()))
  17008. {
  17009. JSON_TRY
  17010. {
  17011. return m_value.array->at(idx);
  17012. }
  17013. JSON_CATCH (std::out_of_range&)
  17014. {
  17015. // create better exception explanation
  17016. JSON_THROW(out_of_range::create(401, "array index " + std::to_string(idx) + " is out of range"));
  17017. }
  17018. }
  17019. else
  17020. {
  17021. JSON_THROW(type_error::create(304, "cannot use at() with " + std::string(type_name())));
  17022. }
  17023. }
  17024. /*!
  17025. @brief access specified object element with bounds checking
  17026. Returns a reference to the element at with specified key @a key, with
  17027. bounds checking.
  17028. @param[in] key key of the element to access
  17029. @return reference to the element at key @a key
  17030. @throw type_error.304 if the JSON value is not an object; in this case,
  17031. calling `at` with a key makes no sense. See example below.
  17032. @throw out_of_range.403 if the key @a key is is not stored in the object;
  17033. that is, `find(key) == end()`. See example below.
  17034. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  17035. changes in the JSON value.
  17036. @complexity Logarithmic in the size of the container.
  17037. @sa @ref operator[](const typename object_t::key_type&) for unchecked
  17038. access by reference
  17039. @sa @ref value() for access by value with a default value
  17040. @since version 1.0.0
  17041. @liveexample{The example below shows how object elements can be read and
  17042. written using `at()`. It also demonstrates the different exceptions that
  17043. can be thrown.,at__object_t_key_type}
  17044. */
  17045. reference at(const typename object_t::key_type& key)
  17046. {
  17047. // at only works for objects
  17048. if (JSON_HEDLEY_LIKELY(is_object()))
  17049. {
  17050. JSON_TRY
  17051. {
  17052. return m_value.object->at(key);
  17053. }
  17054. JSON_CATCH (std::out_of_range&)
  17055. {
  17056. // create better exception explanation
  17057. JSON_THROW(out_of_range::create(403, "key '" + key + "' not found"));
  17058. }
  17059. }
  17060. else
  17061. {
  17062. JSON_THROW(type_error::create(304, "cannot use at() with " + std::string(type_name())));
  17063. }
  17064. }
  17065. /*!
  17066. @brief access specified object element with bounds checking
  17067. Returns a const reference to the element at with specified key @a key,
  17068. with bounds checking.
  17069. @param[in] key key of the element to access
  17070. @return const reference to the element at key @a key
  17071. @throw type_error.304 if the JSON value is not an object; in this case,
  17072. calling `at` with a key makes no sense. See example below.
  17073. @throw out_of_range.403 if the key @a key is is not stored in the object;
  17074. that is, `find(key) == end()`. See example below.
  17075. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  17076. changes in the JSON value.
  17077. @complexity Logarithmic in the size of the container.
  17078. @sa @ref operator[](const typename object_t::key_type&) for unchecked
  17079. access by reference
  17080. @sa @ref value() for access by value with a default value
  17081. @since version 1.0.0
  17082. @liveexample{The example below shows how object elements can be read using
  17083. `at()`. It also demonstrates the different exceptions that can be thrown.,
  17084. at__object_t_key_type_const}
  17085. */
  17086. const_reference at(const typename object_t::key_type& key) const
  17087. {
  17088. // at only works for objects
  17089. if (JSON_HEDLEY_LIKELY(is_object()))
  17090. {
  17091. JSON_TRY
  17092. {
  17093. return m_value.object->at(key);
  17094. }
  17095. JSON_CATCH (std::out_of_range&)
  17096. {
  17097. // create better exception explanation
  17098. JSON_THROW(out_of_range::create(403, "key '" + key + "' not found"));
  17099. }
  17100. }
  17101. else
  17102. {
  17103. JSON_THROW(type_error::create(304, "cannot use at() with " + std::string(type_name())));
  17104. }
  17105. }
  17106. /*!
  17107. @brief access specified array element
  17108. Returns a reference to the element at specified location @a idx.
  17109. @note If @a idx is beyond the range of the array (i.e., `idx >= size()`),
  17110. then the array is silently filled up with `null` values to make `idx` a
  17111. valid reference to the last stored element.
  17112. @param[in] idx index of the element to access
  17113. @return reference to the element at index @a idx
  17114. @throw type_error.305 if the JSON value is not an array or null; in that
  17115. cases, using the [] operator with an index makes no sense.
  17116. @complexity Constant if @a idx is in the range of the array. Otherwise
  17117. linear in `idx - size()`.
  17118. @liveexample{The example below shows how array elements can be read and
  17119. written using `[]` operator. Note the addition of `null`
  17120. values.,operatorarray__size_type}
  17121. @since version 1.0.0
  17122. */
  17123. reference operator[](size_type idx)
  17124. {
  17125. // implicitly convert null value to an empty array
  17126. if (is_null())
  17127. {
  17128. m_type = value_t::array;
  17129. m_value.array = create<array_t>();
  17130. assert_invariant();
  17131. }
  17132. // operator[] only works for arrays
  17133. if (JSON_HEDLEY_LIKELY(is_array()))
  17134. {
  17135. // fill up array with null values if given idx is outside range
  17136. if (idx >= m_value.array->size())
  17137. {
  17138. m_value.array->insert(m_value.array->end(),
  17139. idx - m_value.array->size() + 1,
  17140. basic_json());
  17141. }
  17142. return m_value.array->operator[](idx);
  17143. }
  17144. JSON_THROW(type_error::create(305, "cannot use operator[] with a numeric argument with " + std::string(type_name())));
  17145. }
  17146. /*!
  17147. @brief access specified array element
  17148. Returns a const reference to the element at specified location @a idx.
  17149. @param[in] idx index of the element to access
  17150. @return const reference to the element at index @a idx
  17151. @throw type_error.305 if the JSON value is not an array; in that case,
  17152. using the [] operator with an index makes no sense.
  17153. @complexity Constant.
  17154. @liveexample{The example below shows how array elements can be read using
  17155. the `[]` operator.,operatorarray__size_type_const}
  17156. @since version 1.0.0
  17157. */
  17158. const_reference operator[](size_type idx) const
  17159. {
  17160. // const operator[] only works for arrays
  17161. if (JSON_HEDLEY_LIKELY(is_array()))
  17162. {
  17163. return m_value.array->operator[](idx);
  17164. }
  17165. JSON_THROW(type_error::create(305, "cannot use operator[] with a numeric argument with " + std::string(type_name())));
  17166. }
  17167. /*!
  17168. @brief access specified object element
  17169. Returns a reference to the element at with specified key @a key.
  17170. @note If @a key is not found in the object, then it is silently added to
  17171. the object and filled with a `null` value to make `key` a valid reference.
  17172. In case the value was `null` before, it is converted to an object.
  17173. @param[in] key key of the element to access
  17174. @return reference to the element at key @a key
  17175. @throw type_error.305 if the JSON value is not an object or null; in that
  17176. cases, using the [] operator with a key makes no sense.
  17177. @complexity Logarithmic in the size of the container.
  17178. @liveexample{The example below shows how object elements can be read and
  17179. written using the `[]` operator.,operatorarray__key_type}
  17180. @sa @ref at(const typename object_t::key_type&) for access by reference
  17181. with range checking
  17182. @sa @ref value() for access by value with a default value
  17183. @since version 1.0.0
  17184. */
  17185. reference operator[](const typename object_t::key_type& key)
  17186. {
  17187. // implicitly convert null value to an empty object
  17188. if (is_null())
  17189. {
  17190. m_type = value_t::object;
  17191. m_value.object = create<object_t>();
  17192. assert_invariant();
  17193. }
  17194. // operator[] only works for objects
  17195. if (JSON_HEDLEY_LIKELY(is_object()))
  17196. {
  17197. return m_value.object->operator[](key);
  17198. }
  17199. JSON_THROW(type_error::create(305, "cannot use operator[] with a string argument with " + std::string(type_name())));
  17200. }
  17201. /*!
  17202. @brief read-only access specified object element
  17203. Returns a const reference to the element at with specified key @a key. No
  17204. bounds checking is performed.
  17205. @warning If the element with key @a key does not exist, the behavior is
  17206. undefined.
  17207. @param[in] key key of the element to access
  17208. @return const reference to the element at key @a key
  17209. @pre The element with key @a key must exist. **This precondition is
  17210. enforced with an assertion.**
  17211. @throw type_error.305 if the JSON value is not an object; in that case,
  17212. using the [] operator with a key makes no sense.
  17213. @complexity Logarithmic in the size of the container.
  17214. @liveexample{The example below shows how object elements can be read using
  17215. the `[]` operator.,operatorarray__key_type_const}
  17216. @sa @ref at(const typename object_t::key_type&) for access by reference
  17217. with range checking
  17218. @sa @ref value() for access by value with a default value
  17219. @since version 1.0.0
  17220. */
  17221. const_reference operator[](const typename object_t::key_type& key) const
  17222. {
  17223. // const operator[] only works for objects
  17224. if (JSON_HEDLEY_LIKELY(is_object()))
  17225. {
  17226. JSON_ASSERT(m_value.object->find(key) != m_value.object->end());
  17227. return m_value.object->find(key)->second;
  17228. }
  17229. JSON_THROW(type_error::create(305, "cannot use operator[] with a string argument with " + std::string(type_name())));
  17230. }
  17231. /*!
  17232. @brief access specified object element
  17233. Returns a reference to the element at with specified key @a key.
  17234. @note If @a key is not found in the object, then it is silently added to
  17235. the object and filled with a `null` value to make `key` a valid reference.
  17236. In case the value was `null` before, it is converted to an object.
  17237. @param[in] key key of the element to access
  17238. @return reference to the element at key @a key
  17239. @throw type_error.305 if the JSON value is not an object or null; in that
  17240. cases, using the [] operator with a key makes no sense.
  17241. @complexity Logarithmic in the size of the container.
  17242. @liveexample{The example below shows how object elements can be read and
  17243. written using the `[]` operator.,operatorarray__key_type}
  17244. @sa @ref at(const typename object_t::key_type&) for access by reference
  17245. with range checking
  17246. @sa @ref value() for access by value with a default value
  17247. @since version 1.1.0
  17248. */
  17249. template<typename T>
  17250. JSON_HEDLEY_NON_NULL(2)
  17251. reference operator[](T* key)
  17252. {
  17253. // implicitly convert null to object
  17254. if (is_null())
  17255. {
  17256. m_type = value_t::object;
  17257. m_value = value_t::object;
  17258. assert_invariant();
  17259. }
  17260. // at only works for objects
  17261. if (JSON_HEDLEY_LIKELY(is_object()))
  17262. {
  17263. return m_value.object->operator[](key);
  17264. }
  17265. JSON_THROW(type_error::create(305, "cannot use operator[] with a string argument with " + std::string(type_name())));
  17266. }
  17267. /*!
  17268. @brief read-only access specified object element
  17269. Returns a const reference to the element at with specified key @a key. No
  17270. bounds checking is performed.
  17271. @warning If the element with key @a key does not exist, the behavior is
  17272. undefined.
  17273. @param[in] key key of the element to access
  17274. @return const reference to the element at key @a key
  17275. @pre The element with key @a key must exist. **This precondition is
  17276. enforced with an assertion.**
  17277. @throw type_error.305 if the JSON value is not an object; in that case,
  17278. using the [] operator with a key makes no sense.
  17279. @complexity Logarithmic in the size of the container.
  17280. @liveexample{The example below shows how object elements can be read using
  17281. the `[]` operator.,operatorarray__key_type_const}
  17282. @sa @ref at(const typename object_t::key_type&) for access by reference
  17283. with range checking
  17284. @sa @ref value() for access by value with a default value
  17285. @since version 1.1.0
  17286. */
  17287. template<typename T>
  17288. JSON_HEDLEY_NON_NULL(2)
  17289. const_reference operator[](T* key) const
  17290. {
  17291. // at only works for objects
  17292. if (JSON_HEDLEY_LIKELY(is_object()))
  17293. {
  17294. JSON_ASSERT(m_value.object->find(key) != m_value.object->end());
  17295. return m_value.object->find(key)->second;
  17296. }
  17297. JSON_THROW(type_error::create(305, "cannot use operator[] with a string argument with " + std::string(type_name())));
  17298. }
  17299. /*!
  17300. @brief access specified object element with default value
  17301. Returns either a copy of an object's element at the specified key @a key
  17302. or a given default value if no element with key @a key exists.
  17303. The function is basically equivalent to executing
  17304. @code {.cpp}
  17305. try {
  17306. return at(key);
  17307. } catch(out_of_range) {
  17308. return default_value;
  17309. }
  17310. @endcode
  17311. @note Unlike @ref at(const typename object_t::key_type&), this function
  17312. does not throw if the given key @a key was not found.
  17313. @note Unlike @ref operator[](const typename object_t::key_type& key), this
  17314. function does not implicitly add an element to the position defined by @a
  17315. key. This function is furthermore also applicable to const objects.
  17316. @param[in] key key of the element to access
  17317. @param[in] default_value the value to return if @a key is not found
  17318. @tparam ValueType type compatible to JSON values, for instance `int` for
  17319. JSON integer numbers, `bool` for JSON booleans, or `std::vector` types for
  17320. JSON arrays. Note the type of the expected value at @a key and the default
  17321. value @a default_value must be compatible.
  17322. @return copy of the element at key @a key or @a default_value if @a key
  17323. is not found
  17324. @throw type_error.302 if @a default_value does not match the type of the
  17325. value at @a key
  17326. @throw type_error.306 if the JSON value is not an object; in that case,
  17327. using `value()` with a key makes no sense.
  17328. @complexity Logarithmic in the size of the container.
  17329. @liveexample{The example below shows how object elements can be queried
  17330. with a default value.,basic_json__value}
  17331. @sa @ref at(const typename object_t::key_type&) for access by reference
  17332. with range checking
  17333. @sa @ref operator[](const typename object_t::key_type&) for unchecked
  17334. access by reference
  17335. @since version 1.0.0
  17336. */
  17337. // using std::is_convertible in a std::enable_if will fail when using explicit conversions
  17338. template < class ValueType, typename std::enable_if <
  17339. detail::is_getable<basic_json_t, ValueType>::value
  17340. && !std::is_same<value_t, ValueType>::value, int >::type = 0 >
  17341. ValueType value(const typename object_t::key_type& key, const ValueType& default_value) const
  17342. {
  17343. // at only works for objects
  17344. if (JSON_HEDLEY_LIKELY(is_object()))
  17345. {
  17346. // if key is found, return value and given default value otherwise
  17347. const auto it = find(key);
  17348. if (it != end())
  17349. {
  17350. return it->template get<ValueType>();
  17351. }
  17352. return default_value;
  17353. }
  17354. JSON_THROW(type_error::create(306, "cannot use value() with " + std::string(type_name())));
  17355. }
  17356. /*!
  17357. @brief overload for a default value of type const char*
  17358. @copydoc basic_json::value(const typename object_t::key_type&, const ValueType&) const
  17359. */
  17360. string_t value(const typename object_t::key_type& key, const char* default_value) const
  17361. {
  17362. return value(key, string_t(default_value));
  17363. }
  17364. /*!
  17365. @brief access specified object element via JSON Pointer with default value
  17366. Returns either a copy of an object's element at the specified key @a key
  17367. or a given default value if no element with key @a key exists.
  17368. The function is basically equivalent to executing
  17369. @code {.cpp}
  17370. try {
  17371. return at(ptr);
  17372. } catch(out_of_range) {
  17373. return default_value;
  17374. }
  17375. @endcode
  17376. @note Unlike @ref at(const json_pointer&), this function does not throw
  17377. if the given key @a key was not found.
  17378. @param[in] ptr a JSON pointer to the element to access
  17379. @param[in] default_value the value to return if @a ptr found no value
  17380. @tparam ValueType type compatible to JSON values, for instance `int` for
  17381. JSON integer numbers, `bool` for JSON booleans, or `std::vector` types for
  17382. JSON arrays. Note the type of the expected value at @a key and the default
  17383. value @a default_value must be compatible.
  17384. @return copy of the element at key @a key or @a default_value if @a key
  17385. is not found
  17386. @throw type_error.302 if @a default_value does not match the type of the
  17387. value at @a ptr
  17388. @throw type_error.306 if the JSON value is not an object; in that case,
  17389. using `value()` with a key makes no sense.
  17390. @complexity Logarithmic in the size of the container.
  17391. @liveexample{The example below shows how object elements can be queried
  17392. with a default value.,basic_json__value_ptr}
  17393. @sa @ref operator[](const json_pointer&) for unchecked access by reference
  17394. @since version 2.0.2
  17395. */
  17396. template<class ValueType, typename std::enable_if<
  17397. detail::is_getable<basic_json_t, ValueType>::value, int>::type = 0>
  17398. ValueType value(const json_pointer& ptr, const ValueType& default_value) const
  17399. {
  17400. // at only works for objects
  17401. if (JSON_HEDLEY_LIKELY(is_object()))
  17402. {
  17403. // if pointer resolves a value, return it or use default value
  17404. JSON_TRY
  17405. {
  17406. return ptr.get_checked(this).template get<ValueType>();
  17407. }
  17408. JSON_INTERNAL_CATCH (out_of_range&)
  17409. {
  17410. return default_value;
  17411. }
  17412. }
  17413. JSON_THROW(type_error::create(306, "cannot use value() with " + std::string(type_name())));
  17414. }
  17415. /*!
  17416. @brief overload for a default value of type const char*
  17417. @copydoc basic_json::value(const json_pointer&, ValueType) const
  17418. */
  17419. JSON_HEDLEY_NON_NULL(3)
  17420. string_t value(const json_pointer& ptr, const char* default_value) const
  17421. {
  17422. return value(ptr, string_t(default_value));
  17423. }
  17424. /*!
  17425. @brief access the first element
  17426. Returns a reference to the first element in the container. For a JSON
  17427. container `c`, the expression `c.front()` is equivalent to `*c.begin()`.
  17428. @return In case of a structured type (array or object), a reference to the
  17429. first element is returned. In case of number, string, boolean, or binary
  17430. values, a reference to the value is returned.
  17431. @complexity Constant.
  17432. @pre The JSON value must not be `null` (would throw `std::out_of_range`)
  17433. or an empty array or object (undefined behavior, **guarded by
  17434. assertions**).
  17435. @post The JSON value remains unchanged.
  17436. @throw invalid_iterator.214 when called on `null` value
  17437. @liveexample{The following code shows an example for `front()`.,front}
  17438. @sa @ref back() -- access the last element
  17439. @since version 1.0.0
  17440. */
  17441. reference front()
  17442. {
  17443. return *begin();
  17444. }
  17445. /*!
  17446. @copydoc basic_json::front()
  17447. */
  17448. const_reference front() const
  17449. {
  17450. return *cbegin();
  17451. }
  17452. /*!
  17453. @brief access the last element
  17454. Returns a reference to the last element in the container. For a JSON
  17455. container `c`, the expression `c.back()` is equivalent to
  17456. @code {.cpp}
  17457. auto tmp = c.end();
  17458. --tmp;
  17459. return *tmp;
  17460. @endcode
  17461. @return In case of a structured type (array or object), a reference to the
  17462. last element is returned. In case of number, string, boolean, or binary
  17463. values, a reference to the value is returned.
  17464. @complexity Constant.
  17465. @pre The JSON value must not be `null` (would throw `std::out_of_range`)
  17466. or an empty array or object (undefined behavior, **guarded by
  17467. assertions**).
  17468. @post The JSON value remains unchanged.
  17469. @throw invalid_iterator.214 when called on a `null` value. See example
  17470. below.
  17471. @liveexample{The following code shows an example for `back()`.,back}
  17472. @sa @ref front() -- access the first element
  17473. @since version 1.0.0
  17474. */
  17475. reference back()
  17476. {
  17477. auto tmp = end();
  17478. --tmp;
  17479. return *tmp;
  17480. }
  17481. /*!
  17482. @copydoc basic_json::back()
  17483. */
  17484. const_reference back() const
  17485. {
  17486. auto tmp = cend();
  17487. --tmp;
  17488. return *tmp;
  17489. }
  17490. /*!
  17491. @brief remove element given an iterator
  17492. Removes the element specified by iterator @a pos. The iterator @a pos must
  17493. be valid and dereferenceable. Thus the `end()` iterator (which is valid,
  17494. but is not dereferenceable) cannot be used as a value for @a pos.
  17495. If called on a primitive type other than `null`, the resulting JSON value
  17496. will be `null`.
  17497. @param[in] pos iterator to the element to remove
  17498. @return Iterator following the last removed element. If the iterator @a
  17499. pos refers to the last element, the `end()` iterator is returned.
  17500. @tparam IteratorType an @ref iterator or @ref const_iterator
  17501. @post Invalidates iterators and references at or after the point of the
  17502. erase, including the `end()` iterator.
  17503. @throw type_error.307 if called on a `null` value; example: `"cannot use
  17504. erase() with null"`
  17505. @throw invalid_iterator.202 if called on an iterator which does not belong
  17506. to the current JSON value; example: `"iterator does not fit current
  17507. value"`
  17508. @throw invalid_iterator.205 if called on a primitive type with invalid
  17509. iterator (i.e., any iterator which is not `begin()`); example: `"iterator
  17510. out of range"`
  17511. @complexity The complexity depends on the type:
  17512. - objects: amortized constant
  17513. - arrays: linear in distance between @a pos and the end of the container
  17514. - strings and binary: linear in the length of the member
  17515. - other types: constant
  17516. @liveexample{The example shows the result of `erase()` for different JSON
  17517. types.,erase__IteratorType}
  17518. @sa @ref erase(IteratorType, IteratorType) -- removes the elements in
  17519. the given range
  17520. @sa @ref erase(const typename object_t::key_type&) -- removes the element
  17521. from an object at the given key
  17522. @sa @ref erase(const size_type) -- removes the element from an array at
  17523. the given index
  17524. @since version 1.0.0
  17525. */
  17526. template < class IteratorType, typename std::enable_if <
  17527. std::is_same<IteratorType, typename basic_json_t::iterator>::value ||
  17528. std::is_same<IteratorType, typename basic_json_t::const_iterator>::value, int >::type
  17529. = 0 >
  17530. IteratorType erase(IteratorType pos)
  17531. {
  17532. // make sure iterator fits the current value
  17533. if (JSON_HEDLEY_UNLIKELY(this != pos.m_object))
  17534. {
  17535. JSON_THROW(invalid_iterator::create(202, "iterator does not fit current value"));
  17536. }
  17537. IteratorType result = end();
  17538. switch (m_type)
  17539. {
  17540. case value_t::boolean:
  17541. case value_t::number_float:
  17542. case value_t::number_integer:
  17543. case value_t::number_unsigned:
  17544. case value_t::string:
  17545. case value_t::binary:
  17546. {
  17547. if (JSON_HEDLEY_UNLIKELY(!pos.m_it.primitive_iterator.is_begin()))
  17548. {
  17549. JSON_THROW(invalid_iterator::create(205, "iterator out of range"));
  17550. }
  17551. if (is_string())
  17552. {
  17553. AllocatorType<string_t> alloc;
  17554. std::allocator_traits<decltype(alloc)>::destroy(alloc, m_value.string);
  17555. std::allocator_traits<decltype(alloc)>::deallocate(alloc, m_value.string, 1);
  17556. m_value.string = nullptr;
  17557. }
  17558. else if (is_binary())
  17559. {
  17560. AllocatorType<binary_t> alloc;
  17561. std::allocator_traits<decltype(alloc)>::destroy(alloc, m_value.binary);
  17562. std::allocator_traits<decltype(alloc)>::deallocate(alloc, m_value.binary, 1);
  17563. m_value.binary = nullptr;
  17564. }
  17565. m_type = value_t::null;
  17566. assert_invariant();
  17567. break;
  17568. }
  17569. case value_t::object:
  17570. {
  17571. result.m_it.object_iterator = m_value.object->erase(pos.m_it.object_iterator);
  17572. break;
  17573. }
  17574. case value_t::array:
  17575. {
  17576. result.m_it.array_iterator = m_value.array->erase(pos.m_it.array_iterator);
  17577. break;
  17578. }
  17579. default:
  17580. JSON_THROW(type_error::create(307, "cannot use erase() with " + std::string(type_name())));
  17581. }
  17582. return result;
  17583. }
  17584. /*!
  17585. @brief remove elements given an iterator range
  17586. Removes the element specified by the range `[first; last)`. The iterator
  17587. @a first does not need to be dereferenceable if `first == last`: erasing
  17588. an empty range is a no-op.
  17589. If called on a primitive type other than `null`, the resulting JSON value
  17590. will be `null`.
  17591. @param[in] first iterator to the beginning of the range to remove
  17592. @param[in] last iterator past the end of the range to remove
  17593. @return Iterator following the last removed element. If the iterator @a
  17594. second refers to the last element, the `end()` iterator is returned.
  17595. @tparam IteratorType an @ref iterator or @ref const_iterator
  17596. @post Invalidates iterators and references at or after the point of the
  17597. erase, including the `end()` iterator.
  17598. @throw type_error.307 if called on a `null` value; example: `"cannot use
  17599. erase() with null"`
  17600. @throw invalid_iterator.203 if called on iterators which does not belong
  17601. to the current JSON value; example: `"iterators do not fit current value"`
  17602. @throw invalid_iterator.204 if called on a primitive type with invalid
  17603. iterators (i.e., if `first != begin()` and `last != end()`); example:
  17604. `"iterators out of range"`
  17605. @complexity The complexity depends on the type:
  17606. - objects: `log(size()) + std::distance(first, last)`
  17607. - arrays: linear in the distance between @a first and @a last, plus linear
  17608. in the distance between @a last and end of the container
  17609. - strings and binary: linear in the length of the member
  17610. - other types: constant
  17611. @liveexample{The example shows the result of `erase()` for different JSON
  17612. types.,erase__IteratorType_IteratorType}
  17613. @sa @ref erase(IteratorType) -- removes the element at a given position
  17614. @sa @ref erase(const typename object_t::key_type&) -- removes the element
  17615. from an object at the given key
  17616. @sa @ref erase(const size_type) -- removes the element from an array at
  17617. the given index
  17618. @since version 1.0.0
  17619. */
  17620. template < class IteratorType, typename std::enable_if <
  17621. std::is_same<IteratorType, typename basic_json_t::iterator>::value ||
  17622. std::is_same<IteratorType, typename basic_json_t::const_iterator>::value, int >::type
  17623. = 0 >
  17624. IteratorType erase(IteratorType first, IteratorType last)
  17625. {
  17626. // make sure iterator fits the current value
  17627. if (JSON_HEDLEY_UNLIKELY(this != first.m_object || this != last.m_object))
  17628. {
  17629. JSON_THROW(invalid_iterator::create(203, "iterators do not fit current value"));
  17630. }
  17631. IteratorType result = end();
  17632. switch (m_type)
  17633. {
  17634. case value_t::boolean:
  17635. case value_t::number_float:
  17636. case value_t::number_integer:
  17637. case value_t::number_unsigned:
  17638. case value_t::string:
  17639. case value_t::binary:
  17640. {
  17641. if (JSON_HEDLEY_LIKELY(!first.m_it.primitive_iterator.is_begin()
  17642. || !last.m_it.primitive_iterator.is_end()))
  17643. {
  17644. JSON_THROW(invalid_iterator::create(204, "iterators out of range"));
  17645. }
  17646. if (is_string())
  17647. {
  17648. AllocatorType<string_t> alloc;
  17649. std::allocator_traits<decltype(alloc)>::destroy(alloc, m_value.string);
  17650. std::allocator_traits<decltype(alloc)>::deallocate(alloc, m_value.string, 1);
  17651. m_value.string = nullptr;
  17652. }
  17653. else if (is_binary())
  17654. {
  17655. AllocatorType<binary_t> alloc;
  17656. std::allocator_traits<decltype(alloc)>::destroy(alloc, m_value.binary);
  17657. std::allocator_traits<decltype(alloc)>::deallocate(alloc, m_value.binary, 1);
  17658. m_value.binary = nullptr;
  17659. }
  17660. m_type = value_t::null;
  17661. assert_invariant();
  17662. break;
  17663. }
  17664. case value_t::object:
  17665. {
  17666. result.m_it.object_iterator = m_value.object->erase(first.m_it.object_iterator,
  17667. last.m_it.object_iterator);
  17668. break;
  17669. }
  17670. case value_t::array:
  17671. {
  17672. result.m_it.array_iterator = m_value.array->erase(first.m_it.array_iterator,
  17673. last.m_it.array_iterator);
  17674. break;
  17675. }
  17676. default:
  17677. JSON_THROW(type_error::create(307, "cannot use erase() with " + std::string(type_name())));
  17678. }
  17679. return result;
  17680. }
  17681. /*!
  17682. @brief remove element from a JSON object given a key
  17683. Removes elements from a JSON object with the key value @a key.
  17684. @param[in] key value of the elements to remove
  17685. @return Number of elements removed. If @a ObjectType is the default
  17686. `std::map` type, the return value will always be `0` (@a key was not
  17687. found) or `1` (@a key was found).
  17688. @post References and iterators to the erased elements are invalidated.
  17689. Other references and iterators are not affected.
  17690. @throw type_error.307 when called on a type other than JSON object;
  17691. example: `"cannot use erase() with null"`
  17692. @complexity `log(size()) + count(key)`
  17693. @liveexample{The example shows the effect of `erase()`.,erase__key_type}
  17694. @sa @ref erase(IteratorType) -- removes the element at a given position
  17695. @sa @ref erase(IteratorType, IteratorType) -- removes the elements in
  17696. the given range
  17697. @sa @ref erase(const size_type) -- removes the element from an array at
  17698. the given index
  17699. @since version 1.0.0
  17700. */
  17701. size_type erase(const typename object_t::key_type& key)
  17702. {
  17703. // this erase only works for objects
  17704. if (JSON_HEDLEY_LIKELY(is_object()))
  17705. {
  17706. return m_value.object->erase(key);
  17707. }
  17708. JSON_THROW(type_error::create(307, "cannot use erase() with " + std::string(type_name())));
  17709. }
  17710. /*!
  17711. @brief remove element from a JSON array given an index
  17712. Removes element from a JSON array at the index @a idx.
  17713. @param[in] idx index of the element to remove
  17714. @throw type_error.307 when called on a type other than JSON object;
  17715. example: `"cannot use erase() with null"`
  17716. @throw out_of_range.401 when `idx >= size()`; example: `"array index 17
  17717. is out of range"`
  17718. @complexity Linear in distance between @a idx and the end of the container.
  17719. @liveexample{The example shows the effect of `erase()`.,erase__size_type}
  17720. @sa @ref erase(IteratorType) -- removes the element at a given position
  17721. @sa @ref erase(IteratorType, IteratorType) -- removes the elements in
  17722. the given range
  17723. @sa @ref erase(const typename object_t::key_type&) -- removes the element
  17724. from an object at the given key
  17725. @since version 1.0.0
  17726. */
  17727. void erase(const size_type idx)
  17728. {
  17729. // this erase only works for arrays
  17730. if (JSON_HEDLEY_LIKELY(is_array()))
  17731. {
  17732. if (JSON_HEDLEY_UNLIKELY(idx >= size()))
  17733. {
  17734. JSON_THROW(out_of_range::create(401, "array index " + std::to_string(idx) + " is out of range"));
  17735. }
  17736. m_value.array->erase(m_value.array->begin() + static_cast<difference_type>(idx));
  17737. }
  17738. else
  17739. {
  17740. JSON_THROW(type_error::create(307, "cannot use erase() with " + std::string(type_name())));
  17741. }
  17742. }
  17743. /// @}
  17744. ////////////
  17745. // lookup //
  17746. ////////////
  17747. /// @name lookup
  17748. /// @{
  17749. /*!
  17750. @brief find an element in a JSON object
  17751. Finds an element in a JSON object with key equivalent to @a key. If the
  17752. element is not found or the JSON value is not an object, end() is
  17753. returned.
  17754. @note This method always returns @ref end() when executed on a JSON type
  17755. that is not an object.
  17756. @param[in] key key value of the element to search for.
  17757. @return Iterator to an element with key equivalent to @a key. If no such
  17758. element is found or the JSON value is not an object, past-the-end (see
  17759. @ref end()) iterator is returned.
  17760. @complexity Logarithmic in the size of the JSON object.
  17761. @liveexample{The example shows how `find()` is used.,find__key_type}
  17762. @sa @ref contains(KeyT&&) const -- checks whether a key exists
  17763. @since version 1.0.0
  17764. */
  17765. template<typename KeyT>
  17766. iterator find(KeyT&& key)
  17767. {
  17768. auto result = end();
  17769. if (is_object())
  17770. {
  17771. result.m_it.object_iterator = m_value.object->find(std::forward<KeyT>(key));
  17772. }
  17773. return result;
  17774. }
  17775. /*!
  17776. @brief find an element in a JSON object
  17777. @copydoc find(KeyT&&)
  17778. */
  17779. template<typename KeyT>
  17780. const_iterator find(KeyT&& key) const
  17781. {
  17782. auto result = cend();
  17783. if (is_object())
  17784. {
  17785. result.m_it.object_iterator = m_value.object->find(std::forward<KeyT>(key));
  17786. }
  17787. return result;
  17788. }
  17789. /*!
  17790. @brief returns the number of occurrences of a key in a JSON object
  17791. Returns the number of elements with key @a key. If ObjectType is the
  17792. default `std::map` type, the return value will always be `0` (@a key was
  17793. not found) or `1` (@a key was found).
  17794. @note This method always returns `0` when executed on a JSON type that is
  17795. not an object.
  17796. @param[in] key key value of the element to count
  17797. @return Number of elements with key @a key. If the JSON value is not an
  17798. object, the return value will be `0`.
  17799. @complexity Logarithmic in the size of the JSON object.
  17800. @liveexample{The example shows how `count()` is used.,count}
  17801. @since version 1.0.0
  17802. */
  17803. template<typename KeyT>
  17804. size_type count(KeyT&& key) const
  17805. {
  17806. // return 0 for all nonobject types
  17807. return is_object() ? m_value.object->count(std::forward<KeyT>(key)) : 0;
  17808. }
  17809. /*!
  17810. @brief check the existence of an element in a JSON object
  17811. Check whether an element exists in a JSON object with key equivalent to
  17812. @a key. If the element is not found or the JSON value is not an object,
  17813. false is returned.
  17814. @note This method always returns false when executed on a JSON type
  17815. that is not an object.
  17816. @param[in] key key value to check its existence.
  17817. @return true if an element with specified @a key exists. If no such
  17818. element with such key is found or the JSON value is not an object,
  17819. false is returned.
  17820. @complexity Logarithmic in the size of the JSON object.
  17821. @liveexample{The following code shows an example for `contains()`.,contains}
  17822. @sa @ref find(KeyT&&) -- returns an iterator to an object element
  17823. @sa @ref contains(const json_pointer&) const -- checks the existence for a JSON pointer
  17824. @since version 3.6.0
  17825. */
  17826. template < typename KeyT, typename std::enable_if <
  17827. !std::is_same<typename std::decay<KeyT>::type, json_pointer>::value, int >::type = 0 >
  17828. bool contains(KeyT && key) const
  17829. {
  17830. return is_object() && m_value.object->find(std::forward<KeyT>(key)) != m_value.object->end();
  17831. }
  17832. /*!
  17833. @brief check the existence of an element in a JSON object given a JSON pointer
  17834. Check whether the given JSON pointer @a ptr can be resolved in the current
  17835. JSON value.
  17836. @note This method can be executed on any JSON value type.
  17837. @param[in] ptr JSON pointer to check its existence.
  17838. @return true if the JSON pointer can be resolved to a stored value, false
  17839. otherwise.
  17840. @post If `j.contains(ptr)` returns true, it is safe to call `j[ptr]`.
  17841. @throw parse_error.106 if an array index begins with '0'
  17842. @throw parse_error.109 if an array index was not a number
  17843. @complexity Logarithmic in the size of the JSON object.
  17844. @liveexample{The following code shows an example for `contains()`.,contains_json_pointer}
  17845. @sa @ref contains(KeyT &&) const -- checks the existence of a key
  17846. @since version 3.7.0
  17847. */
  17848. bool contains(const json_pointer& ptr) const
  17849. {
  17850. return ptr.contains(this);
  17851. }
  17852. /// @}
  17853. ///////////////
  17854. // iterators //
  17855. ///////////////
  17856. /// @name iterators
  17857. /// @{
  17858. /*!
  17859. @brief returns an iterator to the first element
  17860. Returns an iterator to the first element.
  17861. @image html range-begin-end.svg "Illustration from cppreference.com"
  17862. @return iterator to the first element
  17863. @complexity Constant.
  17864. @requirement This function helps `basic_json` satisfying the
  17865. [Container](https://en.cppreference.com/w/cpp/named_req/Container)
  17866. requirements:
  17867. - The complexity is constant.
  17868. @liveexample{The following code shows an example for `begin()`.,begin}
  17869. @sa @ref cbegin() -- returns a const iterator to the beginning
  17870. @sa @ref end() -- returns an iterator to the end
  17871. @sa @ref cend() -- returns a const iterator to the end
  17872. @since version 1.0.0
  17873. */
  17874. iterator begin() noexcept
  17875. {
  17876. iterator result(this);
  17877. result.set_begin();
  17878. return result;
  17879. }
  17880. /*!
  17881. @copydoc basic_json::cbegin()
  17882. */
  17883. const_iterator begin() const noexcept
  17884. {
  17885. return cbegin();
  17886. }
  17887. /*!
  17888. @brief returns a const iterator to the first element
  17889. Returns a const iterator to the first element.
  17890. @image html range-begin-end.svg "Illustration from cppreference.com"
  17891. @return const iterator to the first element
  17892. @complexity Constant.
  17893. @requirement This function helps `basic_json` satisfying the
  17894. [Container](https://en.cppreference.com/w/cpp/named_req/Container)
  17895. requirements:
  17896. - The complexity is constant.
  17897. - Has the semantics of `const_cast<const basic_json&>(*this).begin()`.
  17898. @liveexample{The following code shows an example for `cbegin()`.,cbegin}
  17899. @sa @ref begin() -- returns an iterator to the beginning
  17900. @sa @ref end() -- returns an iterator to the end
  17901. @sa @ref cend() -- returns a const iterator to the end
  17902. @since version 1.0.0
  17903. */
  17904. const_iterator cbegin() const noexcept
  17905. {
  17906. const_iterator result(this);
  17907. result.set_begin();
  17908. return result;
  17909. }
  17910. /*!
  17911. @brief returns an iterator to one past the last element
  17912. Returns an iterator to one past the last element.
  17913. @image html range-begin-end.svg "Illustration from cppreference.com"
  17914. @return iterator one past the last element
  17915. @complexity Constant.
  17916. @requirement This function helps `basic_json` satisfying the
  17917. [Container](https://en.cppreference.com/w/cpp/named_req/Container)
  17918. requirements:
  17919. - The complexity is constant.
  17920. @liveexample{The following code shows an example for `end()`.,end}
  17921. @sa @ref cend() -- returns a const iterator to the end
  17922. @sa @ref begin() -- returns an iterator to the beginning
  17923. @sa @ref cbegin() -- returns a const iterator to the beginning
  17924. @since version 1.0.0
  17925. */
  17926. iterator end() noexcept
  17927. {
  17928. iterator result(this);
  17929. result.set_end();
  17930. return result;
  17931. }
  17932. /*!
  17933. @copydoc basic_json::cend()
  17934. */
  17935. const_iterator end() const noexcept
  17936. {
  17937. return cend();
  17938. }
  17939. /*!
  17940. @brief returns a const iterator to one past the last element
  17941. Returns a const iterator to one past the last element.
  17942. @image html range-begin-end.svg "Illustration from cppreference.com"
  17943. @return const iterator one past the last element
  17944. @complexity Constant.
  17945. @requirement This function helps `basic_json` satisfying the
  17946. [Container](https://en.cppreference.com/w/cpp/named_req/Container)
  17947. requirements:
  17948. - The complexity is constant.
  17949. - Has the semantics of `const_cast<const basic_json&>(*this).end()`.
  17950. @liveexample{The following code shows an example for `cend()`.,cend}
  17951. @sa @ref end() -- returns an iterator to the end
  17952. @sa @ref begin() -- returns an iterator to the beginning
  17953. @sa @ref cbegin() -- returns a const iterator to the beginning
  17954. @since version 1.0.0
  17955. */
  17956. const_iterator cend() const noexcept
  17957. {
  17958. const_iterator result(this);
  17959. result.set_end();
  17960. return result;
  17961. }
  17962. /*!
  17963. @brief returns an iterator to the reverse-beginning
  17964. Returns an iterator to the reverse-beginning; that is, the last element.
  17965. @image html range-rbegin-rend.svg "Illustration from cppreference.com"
  17966. @complexity Constant.
  17967. @requirement This function helps `basic_json` satisfying the
  17968. [ReversibleContainer](https://en.cppreference.com/w/cpp/named_req/ReversibleContainer)
  17969. requirements:
  17970. - The complexity is constant.
  17971. - Has the semantics of `reverse_iterator(end())`.
  17972. @liveexample{The following code shows an example for `rbegin()`.,rbegin}
  17973. @sa @ref crbegin() -- returns a const reverse iterator to the beginning
  17974. @sa @ref rend() -- returns a reverse iterator to the end
  17975. @sa @ref crend() -- returns a const reverse iterator to the end
  17976. @since version 1.0.0
  17977. */
  17978. reverse_iterator rbegin() noexcept
  17979. {
  17980. return reverse_iterator(end());
  17981. }
  17982. /*!
  17983. @copydoc basic_json::crbegin()
  17984. */
  17985. const_reverse_iterator rbegin() const noexcept
  17986. {
  17987. return crbegin();
  17988. }
  17989. /*!
  17990. @brief returns an iterator to the reverse-end
  17991. Returns an iterator to the reverse-end; that is, one before the first
  17992. element.
  17993. @image html range-rbegin-rend.svg "Illustration from cppreference.com"
  17994. @complexity Constant.
  17995. @requirement This function helps `basic_json` satisfying the
  17996. [ReversibleContainer](https://en.cppreference.com/w/cpp/named_req/ReversibleContainer)
  17997. requirements:
  17998. - The complexity is constant.
  17999. - Has the semantics of `reverse_iterator(begin())`.
  18000. @liveexample{The following code shows an example for `rend()`.,rend}
  18001. @sa @ref crend() -- returns a const reverse iterator to the end
  18002. @sa @ref rbegin() -- returns a reverse iterator to the beginning
  18003. @sa @ref crbegin() -- returns a const reverse iterator to the beginning
  18004. @since version 1.0.0
  18005. */
  18006. reverse_iterator rend() noexcept
  18007. {
  18008. return reverse_iterator(begin());
  18009. }
  18010. /*!
  18011. @copydoc basic_json::crend()
  18012. */
  18013. const_reverse_iterator rend() const noexcept
  18014. {
  18015. return crend();
  18016. }
  18017. /*!
  18018. @brief returns a const reverse iterator to the last element
  18019. Returns a const iterator to the reverse-beginning; that is, the last
  18020. element.
  18021. @image html range-rbegin-rend.svg "Illustration from cppreference.com"
  18022. @complexity Constant.
  18023. @requirement This function helps `basic_json` satisfying the
  18024. [ReversibleContainer](https://en.cppreference.com/w/cpp/named_req/ReversibleContainer)
  18025. requirements:
  18026. - The complexity is constant.
  18027. - Has the semantics of `const_cast<const basic_json&>(*this).rbegin()`.
  18028. @liveexample{The following code shows an example for `crbegin()`.,crbegin}
  18029. @sa @ref rbegin() -- returns a reverse iterator to the beginning
  18030. @sa @ref rend() -- returns a reverse iterator to the end
  18031. @sa @ref crend() -- returns a const reverse iterator to the end
  18032. @since version 1.0.0
  18033. */
  18034. const_reverse_iterator crbegin() const noexcept
  18035. {
  18036. return const_reverse_iterator(cend());
  18037. }
  18038. /*!
  18039. @brief returns a const reverse iterator to one before the first
  18040. Returns a const reverse iterator to the reverse-end; that is, one before
  18041. the first element.
  18042. @image html range-rbegin-rend.svg "Illustration from cppreference.com"
  18043. @complexity Constant.
  18044. @requirement This function helps `basic_json` satisfying the
  18045. [ReversibleContainer](https://en.cppreference.com/w/cpp/named_req/ReversibleContainer)
  18046. requirements:
  18047. - The complexity is constant.
  18048. - Has the semantics of `const_cast<const basic_json&>(*this).rend()`.
  18049. @liveexample{The following code shows an example for `crend()`.,crend}
  18050. @sa @ref rend() -- returns a reverse iterator to the end
  18051. @sa @ref rbegin() -- returns a reverse iterator to the beginning
  18052. @sa @ref crbegin() -- returns a const reverse iterator to the beginning
  18053. @since version 1.0.0
  18054. */
  18055. const_reverse_iterator crend() const noexcept
  18056. {
  18057. return const_reverse_iterator(cbegin());
  18058. }
  18059. public:
  18060. /*!
  18061. @brief wrapper to access iterator member functions in range-based for
  18062. This function allows to access @ref iterator::key() and @ref
  18063. iterator::value() during range-based for loops. In these loops, a
  18064. reference to the JSON values is returned, so there is no access to the
  18065. underlying iterator.
  18066. For loop without iterator_wrapper:
  18067. @code{cpp}
  18068. for (auto it = j_object.begin(); it != j_object.end(); ++it)
  18069. {
  18070. std::cout << "key: " << it.key() << ", value:" << it.value() << '\n';
  18071. }
  18072. @endcode
  18073. Range-based for loop without iterator proxy:
  18074. @code{cpp}
  18075. for (auto it : j_object)
  18076. {
  18077. // "it" is of type json::reference and has no key() member
  18078. std::cout << "value: " << it << '\n';
  18079. }
  18080. @endcode
  18081. Range-based for loop with iterator proxy:
  18082. @code{cpp}
  18083. for (auto it : json::iterator_wrapper(j_object))
  18084. {
  18085. std::cout << "key: " << it.key() << ", value:" << it.value() << '\n';
  18086. }
  18087. @endcode
  18088. @note When iterating over an array, `key()` will return the index of the
  18089. element as string (see example).
  18090. @param[in] ref reference to a JSON value
  18091. @return iteration proxy object wrapping @a ref with an interface to use in
  18092. range-based for loops
  18093. @liveexample{The following code shows how the wrapper is used,iterator_wrapper}
  18094. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  18095. changes in the JSON value.
  18096. @complexity Constant.
  18097. @note The name of this function is not yet final and may change in the
  18098. future.
  18099. @deprecated This stream operator is deprecated and will be removed in
  18100. future 4.0.0 of the library. Please use @ref items() instead;
  18101. that is, replace `json::iterator_wrapper(j)` with `j.items()`.
  18102. */
  18103. JSON_HEDLEY_DEPRECATED_FOR(3.1.0, items())
  18104. static iteration_proxy<iterator> iterator_wrapper(reference ref) noexcept
  18105. {
  18106. return ref.items();
  18107. }
  18108. /*!
  18109. @copydoc iterator_wrapper(reference)
  18110. */
  18111. JSON_HEDLEY_DEPRECATED_FOR(3.1.0, items())
  18112. static iteration_proxy<const_iterator> iterator_wrapper(const_reference ref) noexcept
  18113. {
  18114. return ref.items();
  18115. }
  18116. /*!
  18117. @brief helper to access iterator member functions in range-based for
  18118. This function allows to access @ref iterator::key() and @ref
  18119. iterator::value() during range-based for loops. In these loops, a
  18120. reference to the JSON values is returned, so there is no access to the
  18121. underlying iterator.
  18122. For loop without `items()` function:
  18123. @code{cpp}
  18124. for (auto it = j_object.begin(); it != j_object.end(); ++it)
  18125. {
  18126. std::cout << "key: " << it.key() << ", value:" << it.value() << '\n';
  18127. }
  18128. @endcode
  18129. Range-based for loop without `items()` function:
  18130. @code{cpp}
  18131. for (auto it : j_object)
  18132. {
  18133. // "it" is of type json::reference and has no key() member
  18134. std::cout << "value: " << it << '\n';
  18135. }
  18136. @endcode
  18137. Range-based for loop with `items()` function:
  18138. @code{cpp}
  18139. for (auto& el : j_object.items())
  18140. {
  18141. std::cout << "key: " << el.key() << ", value:" << el.value() << '\n';
  18142. }
  18143. @endcode
  18144. The `items()` function also allows to use
  18145. [structured bindings](https://en.cppreference.com/w/cpp/language/structured_binding)
  18146. (C++17):
  18147. @code{cpp}
  18148. for (auto& [key, val] : j_object.items())
  18149. {
  18150. std::cout << "key: " << key << ", value:" << val << '\n';
  18151. }
  18152. @endcode
  18153. @note When iterating over an array, `key()` will return the index of the
  18154. element as string (see example). For primitive types (e.g., numbers),
  18155. `key()` returns an empty string.
  18156. @warning Using `items()` on temporary objects is dangerous. Make sure the
  18157. object's lifetime exeeds the iteration. See
  18158. <https://github.com/nlohmann/json/issues/2040> for more
  18159. information.
  18160. @return iteration proxy object wrapping @a ref with an interface to use in
  18161. range-based for loops
  18162. @liveexample{The following code shows how the function is used.,items}
  18163. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  18164. changes in the JSON value.
  18165. @complexity Constant.
  18166. @since version 3.1.0, structured bindings support since 3.5.0.
  18167. */
  18168. iteration_proxy<iterator> items() noexcept
  18169. {
  18170. return iteration_proxy<iterator>(*this);
  18171. }
  18172. /*!
  18173. @copydoc items()
  18174. */
  18175. iteration_proxy<const_iterator> items() const noexcept
  18176. {
  18177. return iteration_proxy<const_iterator>(*this);
  18178. }
  18179. /// @}
  18180. //////////////
  18181. // capacity //
  18182. //////////////
  18183. /// @name capacity
  18184. /// @{
  18185. /*!
  18186. @brief checks whether the container is empty.
  18187. Checks if a JSON value has no elements (i.e. whether its @ref size is `0`).
  18188. @return The return value depends on the different types and is
  18189. defined as follows:
  18190. Value type | return value
  18191. ----------- | -------------
  18192. null | `true`
  18193. boolean | `false`
  18194. string | `false`
  18195. number | `false`
  18196. binary | `false`
  18197. object | result of function `object_t::empty()`
  18198. array | result of function `array_t::empty()`
  18199. @liveexample{The following code uses `empty()` to check if a JSON
  18200. object contains any elements.,empty}
  18201. @complexity Constant, as long as @ref array_t and @ref object_t satisfy
  18202. the Container concept; that is, their `empty()` functions have constant
  18203. complexity.
  18204. @iterators No changes.
  18205. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  18206. @note This function does not return whether a string stored as JSON value
  18207. is empty - it returns whether the JSON container itself is empty which is
  18208. false in the case of a string.
  18209. @requirement This function helps `basic_json` satisfying the
  18210. [Container](https://en.cppreference.com/w/cpp/named_req/Container)
  18211. requirements:
  18212. - The complexity is constant.
  18213. - Has the semantics of `begin() == end()`.
  18214. @sa @ref size() -- returns the number of elements
  18215. @since version 1.0.0
  18216. */
  18217. bool empty() const noexcept
  18218. {
  18219. switch (m_type)
  18220. {
  18221. case value_t::null:
  18222. {
  18223. // null values are empty
  18224. return true;
  18225. }
  18226. case value_t::array:
  18227. {
  18228. // delegate call to array_t::empty()
  18229. return m_value.array->empty();
  18230. }
  18231. case value_t::object:
  18232. {
  18233. // delegate call to object_t::empty()
  18234. return m_value.object->empty();
  18235. }
  18236. default:
  18237. {
  18238. // all other types are nonempty
  18239. return false;
  18240. }
  18241. }
  18242. }
  18243. /*!
  18244. @brief returns the number of elements
  18245. Returns the number of elements in a JSON value.
  18246. @return The return value depends on the different types and is
  18247. defined as follows:
  18248. Value type | return value
  18249. ----------- | -------------
  18250. null | `0`
  18251. boolean | `1`
  18252. string | `1`
  18253. number | `1`
  18254. binary | `1`
  18255. object | result of function object_t::size()
  18256. array | result of function array_t::size()
  18257. @liveexample{The following code calls `size()` on the different value
  18258. types.,size}
  18259. @complexity Constant, as long as @ref array_t and @ref object_t satisfy
  18260. the Container concept; that is, their size() functions have constant
  18261. complexity.
  18262. @iterators No changes.
  18263. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  18264. @note This function does not return the length of a string stored as JSON
  18265. value - it returns the number of elements in the JSON value which is 1 in
  18266. the case of a string.
  18267. @requirement This function helps `basic_json` satisfying the
  18268. [Container](https://en.cppreference.com/w/cpp/named_req/Container)
  18269. requirements:
  18270. - The complexity is constant.
  18271. - Has the semantics of `std::distance(begin(), end())`.
  18272. @sa @ref empty() -- checks whether the container is empty
  18273. @sa @ref max_size() -- returns the maximal number of elements
  18274. @since version 1.0.0
  18275. */
  18276. size_type size() const noexcept
  18277. {
  18278. switch (m_type)
  18279. {
  18280. case value_t::null:
  18281. {
  18282. // null values are empty
  18283. return 0;
  18284. }
  18285. case value_t::array:
  18286. {
  18287. // delegate call to array_t::size()
  18288. return m_value.array->size();
  18289. }
  18290. case value_t::object:
  18291. {
  18292. // delegate call to object_t::size()
  18293. return m_value.object->size();
  18294. }
  18295. default:
  18296. {
  18297. // all other types have size 1
  18298. return 1;
  18299. }
  18300. }
  18301. }
  18302. /*!
  18303. @brief returns the maximum possible number of elements
  18304. Returns the maximum number of elements a JSON value is able to hold due to
  18305. system or library implementation limitations, i.e. `std::distance(begin(),
  18306. end())` for the JSON value.
  18307. @return The return value depends on the different types and is
  18308. defined as follows:
  18309. Value type | return value
  18310. ----------- | -------------
  18311. null | `0` (same as `size()`)
  18312. boolean | `1` (same as `size()`)
  18313. string | `1` (same as `size()`)
  18314. number | `1` (same as `size()`)
  18315. binary | `1` (same as `size()`)
  18316. object | result of function `object_t::max_size()`
  18317. array | result of function `array_t::max_size()`
  18318. @liveexample{The following code calls `max_size()` on the different value
  18319. types. Note the output is implementation specific.,max_size}
  18320. @complexity Constant, as long as @ref array_t and @ref object_t satisfy
  18321. the Container concept; that is, their `max_size()` functions have constant
  18322. complexity.
  18323. @iterators No changes.
  18324. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  18325. @requirement This function helps `basic_json` satisfying the
  18326. [Container](https://en.cppreference.com/w/cpp/named_req/Container)
  18327. requirements:
  18328. - The complexity is constant.
  18329. - Has the semantics of returning `b.size()` where `b` is the largest
  18330. possible JSON value.
  18331. @sa @ref size() -- returns the number of elements
  18332. @since version 1.0.0
  18333. */
  18334. size_type max_size() const noexcept
  18335. {
  18336. switch (m_type)
  18337. {
  18338. case value_t::array:
  18339. {
  18340. // delegate call to array_t::max_size()
  18341. return m_value.array->max_size();
  18342. }
  18343. case value_t::object:
  18344. {
  18345. // delegate call to object_t::max_size()
  18346. return m_value.object->max_size();
  18347. }
  18348. default:
  18349. {
  18350. // all other types have max_size() == size()
  18351. return size();
  18352. }
  18353. }
  18354. }
  18355. /// @}
  18356. ///////////////
  18357. // modifiers //
  18358. ///////////////
  18359. /// @name modifiers
  18360. /// @{
  18361. /*!
  18362. @brief clears the contents
  18363. Clears the content of a JSON value and resets it to the default value as
  18364. if @ref basic_json(value_t) would have been called with the current value
  18365. type from @ref type():
  18366. Value type | initial value
  18367. ----------- | -------------
  18368. null | `null`
  18369. boolean | `false`
  18370. string | `""`
  18371. number | `0`
  18372. binary | An empty byte vector
  18373. object | `{}`
  18374. array | `[]`
  18375. @post Has the same effect as calling
  18376. @code {.cpp}
  18377. *this = basic_json(type());
  18378. @endcode
  18379. @liveexample{The example below shows the effect of `clear()` to different
  18380. JSON types.,clear}
  18381. @complexity Linear in the size of the JSON value.
  18382. @iterators All iterators, pointers and references related to this container
  18383. are invalidated.
  18384. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  18385. @sa @ref basic_json(value_t) -- constructor that creates an object with the
  18386. same value than calling `clear()`
  18387. @since version 1.0.0
  18388. */
  18389. void clear() noexcept
  18390. {
  18391. switch (m_type)
  18392. {
  18393. case value_t::number_integer:
  18394. {
  18395. m_value.number_integer = 0;
  18396. break;
  18397. }
  18398. case value_t::number_unsigned:
  18399. {
  18400. m_value.number_unsigned = 0;
  18401. break;
  18402. }
  18403. case value_t::number_float:
  18404. {
  18405. m_value.number_float = 0.0;
  18406. break;
  18407. }
  18408. case value_t::boolean:
  18409. {
  18410. m_value.boolean = false;
  18411. break;
  18412. }
  18413. case value_t::string:
  18414. {
  18415. m_value.string->clear();
  18416. break;
  18417. }
  18418. case value_t::binary:
  18419. {
  18420. m_value.binary->clear();
  18421. break;
  18422. }
  18423. case value_t::array:
  18424. {
  18425. m_value.array->clear();
  18426. break;
  18427. }
  18428. case value_t::object:
  18429. {
  18430. m_value.object->clear();
  18431. break;
  18432. }
  18433. default:
  18434. break;
  18435. }
  18436. }
  18437. /*!
  18438. @brief add an object to an array
  18439. Appends the given element @a val to the end of the JSON value. If the
  18440. function is called on a JSON null value, an empty array is created before
  18441. appending @a val.
  18442. @param[in] val the value to add to the JSON array
  18443. @throw type_error.308 when called on a type other than JSON array or
  18444. null; example: `"cannot use push_back() with number"`
  18445. @complexity Amortized constant.
  18446. @liveexample{The example shows how `push_back()` and `+=` can be used to
  18447. add elements to a JSON array. Note how the `null` value was silently
  18448. converted to a JSON array.,push_back}
  18449. @since version 1.0.0
  18450. */
  18451. void push_back(basic_json&& val)
  18452. {
  18453. // push_back only works for null objects or arrays
  18454. if (JSON_HEDLEY_UNLIKELY(!(is_null() || is_array())))
  18455. {
  18456. JSON_THROW(type_error::create(308, "cannot use push_back() with " + std::string(type_name())));
  18457. }
  18458. // transform null object into an array
  18459. if (is_null())
  18460. {
  18461. m_type = value_t::array;
  18462. m_value = value_t::array;
  18463. assert_invariant();
  18464. }
  18465. // add element to array (move semantics)
  18466. m_value.array->push_back(std::move(val));
  18467. // if val is moved from, basic_json move constructor marks it null so we do not call the destructor
  18468. }
  18469. /*!
  18470. @brief add an object to an array
  18471. @copydoc push_back(basic_json&&)
  18472. */
  18473. reference operator+=(basic_json&& val)
  18474. {
  18475. push_back(std::move(val));
  18476. return *this;
  18477. }
  18478. /*!
  18479. @brief add an object to an array
  18480. @copydoc push_back(basic_json&&)
  18481. */
  18482. void push_back(const basic_json& val)
  18483. {
  18484. // push_back only works for null objects or arrays
  18485. if (JSON_HEDLEY_UNLIKELY(!(is_null() || is_array())))
  18486. {
  18487. JSON_THROW(type_error::create(308, "cannot use push_back() with " + std::string(type_name())));
  18488. }
  18489. // transform null object into an array
  18490. if (is_null())
  18491. {
  18492. m_type = value_t::array;
  18493. m_value = value_t::array;
  18494. assert_invariant();
  18495. }
  18496. // add element to array
  18497. m_value.array->push_back(val);
  18498. }
  18499. /*!
  18500. @brief add an object to an array
  18501. @copydoc push_back(basic_json&&)
  18502. */
  18503. reference operator+=(const basic_json& val)
  18504. {
  18505. push_back(val);
  18506. return *this;
  18507. }
  18508. /*!
  18509. @brief add an object to an object
  18510. Inserts the given element @a val to the JSON object. If the function is
  18511. called on a JSON null value, an empty object is created before inserting
  18512. @a val.
  18513. @param[in] val the value to add to the JSON object
  18514. @throw type_error.308 when called on a type other than JSON object or
  18515. null; example: `"cannot use push_back() with number"`
  18516. @complexity Logarithmic in the size of the container, O(log(`size()`)).
  18517. @liveexample{The example shows how `push_back()` and `+=` can be used to
  18518. add elements to a JSON object. Note how the `null` value was silently
  18519. converted to a JSON object.,push_back__object_t__value}
  18520. @since version 1.0.0
  18521. */
  18522. void push_back(const typename object_t::value_type& val)
  18523. {
  18524. // push_back only works for null objects or objects
  18525. if (JSON_HEDLEY_UNLIKELY(!(is_null() || is_object())))
  18526. {
  18527. JSON_THROW(type_error::create(308, "cannot use push_back() with " + std::string(type_name())));
  18528. }
  18529. // transform null object into an object
  18530. if (is_null())
  18531. {
  18532. m_type = value_t::object;
  18533. m_value = value_t::object;
  18534. assert_invariant();
  18535. }
  18536. // add element to array
  18537. m_value.object->insert(val);
  18538. }
  18539. /*!
  18540. @brief add an object to an object
  18541. @copydoc push_back(const typename object_t::value_type&)
  18542. */
  18543. reference operator+=(const typename object_t::value_type& val)
  18544. {
  18545. push_back(val);
  18546. return *this;
  18547. }
  18548. /*!
  18549. @brief add an object to an object
  18550. This function allows to use `push_back` with an initializer list. In case
  18551. 1. the current value is an object,
  18552. 2. the initializer list @a init contains only two elements, and
  18553. 3. the first element of @a init is a string,
  18554. @a init is converted into an object element and added using
  18555. @ref push_back(const typename object_t::value_type&). Otherwise, @a init
  18556. is converted to a JSON value and added using @ref push_back(basic_json&&).
  18557. @param[in] init an initializer list
  18558. @complexity Linear in the size of the initializer list @a init.
  18559. @note This function is required to resolve an ambiguous overload error,
  18560. because pairs like `{"key", "value"}` can be both interpreted as
  18561. `object_t::value_type` or `std::initializer_list<basic_json>`, see
  18562. https://github.com/nlohmann/json/issues/235 for more information.
  18563. @liveexample{The example shows how initializer lists are treated as
  18564. objects when possible.,push_back__initializer_list}
  18565. */
  18566. void push_back(initializer_list_t init)
  18567. {
  18568. if (is_object() && init.size() == 2 && (*init.begin())->is_string())
  18569. {
  18570. basic_json&& key = init.begin()->moved_or_copied();
  18571. push_back(typename object_t::value_type(
  18572. std::move(key.get_ref<string_t&>()), (init.begin() + 1)->moved_or_copied()));
  18573. }
  18574. else
  18575. {
  18576. push_back(basic_json(init));
  18577. }
  18578. }
  18579. /*!
  18580. @brief add an object to an object
  18581. @copydoc push_back(initializer_list_t)
  18582. */
  18583. reference operator+=(initializer_list_t init)
  18584. {
  18585. push_back(init);
  18586. return *this;
  18587. }
  18588. /*!
  18589. @brief add an object to an array
  18590. Creates a JSON value from the passed parameters @a args to the end of the
  18591. JSON value. If the function is called on a JSON null value, an empty array
  18592. is created before appending the value created from @a args.
  18593. @param[in] args arguments to forward to a constructor of @ref basic_json
  18594. @tparam Args compatible types to create a @ref basic_json object
  18595. @return reference to the inserted element
  18596. @throw type_error.311 when called on a type other than JSON array or
  18597. null; example: `"cannot use emplace_back() with number"`
  18598. @complexity Amortized constant.
  18599. @liveexample{The example shows how `push_back()` can be used to add
  18600. elements to a JSON array. Note how the `null` value was silently converted
  18601. to a JSON array.,emplace_back}
  18602. @since version 2.0.8, returns reference since 3.7.0
  18603. */
  18604. template<class... Args>
  18605. reference emplace_back(Args&& ... args)
  18606. {
  18607. // emplace_back only works for null objects or arrays
  18608. if (JSON_HEDLEY_UNLIKELY(!(is_null() || is_array())))
  18609. {
  18610. JSON_THROW(type_error::create(311, "cannot use emplace_back() with " + std::string(type_name())));
  18611. }
  18612. // transform null object into an array
  18613. if (is_null())
  18614. {
  18615. m_type = value_t::array;
  18616. m_value = value_t::array;
  18617. assert_invariant();
  18618. }
  18619. // add element to array (perfect forwarding)
  18620. #ifdef JSON_HAS_CPP_17
  18621. return m_value.array->emplace_back(std::forward<Args>(args)...);
  18622. #else
  18623. m_value.array->emplace_back(std::forward<Args>(args)...);
  18624. return m_value.array->back();
  18625. #endif
  18626. }
  18627. /*!
  18628. @brief add an object to an object if key does not exist
  18629. Inserts a new element into a JSON object constructed in-place with the
  18630. given @a args if there is no element with the key in the container. If the
  18631. function is called on a JSON null value, an empty object is created before
  18632. appending the value created from @a args.
  18633. @param[in] args arguments to forward to a constructor of @ref basic_json
  18634. @tparam Args compatible types to create a @ref basic_json object
  18635. @return a pair consisting of an iterator to the inserted element, or the
  18636. already-existing element if no insertion happened, and a bool
  18637. denoting whether the insertion took place.
  18638. @throw type_error.311 when called on a type other than JSON object or
  18639. null; example: `"cannot use emplace() with number"`
  18640. @complexity Logarithmic in the size of the container, O(log(`size()`)).
  18641. @liveexample{The example shows how `emplace()` can be used to add elements
  18642. to a JSON object. Note how the `null` value was silently converted to a
  18643. JSON object. Further note how no value is added if there was already one
  18644. value stored with the same key.,emplace}
  18645. @since version 2.0.8
  18646. */
  18647. template<class... Args>
  18648. std::pair<iterator, bool> emplace(Args&& ... args)
  18649. {
  18650. // emplace only works for null objects or arrays
  18651. if (JSON_HEDLEY_UNLIKELY(!(is_null() || is_object())))
  18652. {
  18653. JSON_THROW(type_error::create(311, "cannot use emplace() with " + std::string(type_name())));
  18654. }
  18655. // transform null object into an object
  18656. if (is_null())
  18657. {
  18658. m_type = value_t::object;
  18659. m_value = value_t::object;
  18660. assert_invariant();
  18661. }
  18662. // add element to array (perfect forwarding)
  18663. auto res = m_value.object->emplace(std::forward<Args>(args)...);
  18664. // create result iterator and set iterator to the result of emplace
  18665. auto it = begin();
  18666. it.m_it.object_iterator = res.first;
  18667. // return pair of iterator and boolean
  18668. return {it, res.second};
  18669. }
  18670. /// Helper for insertion of an iterator
  18671. /// @note: This uses std::distance to support GCC 4.8,
  18672. /// see https://github.com/nlohmann/json/pull/1257
  18673. template<typename... Args>
  18674. iterator insert_iterator(const_iterator pos, Args&& ... args)
  18675. {
  18676. iterator result(this);
  18677. JSON_ASSERT(m_value.array != nullptr);
  18678. auto insert_pos = std::distance(m_value.array->begin(), pos.m_it.array_iterator);
  18679. m_value.array->insert(pos.m_it.array_iterator, std::forward<Args>(args)...);
  18680. result.m_it.array_iterator = m_value.array->begin() + insert_pos;
  18681. // This could have been written as:
  18682. // result.m_it.array_iterator = m_value.array->insert(pos.m_it.array_iterator, cnt, val);
  18683. // but the return value of insert is missing in GCC 4.8, so it is written this way instead.
  18684. return result;
  18685. }
  18686. /*!
  18687. @brief inserts element
  18688. Inserts element @a val before iterator @a pos.
  18689. @param[in] pos iterator before which the content will be inserted; may be
  18690. the end() iterator
  18691. @param[in] val element to insert
  18692. @return iterator pointing to the inserted @a val.
  18693. @throw type_error.309 if called on JSON values other than arrays;
  18694. example: `"cannot use insert() with string"`
  18695. @throw invalid_iterator.202 if @a pos is not an iterator of *this;
  18696. example: `"iterator does not fit current value"`
  18697. @complexity Constant plus linear in the distance between @a pos and end of
  18698. the container.
  18699. @liveexample{The example shows how `insert()` is used.,insert}
  18700. @since version 1.0.0
  18701. */
  18702. iterator insert(const_iterator pos, const basic_json& val)
  18703. {
  18704. // insert only works for arrays
  18705. if (JSON_HEDLEY_LIKELY(is_array()))
  18706. {
  18707. // check if iterator pos fits to this JSON value
  18708. if (JSON_HEDLEY_UNLIKELY(pos.m_object != this))
  18709. {
  18710. JSON_THROW(invalid_iterator::create(202, "iterator does not fit current value"));
  18711. }
  18712. // insert to array and return iterator
  18713. return insert_iterator(pos, val);
  18714. }
  18715. JSON_THROW(type_error::create(309, "cannot use insert() with " + std::string(type_name())));
  18716. }
  18717. /*!
  18718. @brief inserts element
  18719. @copydoc insert(const_iterator, const basic_json&)
  18720. */
  18721. iterator insert(const_iterator pos, basic_json&& val)
  18722. {
  18723. return insert(pos, val);
  18724. }
  18725. /*!
  18726. @brief inserts elements
  18727. Inserts @a cnt copies of @a val before iterator @a pos.
  18728. @param[in] pos iterator before which the content will be inserted; may be
  18729. the end() iterator
  18730. @param[in] cnt number of copies of @a val to insert
  18731. @param[in] val element to insert
  18732. @return iterator pointing to the first element inserted, or @a pos if
  18733. `cnt==0`
  18734. @throw type_error.309 if called on JSON values other than arrays; example:
  18735. `"cannot use insert() with string"`
  18736. @throw invalid_iterator.202 if @a pos is not an iterator of *this;
  18737. example: `"iterator does not fit current value"`
  18738. @complexity Linear in @a cnt plus linear in the distance between @a pos
  18739. and end of the container.
  18740. @liveexample{The example shows how `insert()` is used.,insert__count}
  18741. @since version 1.0.0
  18742. */
  18743. iterator insert(const_iterator pos, size_type cnt, const basic_json& val)
  18744. {
  18745. // insert only works for arrays
  18746. if (JSON_HEDLEY_LIKELY(is_array()))
  18747. {
  18748. // check if iterator pos fits to this JSON value
  18749. if (JSON_HEDLEY_UNLIKELY(pos.m_object != this))
  18750. {
  18751. JSON_THROW(invalid_iterator::create(202, "iterator does not fit current value"));
  18752. }
  18753. // insert to array and return iterator
  18754. return insert_iterator(pos, cnt, val);
  18755. }
  18756. JSON_THROW(type_error::create(309, "cannot use insert() with " + std::string(type_name())));
  18757. }
  18758. /*!
  18759. @brief inserts elements
  18760. Inserts elements from range `[first, last)` before iterator @a pos.
  18761. @param[in] pos iterator before which the content will be inserted; may be
  18762. the end() iterator
  18763. @param[in] first begin of the range of elements to insert
  18764. @param[in] last end of the range of elements to insert
  18765. @throw type_error.309 if called on JSON values other than arrays; example:
  18766. `"cannot use insert() with string"`
  18767. @throw invalid_iterator.202 if @a pos is not an iterator of *this;
  18768. example: `"iterator does not fit current value"`
  18769. @throw invalid_iterator.210 if @a first and @a last do not belong to the
  18770. same JSON value; example: `"iterators do not fit"`
  18771. @throw invalid_iterator.211 if @a first or @a last are iterators into
  18772. container for which insert is called; example: `"passed iterators may not
  18773. belong to container"`
  18774. @return iterator pointing to the first element inserted, or @a pos if
  18775. `first==last`
  18776. @complexity Linear in `std::distance(first, last)` plus linear in the
  18777. distance between @a pos and end of the container.
  18778. @liveexample{The example shows how `insert()` is used.,insert__range}
  18779. @since version 1.0.0
  18780. */
  18781. iterator insert(const_iterator pos, const_iterator first, const_iterator last)
  18782. {
  18783. // insert only works for arrays
  18784. if (JSON_HEDLEY_UNLIKELY(!is_array()))
  18785. {
  18786. JSON_THROW(type_error::create(309, "cannot use insert() with " + std::string(type_name())));
  18787. }
  18788. // check if iterator pos fits to this JSON value
  18789. if (JSON_HEDLEY_UNLIKELY(pos.m_object != this))
  18790. {
  18791. JSON_THROW(invalid_iterator::create(202, "iterator does not fit current value"));
  18792. }
  18793. // check if range iterators belong to the same JSON object
  18794. if (JSON_HEDLEY_UNLIKELY(first.m_object != last.m_object))
  18795. {
  18796. JSON_THROW(invalid_iterator::create(210, "iterators do not fit"));
  18797. }
  18798. if (JSON_HEDLEY_UNLIKELY(first.m_object == this))
  18799. {
  18800. JSON_THROW(invalid_iterator::create(211, "passed iterators may not belong to container"));
  18801. }
  18802. // insert to array and return iterator
  18803. return insert_iterator(pos, first.m_it.array_iterator, last.m_it.array_iterator);
  18804. }
  18805. /*!
  18806. @brief inserts elements
  18807. Inserts elements from initializer list @a ilist before iterator @a pos.
  18808. @param[in] pos iterator before which the content will be inserted; may be
  18809. the end() iterator
  18810. @param[in] ilist initializer list to insert the values from
  18811. @throw type_error.309 if called on JSON values other than arrays; example:
  18812. `"cannot use insert() with string"`
  18813. @throw invalid_iterator.202 if @a pos is not an iterator of *this;
  18814. example: `"iterator does not fit current value"`
  18815. @return iterator pointing to the first element inserted, or @a pos if
  18816. `ilist` is empty
  18817. @complexity Linear in `ilist.size()` plus linear in the distance between
  18818. @a pos and end of the container.
  18819. @liveexample{The example shows how `insert()` is used.,insert__ilist}
  18820. @since version 1.0.0
  18821. */
  18822. iterator insert(const_iterator pos, initializer_list_t ilist)
  18823. {
  18824. // insert only works for arrays
  18825. if (JSON_HEDLEY_UNLIKELY(!is_array()))
  18826. {
  18827. JSON_THROW(type_error::create(309, "cannot use insert() with " + std::string(type_name())));
  18828. }
  18829. // check if iterator pos fits to this JSON value
  18830. if (JSON_HEDLEY_UNLIKELY(pos.m_object != this))
  18831. {
  18832. JSON_THROW(invalid_iterator::create(202, "iterator does not fit current value"));
  18833. }
  18834. // insert to array and return iterator
  18835. return insert_iterator(pos, ilist.begin(), ilist.end());
  18836. }
  18837. /*!
  18838. @brief inserts elements
  18839. Inserts elements from range `[first, last)`.
  18840. @param[in] first begin of the range of elements to insert
  18841. @param[in] last end of the range of elements to insert
  18842. @throw type_error.309 if called on JSON values other than objects; example:
  18843. `"cannot use insert() with string"`
  18844. @throw invalid_iterator.202 if iterator @a first or @a last does does not
  18845. point to an object; example: `"iterators first and last must point to
  18846. objects"`
  18847. @throw invalid_iterator.210 if @a first and @a last do not belong to the
  18848. same JSON value; example: `"iterators do not fit"`
  18849. @complexity Logarithmic: `O(N*log(size() + N))`, where `N` is the number
  18850. of elements to insert.
  18851. @liveexample{The example shows how `insert()` is used.,insert__range_object}
  18852. @since version 3.0.0
  18853. */
  18854. void insert(const_iterator first, const_iterator last)
  18855. {
  18856. // insert only works for objects
  18857. if (JSON_HEDLEY_UNLIKELY(!is_object()))
  18858. {
  18859. JSON_THROW(type_error::create(309, "cannot use insert() with " + std::string(type_name())));
  18860. }
  18861. // check if range iterators belong to the same JSON object
  18862. if (JSON_HEDLEY_UNLIKELY(first.m_object != last.m_object))
  18863. {
  18864. JSON_THROW(invalid_iterator::create(210, "iterators do not fit"));
  18865. }
  18866. // passed iterators must belong to objects
  18867. if (JSON_HEDLEY_UNLIKELY(!first.m_object->is_object()))
  18868. {
  18869. JSON_THROW(invalid_iterator::create(202, "iterators first and last must point to objects"));
  18870. }
  18871. m_value.object->insert(first.m_it.object_iterator, last.m_it.object_iterator);
  18872. }
  18873. /*!
  18874. @brief updates a JSON object from another object, overwriting existing keys
  18875. Inserts all values from JSON object @a j and overwrites existing keys.
  18876. @param[in] j JSON object to read values from
  18877. @throw type_error.312 if called on JSON values other than objects; example:
  18878. `"cannot use update() with string"`
  18879. @complexity O(N*log(size() + N)), where N is the number of elements to
  18880. insert.
  18881. @liveexample{The example shows how `update()` is used.,update}
  18882. @sa https://docs.python.org/3.6/library/stdtypes.html#dict.update
  18883. @since version 3.0.0
  18884. */
  18885. void update(const_reference j)
  18886. {
  18887. // implicitly convert null value to an empty object
  18888. if (is_null())
  18889. {
  18890. m_type = value_t::object;
  18891. m_value.object = create<object_t>();
  18892. assert_invariant();
  18893. }
  18894. if (JSON_HEDLEY_UNLIKELY(!is_object()))
  18895. {
  18896. JSON_THROW(type_error::create(312, "cannot use update() with " + std::string(type_name())));
  18897. }
  18898. if (JSON_HEDLEY_UNLIKELY(!j.is_object()))
  18899. {
  18900. JSON_THROW(type_error::create(312, "cannot use update() with " + std::string(j.type_name())));
  18901. }
  18902. for (auto it = j.cbegin(); it != j.cend(); ++it)
  18903. {
  18904. m_value.object->operator[](it.key()) = it.value();
  18905. }
  18906. }
  18907. /*!
  18908. @brief updates a JSON object from another object, overwriting existing keys
  18909. Inserts all values from from range `[first, last)` and overwrites existing
  18910. keys.
  18911. @param[in] first begin of the range of elements to insert
  18912. @param[in] last end of the range of elements to insert
  18913. @throw type_error.312 if called on JSON values other than objects; example:
  18914. `"cannot use update() with string"`
  18915. @throw invalid_iterator.202 if iterator @a first or @a last does does not
  18916. point to an object; example: `"iterators first and last must point to
  18917. objects"`
  18918. @throw invalid_iterator.210 if @a first and @a last do not belong to the
  18919. same JSON value; example: `"iterators do not fit"`
  18920. @complexity O(N*log(size() + N)), where N is the number of elements to
  18921. insert.
  18922. @liveexample{The example shows how `update()` is used__range.,update}
  18923. @sa https://docs.python.org/3.6/library/stdtypes.html#dict.update
  18924. @since version 3.0.0
  18925. */
  18926. void update(const_iterator first, const_iterator last)
  18927. {
  18928. // implicitly convert null value to an empty object
  18929. if (is_null())
  18930. {
  18931. m_type = value_t::object;
  18932. m_value.object = create<object_t>();
  18933. assert_invariant();
  18934. }
  18935. if (JSON_HEDLEY_UNLIKELY(!is_object()))
  18936. {
  18937. JSON_THROW(type_error::create(312, "cannot use update() with " + std::string(type_name())));
  18938. }
  18939. // check if range iterators belong to the same JSON object
  18940. if (JSON_HEDLEY_UNLIKELY(first.m_object != last.m_object))
  18941. {
  18942. JSON_THROW(invalid_iterator::create(210, "iterators do not fit"));
  18943. }
  18944. // passed iterators must belong to objects
  18945. if (JSON_HEDLEY_UNLIKELY(!first.m_object->is_object()
  18946. || !last.m_object->is_object()))
  18947. {
  18948. JSON_THROW(invalid_iterator::create(202, "iterators first and last must point to objects"));
  18949. }
  18950. for (auto it = first; it != last; ++it)
  18951. {
  18952. m_value.object->operator[](it.key()) = it.value();
  18953. }
  18954. }
  18955. /*!
  18956. @brief exchanges the values
  18957. Exchanges the contents of the JSON value with those of @a other. Does not
  18958. invoke any move, copy, or swap operations on individual elements. All
  18959. iterators and references remain valid. The past-the-end iterator is
  18960. invalidated.
  18961. @param[in,out] other JSON value to exchange the contents with
  18962. @complexity Constant.
  18963. @liveexample{The example below shows how JSON values can be swapped with
  18964. `swap()`.,swap__reference}
  18965. @since version 1.0.0
  18966. */
  18967. void swap(reference other) noexcept (
  18968. std::is_nothrow_move_constructible<value_t>::value&&
  18969. std::is_nothrow_move_assignable<value_t>::value&&
  18970. std::is_nothrow_move_constructible<json_value>::value&&
  18971. std::is_nothrow_move_assignable<json_value>::value
  18972. )
  18973. {
  18974. std::swap(m_type, other.m_type);
  18975. std::swap(m_value, other.m_value);
  18976. assert_invariant();
  18977. }
  18978. /*!
  18979. @brief exchanges the values
  18980. Exchanges the contents of the JSON value from @a left with those of @a right. Does not
  18981. invoke any move, copy, or swap operations on individual elements. All
  18982. iterators and references remain valid. The past-the-end iterator is
  18983. invalidated. implemented as a friend function callable via ADL.
  18984. @param[in,out] left JSON value to exchange the contents with
  18985. @param[in,out] right JSON value to exchange the contents with
  18986. @complexity Constant.
  18987. @liveexample{The example below shows how JSON values can be swapped with
  18988. `swap()`.,swap__reference}
  18989. @since version 1.0.0
  18990. */
  18991. friend void swap(reference left, reference right) noexcept (
  18992. std::is_nothrow_move_constructible<value_t>::value&&
  18993. std::is_nothrow_move_assignable<value_t>::value&&
  18994. std::is_nothrow_move_constructible<json_value>::value&&
  18995. std::is_nothrow_move_assignable<json_value>::value
  18996. )
  18997. {
  18998. left.swap(right);
  18999. }
  19000. /*!
  19001. @brief exchanges the values
  19002. Exchanges the contents of a JSON array with those of @a other. Does not
  19003. invoke any move, copy, or swap operations on individual elements. All
  19004. iterators and references remain valid. The past-the-end iterator is
  19005. invalidated.
  19006. @param[in,out] other array to exchange the contents with
  19007. @throw type_error.310 when JSON value is not an array; example: `"cannot
  19008. use swap() with string"`
  19009. @complexity Constant.
  19010. @liveexample{The example below shows how arrays can be swapped with
  19011. `swap()`.,swap__array_t}
  19012. @since version 1.0.0
  19013. */
  19014. void swap(array_t& other)
  19015. {
  19016. // swap only works for arrays
  19017. if (JSON_HEDLEY_LIKELY(is_array()))
  19018. {
  19019. std::swap(*(m_value.array), other);
  19020. }
  19021. else
  19022. {
  19023. JSON_THROW(type_error::create(310, "cannot use swap() with " + std::string(type_name())));
  19024. }
  19025. }
  19026. /*!
  19027. @brief exchanges the values
  19028. Exchanges the contents of a JSON object with those of @a other. Does not
  19029. invoke any move, copy, or swap operations on individual elements. All
  19030. iterators and references remain valid. The past-the-end iterator is
  19031. invalidated.
  19032. @param[in,out] other object to exchange the contents with
  19033. @throw type_error.310 when JSON value is not an object; example:
  19034. `"cannot use swap() with string"`
  19035. @complexity Constant.
  19036. @liveexample{The example below shows how objects can be swapped with
  19037. `swap()`.,swap__object_t}
  19038. @since version 1.0.0
  19039. */
  19040. void swap(object_t& other)
  19041. {
  19042. // swap only works for objects
  19043. if (JSON_HEDLEY_LIKELY(is_object()))
  19044. {
  19045. std::swap(*(m_value.object), other);
  19046. }
  19047. else
  19048. {
  19049. JSON_THROW(type_error::create(310, "cannot use swap() with " + std::string(type_name())));
  19050. }
  19051. }
  19052. /*!
  19053. @brief exchanges the values
  19054. Exchanges the contents of a JSON string with those of @a other. Does not
  19055. invoke any move, copy, or swap operations on individual elements. All
  19056. iterators and references remain valid. The past-the-end iterator is
  19057. invalidated.
  19058. @param[in,out] other string to exchange the contents with
  19059. @throw type_error.310 when JSON value is not a string; example: `"cannot
  19060. use swap() with boolean"`
  19061. @complexity Constant.
  19062. @liveexample{The example below shows how strings can be swapped with
  19063. `swap()`.,swap__string_t}
  19064. @since version 1.0.0
  19065. */
  19066. void swap(string_t& other)
  19067. {
  19068. // swap only works for strings
  19069. if (JSON_HEDLEY_LIKELY(is_string()))
  19070. {
  19071. std::swap(*(m_value.string), other);
  19072. }
  19073. else
  19074. {
  19075. JSON_THROW(type_error::create(310, "cannot use swap() with " + std::string(type_name())));
  19076. }
  19077. }
  19078. /*!
  19079. @brief exchanges the values
  19080. Exchanges the contents of a JSON string with those of @a other. Does not
  19081. invoke any move, copy, or swap operations on individual elements. All
  19082. iterators and references remain valid. The past-the-end iterator is
  19083. invalidated.
  19084. @param[in,out] other binary to exchange the contents with
  19085. @throw type_error.310 when JSON value is not a string; example: `"cannot
  19086. use swap() with boolean"`
  19087. @complexity Constant.
  19088. @liveexample{The example below shows how strings can be swapped with
  19089. `swap()`.,swap__binary_t}
  19090. @since version 3.8.0
  19091. */
  19092. void swap(binary_t& other)
  19093. {
  19094. // swap only works for strings
  19095. if (JSON_HEDLEY_LIKELY(is_binary()))
  19096. {
  19097. std::swap(*(m_value.binary), other);
  19098. }
  19099. else
  19100. {
  19101. JSON_THROW(type_error::create(310, "cannot use swap() with " + std::string(type_name())));
  19102. }
  19103. }
  19104. /// @copydoc swap(binary_t)
  19105. void swap(typename binary_t::container_type& other)
  19106. {
  19107. // swap only works for strings
  19108. if (JSON_HEDLEY_LIKELY(is_binary()))
  19109. {
  19110. std::swap(*(m_value.binary), other);
  19111. }
  19112. else
  19113. {
  19114. JSON_THROW(type_error::create(310, "cannot use swap() with " + std::string(type_name())));
  19115. }
  19116. }
  19117. /// @}
  19118. public:
  19119. //////////////////////////////////////////
  19120. // lexicographical comparison operators //
  19121. //////////////////////////////////////////
  19122. /// @name lexicographical comparison operators
  19123. /// @{
  19124. /*!
  19125. @brief comparison: equal
  19126. Compares two JSON values for equality according to the following rules:
  19127. - Two JSON values are equal if (1) they are from the same type and (2)
  19128. their stored values are the same according to their respective
  19129. `operator==`.
  19130. - Integer and floating-point numbers are automatically converted before
  19131. comparison. Note that two NaN values are always treated as unequal.
  19132. - Two JSON null values are equal.
  19133. @note Floating-point inside JSON values numbers are compared with
  19134. `json::number_float_t::operator==` which is `double::operator==` by
  19135. default. To compare floating-point while respecting an epsilon, an alternative
  19136. [comparison function](https://github.com/mariokonrad/marnav/blob/master/include/marnav/math/floatingpoint.hpp#L34-#L39)
  19137. could be used, for instance
  19138. @code {.cpp}
  19139. template<typename T, typename = typename std::enable_if<std::is_floating_point<T>::value, T>::type>
  19140. inline bool is_same(T a, T b, T epsilon = std::numeric_limits<T>::epsilon()) noexcept
  19141. {
  19142. return std::abs(a - b) <= epsilon;
  19143. }
  19144. @endcode
  19145. Or you can self-defined operator equal function like this:
  19146. @code {.cpp}
  19147. bool my_equal(const_reference lhs, const_reference rhs) {
  19148. const auto lhs_type lhs.type();
  19149. const auto rhs_type rhs.type();
  19150. if (lhs_type == rhs_type) {
  19151. switch(lhs_type)
  19152. // self_defined case
  19153. case value_t::number_float:
  19154. return std::abs(lhs - rhs) <= std::numeric_limits<float>::epsilon();
  19155. // other cases remain the same with the original
  19156. ...
  19157. }
  19158. ...
  19159. }
  19160. @endcode
  19161. @note NaN values never compare equal to themselves or to other NaN values.
  19162. @param[in] lhs first JSON value to consider
  19163. @param[in] rhs second JSON value to consider
  19164. @return whether the values @a lhs and @a rhs are equal
  19165. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  19166. @complexity Linear.
  19167. @liveexample{The example demonstrates comparing several JSON
  19168. types.,operator__equal}
  19169. @since version 1.0.0
  19170. */
  19171. friend bool operator==(const_reference lhs, const_reference rhs) noexcept
  19172. {
  19173. const auto lhs_type = lhs.type();
  19174. const auto rhs_type = rhs.type();
  19175. if (lhs_type == rhs_type)
  19176. {
  19177. switch (lhs_type)
  19178. {
  19179. case value_t::array:
  19180. return *lhs.m_value.array == *rhs.m_value.array;
  19181. case value_t::object:
  19182. return *lhs.m_value.object == *rhs.m_value.object;
  19183. case value_t::null:
  19184. return true;
  19185. case value_t::string:
  19186. return *lhs.m_value.string == *rhs.m_value.string;
  19187. case value_t::boolean:
  19188. return lhs.m_value.boolean == rhs.m_value.boolean;
  19189. case value_t::number_integer:
  19190. return lhs.m_value.number_integer == rhs.m_value.number_integer;
  19191. case value_t::number_unsigned:
  19192. return lhs.m_value.number_unsigned == rhs.m_value.number_unsigned;
  19193. case value_t::number_float:
  19194. return lhs.m_value.number_float == rhs.m_value.number_float;
  19195. case value_t::binary:
  19196. return *lhs.m_value.binary == *rhs.m_value.binary;
  19197. default:
  19198. return false;
  19199. }
  19200. }
  19201. else if (lhs_type == value_t::number_integer && rhs_type == value_t::number_float)
  19202. {
  19203. return static_cast<number_float_t>(lhs.m_value.number_integer) == rhs.m_value.number_float;
  19204. }
  19205. else if (lhs_type == value_t::number_float && rhs_type == value_t::number_integer)
  19206. {
  19207. return lhs.m_value.number_float == static_cast<number_float_t>(rhs.m_value.number_integer);
  19208. }
  19209. else if (lhs_type == value_t::number_unsigned && rhs_type == value_t::number_float)
  19210. {
  19211. return static_cast<number_float_t>(lhs.m_value.number_unsigned) == rhs.m_value.number_float;
  19212. }
  19213. else if (lhs_type == value_t::number_float && rhs_type == value_t::number_unsigned)
  19214. {
  19215. return lhs.m_value.number_float == static_cast<number_float_t>(rhs.m_value.number_unsigned);
  19216. }
  19217. else if (lhs_type == value_t::number_unsigned && rhs_type == value_t::number_integer)
  19218. {
  19219. return static_cast<number_integer_t>(lhs.m_value.number_unsigned) == rhs.m_value.number_integer;
  19220. }
  19221. else if (lhs_type == value_t::number_integer && rhs_type == value_t::number_unsigned)
  19222. {
  19223. return lhs.m_value.number_integer == static_cast<number_integer_t>(rhs.m_value.number_unsigned);
  19224. }
  19225. return false;
  19226. }
  19227. /*!
  19228. @brief comparison: equal
  19229. @copydoc operator==(const_reference, const_reference)
  19230. */
  19231. template<typename ScalarType, typename std::enable_if<
  19232. std::is_scalar<ScalarType>::value, int>::type = 0>
  19233. friend bool operator==(const_reference lhs, const ScalarType rhs) noexcept
  19234. {
  19235. return lhs == basic_json(rhs);
  19236. }
  19237. /*!
  19238. @brief comparison: equal
  19239. @copydoc operator==(const_reference, const_reference)
  19240. */
  19241. template<typename ScalarType, typename std::enable_if<
  19242. std::is_scalar<ScalarType>::value, int>::type = 0>
  19243. friend bool operator==(const ScalarType lhs, const_reference rhs) noexcept
  19244. {
  19245. return basic_json(lhs) == rhs;
  19246. }
  19247. /*!
  19248. @brief comparison: not equal
  19249. Compares two JSON values for inequality by calculating `not (lhs == rhs)`.
  19250. @param[in] lhs first JSON value to consider
  19251. @param[in] rhs second JSON value to consider
  19252. @return whether the values @a lhs and @a rhs are not equal
  19253. @complexity Linear.
  19254. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  19255. @liveexample{The example demonstrates comparing several JSON
  19256. types.,operator__notequal}
  19257. @since version 1.0.0
  19258. */
  19259. friend bool operator!=(const_reference lhs, const_reference rhs) noexcept
  19260. {
  19261. return !(lhs == rhs);
  19262. }
  19263. /*!
  19264. @brief comparison: not equal
  19265. @copydoc operator!=(const_reference, const_reference)
  19266. */
  19267. template<typename ScalarType, typename std::enable_if<
  19268. std::is_scalar<ScalarType>::value, int>::type = 0>
  19269. friend bool operator!=(const_reference lhs, const ScalarType rhs) noexcept
  19270. {
  19271. return lhs != basic_json(rhs);
  19272. }
  19273. /*!
  19274. @brief comparison: not equal
  19275. @copydoc operator!=(const_reference, const_reference)
  19276. */
  19277. template<typename ScalarType, typename std::enable_if<
  19278. std::is_scalar<ScalarType>::value, int>::type = 0>
  19279. friend bool operator!=(const ScalarType lhs, const_reference rhs) noexcept
  19280. {
  19281. return basic_json(lhs) != rhs;
  19282. }
  19283. /*!
  19284. @brief comparison: less than
  19285. Compares whether one JSON value @a lhs is less than another JSON value @a
  19286. rhs according to the following rules:
  19287. - If @a lhs and @a rhs have the same type, the values are compared using
  19288. the default `<` operator.
  19289. - Integer and floating-point numbers are automatically converted before
  19290. comparison
  19291. - In case @a lhs and @a rhs have different types, the values are ignored
  19292. and the order of the types is considered, see
  19293. @ref operator<(const value_t, const value_t).
  19294. @param[in] lhs first JSON value to consider
  19295. @param[in] rhs second JSON value to consider
  19296. @return whether @a lhs is less than @a rhs
  19297. @complexity Linear.
  19298. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  19299. @liveexample{The example demonstrates comparing several JSON
  19300. types.,operator__less}
  19301. @since version 1.0.0
  19302. */
  19303. friend bool operator<(const_reference lhs, const_reference rhs) noexcept
  19304. {
  19305. const auto lhs_type = lhs.type();
  19306. const auto rhs_type = rhs.type();
  19307. if (lhs_type == rhs_type)
  19308. {
  19309. switch (lhs_type)
  19310. {
  19311. case value_t::array:
  19312. // note parentheses are necessary, see
  19313. // https://github.com/nlohmann/json/issues/1530
  19314. return (*lhs.m_value.array) < (*rhs.m_value.array);
  19315. case value_t::object:
  19316. return (*lhs.m_value.object) < (*rhs.m_value.object);
  19317. case value_t::null:
  19318. return false;
  19319. case value_t::string:
  19320. return (*lhs.m_value.string) < (*rhs.m_value.string);
  19321. case value_t::boolean:
  19322. return (lhs.m_value.boolean) < (rhs.m_value.boolean);
  19323. case value_t::number_integer:
  19324. return (lhs.m_value.number_integer) < (rhs.m_value.number_integer);
  19325. case value_t::number_unsigned:
  19326. return (lhs.m_value.number_unsigned) < (rhs.m_value.number_unsigned);
  19327. case value_t::number_float:
  19328. return (lhs.m_value.number_float) < (rhs.m_value.number_float);
  19329. case value_t::binary:
  19330. return (*lhs.m_value.binary) < (*rhs.m_value.binary);
  19331. default:
  19332. return false;
  19333. }
  19334. }
  19335. else if (lhs_type == value_t::number_integer && rhs_type == value_t::number_float)
  19336. {
  19337. return static_cast<number_float_t>(lhs.m_value.number_integer) < rhs.m_value.number_float;
  19338. }
  19339. else if (lhs_type == value_t::number_float && rhs_type == value_t::number_integer)
  19340. {
  19341. return lhs.m_value.number_float < static_cast<number_float_t>(rhs.m_value.number_integer);
  19342. }
  19343. else if (lhs_type == value_t::number_unsigned && rhs_type == value_t::number_float)
  19344. {
  19345. return static_cast<number_float_t>(lhs.m_value.number_unsigned) < rhs.m_value.number_float;
  19346. }
  19347. else if (lhs_type == value_t::number_float && rhs_type == value_t::number_unsigned)
  19348. {
  19349. return lhs.m_value.number_float < static_cast<number_float_t>(rhs.m_value.number_unsigned);
  19350. }
  19351. else if (lhs_type == value_t::number_integer && rhs_type == value_t::number_unsigned)
  19352. {
  19353. return lhs.m_value.number_integer < static_cast<number_integer_t>(rhs.m_value.number_unsigned);
  19354. }
  19355. else if (lhs_type == value_t::number_unsigned && rhs_type == value_t::number_integer)
  19356. {
  19357. return static_cast<number_integer_t>(lhs.m_value.number_unsigned) < rhs.m_value.number_integer;
  19358. }
  19359. // We only reach this line if we cannot compare values. In that case,
  19360. // we compare types. Note we have to call the operator explicitly,
  19361. // because MSVC has problems otherwise.
  19362. return operator<(lhs_type, rhs_type);
  19363. }
  19364. /*!
  19365. @brief comparison: less than
  19366. @copydoc operator<(const_reference, const_reference)
  19367. */
  19368. template<typename ScalarType, typename std::enable_if<
  19369. std::is_scalar<ScalarType>::value, int>::type = 0>
  19370. friend bool operator<(const_reference lhs, const ScalarType rhs) noexcept
  19371. {
  19372. return lhs < basic_json(rhs);
  19373. }
  19374. /*!
  19375. @brief comparison: less than
  19376. @copydoc operator<(const_reference, const_reference)
  19377. */
  19378. template<typename ScalarType, typename std::enable_if<
  19379. std::is_scalar<ScalarType>::value, int>::type = 0>
  19380. friend bool operator<(const ScalarType lhs, const_reference rhs) noexcept
  19381. {
  19382. return basic_json(lhs) < rhs;
  19383. }
  19384. /*!
  19385. @brief comparison: less than or equal
  19386. Compares whether one JSON value @a lhs is less than or equal to another
  19387. JSON value by calculating `not (rhs < lhs)`.
  19388. @param[in] lhs first JSON value to consider
  19389. @param[in] rhs second JSON value to consider
  19390. @return whether @a lhs is less than or equal to @a rhs
  19391. @complexity Linear.
  19392. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  19393. @liveexample{The example demonstrates comparing several JSON
  19394. types.,operator__greater}
  19395. @since version 1.0.0
  19396. */
  19397. friend bool operator<=(const_reference lhs, const_reference rhs) noexcept
  19398. {
  19399. return !(rhs < lhs);
  19400. }
  19401. /*!
  19402. @brief comparison: less than or equal
  19403. @copydoc operator<=(const_reference, const_reference)
  19404. */
  19405. template<typename ScalarType, typename std::enable_if<
  19406. std::is_scalar<ScalarType>::value, int>::type = 0>
  19407. friend bool operator<=(const_reference lhs, const ScalarType rhs) noexcept
  19408. {
  19409. return lhs <= basic_json(rhs);
  19410. }
  19411. /*!
  19412. @brief comparison: less than or equal
  19413. @copydoc operator<=(const_reference, const_reference)
  19414. */
  19415. template<typename ScalarType, typename std::enable_if<
  19416. std::is_scalar<ScalarType>::value, int>::type = 0>
  19417. friend bool operator<=(const ScalarType lhs, const_reference rhs) noexcept
  19418. {
  19419. return basic_json(lhs) <= rhs;
  19420. }
  19421. /*!
  19422. @brief comparison: greater than
  19423. Compares whether one JSON value @a lhs is greater than another
  19424. JSON value by calculating `not (lhs <= rhs)`.
  19425. @param[in] lhs first JSON value to consider
  19426. @param[in] rhs second JSON value to consider
  19427. @return whether @a lhs is greater than to @a rhs
  19428. @complexity Linear.
  19429. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  19430. @liveexample{The example demonstrates comparing several JSON
  19431. types.,operator__lessequal}
  19432. @since version 1.0.0
  19433. */
  19434. friend bool operator>(const_reference lhs, const_reference rhs) noexcept
  19435. {
  19436. return !(lhs <= rhs);
  19437. }
  19438. /*!
  19439. @brief comparison: greater than
  19440. @copydoc operator>(const_reference, const_reference)
  19441. */
  19442. template<typename ScalarType, typename std::enable_if<
  19443. std::is_scalar<ScalarType>::value, int>::type = 0>
  19444. friend bool operator>(const_reference lhs, const ScalarType rhs) noexcept
  19445. {
  19446. return lhs > basic_json(rhs);
  19447. }
  19448. /*!
  19449. @brief comparison: greater than
  19450. @copydoc operator>(const_reference, const_reference)
  19451. */
  19452. template<typename ScalarType, typename std::enable_if<
  19453. std::is_scalar<ScalarType>::value, int>::type = 0>
  19454. friend bool operator>(const ScalarType lhs, const_reference rhs) noexcept
  19455. {
  19456. return basic_json(lhs) > rhs;
  19457. }
  19458. /*!
  19459. @brief comparison: greater than or equal
  19460. Compares whether one JSON value @a lhs is greater than or equal to another
  19461. JSON value by calculating `not (lhs < rhs)`.
  19462. @param[in] lhs first JSON value to consider
  19463. @param[in] rhs second JSON value to consider
  19464. @return whether @a lhs is greater than or equal to @a rhs
  19465. @complexity Linear.
  19466. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  19467. @liveexample{The example demonstrates comparing several JSON
  19468. types.,operator__greaterequal}
  19469. @since version 1.0.0
  19470. */
  19471. friend bool operator>=(const_reference lhs, const_reference rhs) noexcept
  19472. {
  19473. return !(lhs < rhs);
  19474. }
  19475. /*!
  19476. @brief comparison: greater than or equal
  19477. @copydoc operator>=(const_reference, const_reference)
  19478. */
  19479. template<typename ScalarType, typename std::enable_if<
  19480. std::is_scalar<ScalarType>::value, int>::type = 0>
  19481. friend bool operator>=(const_reference lhs, const ScalarType rhs) noexcept
  19482. {
  19483. return lhs >= basic_json(rhs);
  19484. }
  19485. /*!
  19486. @brief comparison: greater than or equal
  19487. @copydoc operator>=(const_reference, const_reference)
  19488. */
  19489. template<typename ScalarType, typename std::enable_if<
  19490. std::is_scalar<ScalarType>::value, int>::type = 0>
  19491. friend bool operator>=(const ScalarType lhs, const_reference rhs) noexcept
  19492. {
  19493. return basic_json(lhs) >= rhs;
  19494. }
  19495. /// @}
  19496. ///////////////////
  19497. // serialization //
  19498. ///////////////////
  19499. /// @name serialization
  19500. /// @{
  19501. /*!
  19502. @brief serialize to stream
  19503. Serialize the given JSON value @a j to the output stream @a o. The JSON
  19504. value will be serialized using the @ref dump member function.
  19505. - The indentation of the output can be controlled with the member variable
  19506. `width` of the output stream @a o. For instance, using the manipulator
  19507. `std::setw(4)` on @a o sets the indentation level to `4` and the
  19508. serialization result is the same as calling `dump(4)`.
  19509. - The indentation character can be controlled with the member variable
  19510. `fill` of the output stream @a o. For instance, the manipulator
  19511. `std::setfill('\\t')` sets indentation to use a tab character rather than
  19512. the default space character.
  19513. @param[in,out] o stream to serialize to
  19514. @param[in] j JSON value to serialize
  19515. @return the stream @a o
  19516. @throw type_error.316 if a string stored inside the JSON value is not
  19517. UTF-8 encoded
  19518. @complexity Linear.
  19519. @liveexample{The example below shows the serialization with different
  19520. parameters to `width` to adjust the indentation level.,operator_serialize}
  19521. @since version 1.0.0; indentation character added in version 3.0.0
  19522. */
  19523. friend std::ostream& operator<<(std::ostream& o, const basic_json& j)
  19524. {
  19525. // read width member and use it as indentation parameter if nonzero
  19526. const bool pretty_print = o.width() > 0;
  19527. const auto indentation = pretty_print ? o.width() : 0;
  19528. // reset width to 0 for subsequent calls to this stream
  19529. o.width(0);
  19530. // do the actual serialization
  19531. serializer s(detail::output_adapter<char>(o), o.fill());
  19532. s.dump(j, pretty_print, false, static_cast<unsigned int>(indentation));
  19533. return o;
  19534. }
  19535. /*!
  19536. @brief serialize to stream
  19537. @deprecated This stream operator is deprecated and will be removed in
  19538. future 4.0.0 of the library. Please use
  19539. @ref operator<<(std::ostream&, const basic_json&)
  19540. instead; that is, replace calls like `j >> o;` with `o << j;`.
  19541. @since version 1.0.0; deprecated since version 3.0.0
  19542. */
  19543. JSON_HEDLEY_DEPRECATED_FOR(3.0.0, operator<<(std::ostream&, const basic_json&))
  19544. friend std::ostream& operator>>(const basic_json& j, std::ostream& o)
  19545. {
  19546. return o << j;
  19547. }
  19548. /// @}
  19549. /////////////////////
  19550. // deserialization //
  19551. /////////////////////
  19552. /// @name deserialization
  19553. /// @{
  19554. /*!
  19555. @brief deserialize from a compatible input
  19556. @tparam InputType A compatible input, for instance
  19557. - an std::istream object
  19558. - a FILE pointer
  19559. - a C-style array of characters
  19560. - a pointer to a null-terminated string of single byte characters
  19561. - an object obj for which begin(obj) and end(obj) produces a valid pair of
  19562. iterators.
  19563. @param[in] i input to read from
  19564. @param[in] cb a parser callback function of type @ref parser_callback_t
  19565. which is used to control the deserialization by filtering unwanted values
  19566. (optional)
  19567. @param[in] allow_exceptions whether to throw exceptions in case of a
  19568. parse error (optional, true by default)
  19569. @param[in] ignore_comments whether comments should be ignored and treated
  19570. like whitespace (true) or yield a parse error (true); (optional, false by
  19571. default)
  19572. @return deserialized JSON value; in case of a parse error and
  19573. @a allow_exceptions set to `false`, the return value will be
  19574. value_t::discarded.
  19575. @throw parse_error.101 if a parse error occurs; example: `""unexpected end
  19576. of input; expected string literal""`
  19577. @throw parse_error.102 if to_unicode fails or surrogate error
  19578. @throw parse_error.103 if to_unicode fails
  19579. @complexity Linear in the length of the input. The parser is a predictive
  19580. LL(1) parser. The complexity can be higher if the parser callback function
  19581. @a cb or reading from the input @a i has a super-linear complexity.
  19582. @note A UTF-8 byte order mark is silently ignored.
  19583. @liveexample{The example below demonstrates the `parse()` function reading
  19584. from an array.,parse__array__parser_callback_t}
  19585. @liveexample{The example below demonstrates the `parse()` function with
  19586. and without callback function.,parse__string__parser_callback_t}
  19587. @liveexample{The example below demonstrates the `parse()` function with
  19588. and without callback function.,parse__istream__parser_callback_t}
  19589. @liveexample{The example below demonstrates the `parse()` function reading
  19590. from a contiguous container.,parse__contiguouscontainer__parser_callback_t}
  19591. @since version 2.0.3 (contiguous containers); version 3.9.0 allowed to
  19592. ignore comments.
  19593. */
  19594. template<typename InputType>
  19595. JSON_HEDLEY_WARN_UNUSED_RESULT
  19596. static basic_json parse(InputType&& i,
  19597. const parser_callback_t cb = nullptr,
  19598. const bool allow_exceptions = true,
  19599. const bool ignore_comments = false)
  19600. {
  19601. basic_json result;
  19602. parser(detail::input_adapter(std::forward<InputType>(i)), cb, allow_exceptions, ignore_comments).parse(true, result);
  19603. return result;
  19604. }
  19605. /*!
  19606. @brief deserialize from a pair of character iterators
  19607. The value_type of the iterator must be a integral type with size of 1, 2 or
  19608. 4 bytes, which will be interpreted respectively as UTF-8, UTF-16 and UTF-32.
  19609. @param[in] first iterator to start of character range
  19610. @param[in] last iterator to end of character range
  19611. @param[in] cb a parser callback function of type @ref parser_callback_t
  19612. which is used to control the deserialization by filtering unwanted values
  19613. (optional)
  19614. @param[in] allow_exceptions whether to throw exceptions in case of a
  19615. parse error (optional, true by default)
  19616. @param[in] ignore_comments whether comments should be ignored and treated
  19617. like whitespace (true) or yield a parse error (true); (optional, false by
  19618. default)
  19619. @return deserialized JSON value; in case of a parse error and
  19620. @a allow_exceptions set to `false`, the return value will be
  19621. value_t::discarded.
  19622. @throw parse_error.101 if a parse error occurs; example: `""unexpected end
  19623. of input; expected string literal""`
  19624. @throw parse_error.102 if to_unicode fails or surrogate error
  19625. @throw parse_error.103 if to_unicode fails
  19626. */
  19627. template<typename IteratorType>
  19628. JSON_HEDLEY_WARN_UNUSED_RESULT
  19629. static basic_json parse(IteratorType first,
  19630. IteratorType last,
  19631. const parser_callback_t cb = nullptr,
  19632. const bool allow_exceptions = true,
  19633. const bool ignore_comments = false)
  19634. {
  19635. basic_json result;
  19636. parser(detail::input_adapter(std::move(first), std::move(last)), cb, allow_exceptions, ignore_comments).parse(true, result);
  19637. return result;
  19638. }
  19639. JSON_HEDLEY_WARN_UNUSED_RESULT
  19640. JSON_HEDLEY_DEPRECATED_FOR(3.8.0, parse(ptr, ptr + len))
  19641. static basic_json parse(detail::span_input_adapter&& i,
  19642. const parser_callback_t cb = nullptr,
  19643. const bool allow_exceptions = true,
  19644. const bool ignore_comments = false)
  19645. {
  19646. basic_json result;
  19647. parser(i.get(), cb, allow_exceptions, ignore_comments).parse(true, result);
  19648. return result;
  19649. }
  19650. /*!
  19651. @brief check if the input is valid JSON
  19652. Unlike the @ref parse(InputType&&, const parser_callback_t,const bool)
  19653. function, this function neither throws an exception in case of invalid JSON
  19654. input (i.e., a parse error) nor creates diagnostic information.
  19655. @tparam InputType A compatible input, for instance
  19656. - an std::istream object
  19657. - a FILE pointer
  19658. - a C-style array of characters
  19659. - a pointer to a null-terminated string of single byte characters
  19660. - an object obj for which begin(obj) and end(obj) produces a valid pair of
  19661. iterators.
  19662. @param[in] i input to read from
  19663. @param[in] ignore_comments whether comments should be ignored and treated
  19664. like whitespace (true) or yield a parse error (true); (optional, false by
  19665. default)
  19666. @return Whether the input read from @a i is valid JSON.
  19667. @complexity Linear in the length of the input. The parser is a predictive
  19668. LL(1) parser.
  19669. @note A UTF-8 byte order mark is silently ignored.
  19670. @liveexample{The example below demonstrates the `accept()` function reading
  19671. from a string.,accept__string}
  19672. */
  19673. template<typename InputType>
  19674. static bool accept(InputType&& i,
  19675. const bool ignore_comments = false)
  19676. {
  19677. return parser(detail::input_adapter(std::forward<InputType>(i)), nullptr, false, ignore_comments).accept(true);
  19678. }
  19679. template<typename IteratorType>
  19680. static bool accept(IteratorType first, IteratorType last,
  19681. const bool ignore_comments = false)
  19682. {
  19683. return parser(detail::input_adapter(std::move(first), std::move(last)), nullptr, false, ignore_comments).accept(true);
  19684. }
  19685. JSON_HEDLEY_WARN_UNUSED_RESULT
  19686. JSON_HEDLEY_DEPRECATED_FOR(3.8.0, accept(ptr, ptr + len))
  19687. static bool accept(detail::span_input_adapter&& i,
  19688. const bool ignore_comments = false)
  19689. {
  19690. return parser(i.get(), nullptr, false, ignore_comments).accept(true);
  19691. }
  19692. /*!
  19693. @brief generate SAX events
  19694. The SAX event lister must follow the interface of @ref json_sax.
  19695. This function reads from a compatible input. Examples are:
  19696. - an std::istream object
  19697. - a FILE pointer
  19698. - a C-style array of characters
  19699. - a pointer to a null-terminated string of single byte characters
  19700. - an object obj for which begin(obj) and end(obj) produces a valid pair of
  19701. iterators.
  19702. @param[in] i input to read from
  19703. @param[in,out] sax SAX event listener
  19704. @param[in] format the format to parse (JSON, CBOR, MessagePack, or UBJSON)
  19705. @param[in] strict whether the input has to be consumed completely
  19706. @param[in] ignore_comments whether comments should be ignored and treated
  19707. like whitespace (true) or yield a parse error (true); (optional, false by
  19708. default); only applies to the JSON file format.
  19709. @return return value of the last processed SAX event
  19710. @throw parse_error.101 if a parse error occurs; example: `""unexpected end
  19711. of input; expected string literal""`
  19712. @throw parse_error.102 if to_unicode fails or surrogate error
  19713. @throw parse_error.103 if to_unicode fails
  19714. @complexity Linear in the length of the input. The parser is a predictive
  19715. LL(1) parser. The complexity can be higher if the SAX consumer @a sax has
  19716. a super-linear complexity.
  19717. @note A UTF-8 byte order mark is silently ignored.
  19718. @liveexample{The example below demonstrates the `sax_parse()` function
  19719. reading from string and processing the events with a user-defined SAX
  19720. event consumer.,sax_parse}
  19721. @since version 3.2.0
  19722. */
  19723. template <typename InputType, typename SAX>
  19724. JSON_HEDLEY_NON_NULL(2)
  19725. static bool sax_parse(InputType&& i, SAX* sax,
  19726. input_format_t format = input_format_t::json,
  19727. const bool strict = true,
  19728. const bool ignore_comments = false)
  19729. {
  19730. auto ia = detail::input_adapter(std::forward<InputType>(i));
  19731. return format == input_format_t::json
  19732. ? parser(std::move(ia), nullptr, true, ignore_comments).sax_parse(sax, strict)
  19733. : detail::binary_reader<basic_json, decltype(ia), SAX>(std::move(ia)).sax_parse(format, sax, strict);
  19734. }
  19735. template<class IteratorType, class SAX>
  19736. JSON_HEDLEY_NON_NULL(3)
  19737. static bool sax_parse(IteratorType first, IteratorType last, SAX* sax,
  19738. input_format_t format = input_format_t::json,
  19739. const bool strict = true,
  19740. const bool ignore_comments = false)
  19741. {
  19742. auto ia = detail::input_adapter(std::move(first), std::move(last));
  19743. return format == input_format_t::json
  19744. ? parser(std::move(ia), nullptr, true, ignore_comments).sax_parse(sax, strict)
  19745. : detail::binary_reader<basic_json, decltype(ia), SAX>(std::move(ia)).sax_parse(format, sax, strict);
  19746. }
  19747. template <typename SAX>
  19748. JSON_HEDLEY_DEPRECATED_FOR(3.8.0, sax_parse(ptr, ptr + len, ...))
  19749. JSON_HEDLEY_NON_NULL(2)
  19750. static bool sax_parse(detail::span_input_adapter&& i, SAX* sax,
  19751. input_format_t format = input_format_t::json,
  19752. const bool strict = true,
  19753. const bool ignore_comments = false)
  19754. {
  19755. auto ia = i.get();
  19756. return format == input_format_t::json
  19757. ? parser(std::move(ia), nullptr, true, ignore_comments).sax_parse(sax, strict)
  19758. : detail::binary_reader<basic_json, decltype(ia), SAX>(std::move(ia)).sax_parse(format, sax, strict);
  19759. }
  19760. /*!
  19761. @brief deserialize from stream
  19762. @deprecated This stream operator is deprecated and will be removed in
  19763. version 4.0.0 of the library. Please use
  19764. @ref operator>>(std::istream&, basic_json&)
  19765. instead; that is, replace calls like `j << i;` with `i >> j;`.
  19766. @since version 1.0.0; deprecated since version 3.0.0
  19767. */
  19768. JSON_HEDLEY_DEPRECATED_FOR(3.0.0, operator>>(std::istream&, basic_json&))
  19769. friend std::istream& operator<<(basic_json& j, std::istream& i)
  19770. {
  19771. return operator>>(i, j);
  19772. }
  19773. /*!
  19774. @brief deserialize from stream
  19775. Deserializes an input stream to a JSON value.
  19776. @param[in,out] i input stream to read a serialized JSON value from
  19777. @param[in,out] j JSON value to write the deserialized input to
  19778. @throw parse_error.101 in case of an unexpected token
  19779. @throw parse_error.102 if to_unicode fails or surrogate error
  19780. @throw parse_error.103 if to_unicode fails
  19781. @complexity Linear in the length of the input. The parser is a predictive
  19782. LL(1) parser.
  19783. @note A UTF-8 byte order mark is silently ignored.
  19784. @liveexample{The example below shows how a JSON value is constructed by
  19785. reading a serialization from a stream.,operator_deserialize}
  19786. @sa parse(std::istream&, const parser_callback_t) for a variant with a
  19787. parser callback function to filter values while parsing
  19788. @since version 1.0.0
  19789. */
  19790. friend std::istream& operator>>(std::istream& i, basic_json& j)
  19791. {
  19792. parser(detail::input_adapter(i)).parse(false, j);
  19793. return i;
  19794. }
  19795. /// @}
  19796. ///////////////////////////
  19797. // convenience functions //
  19798. ///////////////////////////
  19799. /*!
  19800. @brief return the type as string
  19801. Returns the type name as string to be used in error messages - usually to
  19802. indicate that a function was called on a wrong JSON type.
  19803. @return a string representation of a the @a m_type member:
  19804. Value type | return value
  19805. ----------- | -------------
  19806. null | `"null"`
  19807. boolean | `"boolean"`
  19808. string | `"string"`
  19809. number | `"number"` (for all number types)
  19810. object | `"object"`
  19811. array | `"array"`
  19812. binary | `"binary"`
  19813. discarded | `"discarded"`
  19814. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  19815. @complexity Constant.
  19816. @liveexample{The following code exemplifies `type_name()` for all JSON
  19817. types.,type_name}
  19818. @sa @ref type() -- return the type of the JSON value
  19819. @sa @ref operator value_t() -- return the type of the JSON value (implicit)
  19820. @since version 1.0.0, public since 2.1.0, `const char*` and `noexcept`
  19821. since 3.0.0
  19822. */
  19823. JSON_HEDLEY_RETURNS_NON_NULL
  19824. const char* type_name() const noexcept
  19825. {
  19826. {
  19827. switch (m_type)
  19828. {
  19829. case value_t::null:
  19830. return "null";
  19831. case value_t::object:
  19832. return "object";
  19833. case value_t::array:
  19834. return "array";
  19835. case value_t::string:
  19836. return "string";
  19837. case value_t::boolean:
  19838. return "boolean";
  19839. case value_t::binary:
  19840. return "binary";
  19841. case value_t::discarded:
  19842. return "discarded";
  19843. default:
  19844. return "number";
  19845. }
  19846. }
  19847. }
  19848. private:
  19849. //////////////////////
  19850. // member variables //
  19851. //////////////////////
  19852. /// the type of the current element
  19853. value_t m_type = value_t::null;
  19854. /// the value of the current element
  19855. json_value m_value = {};
  19856. //////////////////////////////////////////
  19857. // binary serialization/deserialization //
  19858. //////////////////////////////////////////
  19859. /// @name binary serialization/deserialization support
  19860. /// @{
  19861. public:
  19862. /*!
  19863. @brief create a CBOR serialization of a given JSON value
  19864. Serializes a given JSON value @a j to a byte vector using the CBOR (Concise
  19865. Binary Object Representation) serialization format. CBOR is a binary
  19866. serialization format which aims to be more compact than JSON itself, yet
  19867. more efficient to parse.
  19868. The library uses the following mapping from JSON values types to
  19869. CBOR types according to the CBOR specification (RFC 7049):
  19870. JSON value type | value/range | CBOR type | first byte
  19871. --------------- | ------------------------------------------ | ---------------------------------- | ---------------
  19872. null | `null` | Null | 0xF6
  19873. boolean | `true` | True | 0xF5
  19874. boolean | `false` | False | 0xF4
  19875. number_integer | -9223372036854775808..-2147483649 | Negative integer (8 bytes follow) | 0x3B
  19876. number_integer | -2147483648..-32769 | Negative integer (4 bytes follow) | 0x3A
  19877. number_integer | -32768..-129 | Negative integer (2 bytes follow) | 0x39
  19878. number_integer | -128..-25 | Negative integer (1 byte follow) | 0x38
  19879. number_integer | -24..-1 | Negative integer | 0x20..0x37
  19880. number_integer | 0..23 | Integer | 0x00..0x17
  19881. number_integer | 24..255 | Unsigned integer (1 byte follow) | 0x18
  19882. number_integer | 256..65535 | Unsigned integer (2 bytes follow) | 0x19
  19883. number_integer | 65536..4294967295 | Unsigned integer (4 bytes follow) | 0x1A
  19884. number_integer | 4294967296..18446744073709551615 | Unsigned integer (8 bytes follow) | 0x1B
  19885. number_unsigned | 0..23 | Integer | 0x00..0x17
  19886. number_unsigned | 24..255 | Unsigned integer (1 byte follow) | 0x18
  19887. number_unsigned | 256..65535 | Unsigned integer (2 bytes follow) | 0x19
  19888. number_unsigned | 65536..4294967295 | Unsigned integer (4 bytes follow) | 0x1A
  19889. number_unsigned | 4294967296..18446744073709551615 | Unsigned integer (8 bytes follow) | 0x1B
  19890. number_float | *any value representable by a float* | Single-Precision Float | 0xFA
  19891. number_float | *any value NOT representable by a float* | Double-Precision Float | 0xFB
  19892. string | *length*: 0..23 | UTF-8 string | 0x60..0x77
  19893. string | *length*: 23..255 | UTF-8 string (1 byte follow) | 0x78
  19894. string | *length*: 256..65535 | UTF-8 string (2 bytes follow) | 0x79
  19895. string | *length*: 65536..4294967295 | UTF-8 string (4 bytes follow) | 0x7A
  19896. string | *length*: 4294967296..18446744073709551615 | UTF-8 string (8 bytes follow) | 0x7B
  19897. array | *size*: 0..23 | array | 0x80..0x97
  19898. array | *size*: 23..255 | array (1 byte follow) | 0x98
  19899. array | *size*: 256..65535 | array (2 bytes follow) | 0x99
  19900. array | *size*: 65536..4294967295 | array (4 bytes follow) | 0x9A
  19901. array | *size*: 4294967296..18446744073709551615 | array (8 bytes follow) | 0x9B
  19902. object | *size*: 0..23 | map | 0xA0..0xB7
  19903. object | *size*: 23..255 | map (1 byte follow) | 0xB8
  19904. object | *size*: 256..65535 | map (2 bytes follow) | 0xB9
  19905. object | *size*: 65536..4294967295 | map (4 bytes follow) | 0xBA
  19906. object | *size*: 4294967296..18446744073709551615 | map (8 bytes follow) | 0xBB
  19907. binary | *size*: 0..23 | byte string | 0x40..0x57
  19908. binary | *size*: 23..255 | byte string (1 byte follow) | 0x58
  19909. binary | *size*: 256..65535 | byte string (2 bytes follow) | 0x59
  19910. binary | *size*: 65536..4294967295 | byte string (4 bytes follow) | 0x5A
  19911. binary | *size*: 4294967296..18446744073709551615 | byte string (8 bytes follow) | 0x5B
  19912. @note The mapping is **complete** in the sense that any JSON value type
  19913. can be converted to a CBOR value.
  19914. @note If NaN or Infinity are stored inside a JSON number, they are
  19915. serialized properly. This behavior differs from the @ref dump()
  19916. function which serializes NaN or Infinity to `null`.
  19917. @note The following CBOR types are not used in the conversion:
  19918. - UTF-8 strings terminated by "break" (0x7F)
  19919. - arrays terminated by "break" (0x9F)
  19920. - maps terminated by "break" (0xBF)
  19921. - byte strings terminated by "break" (0x5F)
  19922. - date/time (0xC0..0xC1)
  19923. - bignum (0xC2..0xC3)
  19924. - decimal fraction (0xC4)
  19925. - bigfloat (0xC5)
  19926. - expected conversions (0xD5..0xD7)
  19927. - simple values (0xE0..0xF3, 0xF8)
  19928. - undefined (0xF7)
  19929. - half-precision floats (0xF9)
  19930. - break (0xFF)
  19931. @param[in] j JSON value to serialize
  19932. @return CBOR serialization as byte vector
  19933. @complexity Linear in the size of the JSON value @a j.
  19934. @liveexample{The example shows the serialization of a JSON value to a byte
  19935. vector in CBOR format.,to_cbor}
  19936. @sa http://cbor.io
  19937. @sa @ref from_cbor(detail::input_adapter&&, const bool, const bool, const cbor_tag_handler_t) for the
  19938. analogous deserialization
  19939. @sa @ref to_msgpack(const basic_json&) for the related MessagePack format
  19940. @sa @ref to_ubjson(const basic_json&, const bool, const bool) for the
  19941. related UBJSON format
  19942. @since version 2.0.9; compact representation of floating-point numbers
  19943. since version 3.8.0
  19944. */
  19945. static std::vector<uint8_t> to_cbor(const basic_json& j)
  19946. {
  19947. std::vector<uint8_t> result;
  19948. to_cbor(j, result);
  19949. return result;
  19950. }
  19951. static void to_cbor(const basic_json& j, detail::output_adapter<uint8_t> o)
  19952. {
  19953. binary_writer<uint8_t>(o).write_cbor(j);
  19954. }
  19955. static void to_cbor(const basic_json& j, detail::output_adapter<char> o)
  19956. {
  19957. binary_writer<char>(o).write_cbor(j);
  19958. }
  19959. /*!
  19960. @brief create a MessagePack serialization of a given JSON value
  19961. Serializes a given JSON value @a j to a byte vector using the MessagePack
  19962. serialization format. MessagePack is a binary serialization format which
  19963. aims to be more compact than JSON itself, yet more efficient to parse.
  19964. The library uses the following mapping from JSON values types to
  19965. MessagePack types according to the MessagePack specification:
  19966. JSON value type | value/range | MessagePack type | first byte
  19967. --------------- | --------------------------------- | ---------------- | ----------
  19968. null | `null` | nil | 0xC0
  19969. boolean | `true` | true | 0xC3
  19970. boolean | `false` | false | 0xC2
  19971. number_integer | -9223372036854775808..-2147483649 | int64 | 0xD3
  19972. number_integer | -2147483648..-32769 | int32 | 0xD2
  19973. number_integer | -32768..-129 | int16 | 0xD1
  19974. number_integer | -128..-33 | int8 | 0xD0
  19975. number_integer | -32..-1 | negative fixint | 0xE0..0xFF
  19976. number_integer | 0..127 | positive fixint | 0x00..0x7F
  19977. number_integer | 128..255 | uint 8 | 0xCC
  19978. number_integer | 256..65535 | uint 16 | 0xCD
  19979. number_integer | 65536..4294967295 | uint 32 | 0xCE
  19980. number_integer | 4294967296..18446744073709551615 | uint 64 | 0xCF
  19981. number_unsigned | 0..127 | positive fixint | 0x00..0x7F
  19982. number_unsigned | 128..255 | uint 8 | 0xCC
  19983. number_unsigned | 256..65535 | uint 16 | 0xCD
  19984. number_unsigned | 65536..4294967295 | uint 32 | 0xCE
  19985. number_unsigned | 4294967296..18446744073709551615 | uint 64 | 0xCF
  19986. number_float | *any value representable by a float* | float 32 | 0xCA
  19987. number_float | *any value NOT representable by a float* | float 64 | 0xCB
  19988. string | *length*: 0..31 | fixstr | 0xA0..0xBF
  19989. string | *length*: 32..255 | str 8 | 0xD9
  19990. string | *length*: 256..65535 | str 16 | 0xDA
  19991. string | *length*: 65536..4294967295 | str 32 | 0xDB
  19992. array | *size*: 0..15 | fixarray | 0x90..0x9F
  19993. array | *size*: 16..65535 | array 16 | 0xDC
  19994. array | *size*: 65536..4294967295 | array 32 | 0xDD
  19995. object | *size*: 0..15 | fix map | 0x80..0x8F
  19996. object | *size*: 16..65535 | map 16 | 0xDE
  19997. object | *size*: 65536..4294967295 | map 32 | 0xDF
  19998. binary | *size*: 0..255 | bin 8 | 0xC4
  19999. binary | *size*: 256..65535 | bin 16 | 0xC5
  20000. binary | *size*: 65536..4294967295 | bin 32 | 0xC6
  20001. @note The mapping is **complete** in the sense that any JSON value type
  20002. can be converted to a MessagePack value.
  20003. @note The following values can **not** be converted to a MessagePack value:
  20004. - strings with more than 4294967295 bytes
  20005. - byte strings with more than 4294967295 bytes
  20006. - arrays with more than 4294967295 elements
  20007. - objects with more than 4294967295 elements
  20008. @note Any MessagePack output created @ref to_msgpack can be successfully
  20009. parsed by @ref from_msgpack.
  20010. @note If NaN or Infinity are stored inside a JSON number, they are
  20011. serialized properly. This behavior differs from the @ref dump()
  20012. function which serializes NaN or Infinity to `null`.
  20013. @param[in] j JSON value to serialize
  20014. @return MessagePack serialization as byte vector
  20015. @complexity Linear in the size of the JSON value @a j.
  20016. @liveexample{The example shows the serialization of a JSON value to a byte
  20017. vector in MessagePack format.,to_msgpack}
  20018. @sa http://msgpack.org
  20019. @sa @ref from_msgpack for the analogous deserialization
  20020. @sa @ref to_cbor(const basic_json& for the related CBOR format
  20021. @sa @ref to_ubjson(const basic_json&, const bool, const bool) for the
  20022. related UBJSON format
  20023. @since version 2.0.9
  20024. */
  20025. static std::vector<uint8_t> to_msgpack(const basic_json& j)
  20026. {
  20027. std::vector<uint8_t> result;
  20028. to_msgpack(j, result);
  20029. return result;
  20030. }
  20031. static void to_msgpack(const basic_json& j, detail::output_adapter<uint8_t> o)
  20032. {
  20033. binary_writer<uint8_t>(o).write_msgpack(j);
  20034. }
  20035. static void to_msgpack(const basic_json& j, detail::output_adapter<char> o)
  20036. {
  20037. binary_writer<char>(o).write_msgpack(j);
  20038. }
  20039. /*!
  20040. @brief create a UBJSON serialization of a given JSON value
  20041. Serializes a given JSON value @a j to a byte vector using the UBJSON
  20042. (Universal Binary JSON) serialization format. UBJSON aims to be more compact
  20043. than JSON itself, yet more efficient to parse.
  20044. The library uses the following mapping from JSON values types to
  20045. UBJSON types according to the UBJSON specification:
  20046. JSON value type | value/range | UBJSON type | marker
  20047. --------------- | --------------------------------- | ----------- | ------
  20048. null | `null` | null | `Z`
  20049. boolean | `true` | true | `T`
  20050. boolean | `false` | false | `F`
  20051. number_integer | -9223372036854775808..-2147483649 | int64 | `L`
  20052. number_integer | -2147483648..-32769 | int32 | `l`
  20053. number_integer | -32768..-129 | int16 | `I`
  20054. number_integer | -128..127 | int8 | `i`
  20055. number_integer | 128..255 | uint8 | `U`
  20056. number_integer | 256..32767 | int16 | `I`
  20057. number_integer | 32768..2147483647 | int32 | `l`
  20058. number_integer | 2147483648..9223372036854775807 | int64 | `L`
  20059. number_unsigned | 0..127 | int8 | `i`
  20060. number_unsigned | 128..255 | uint8 | `U`
  20061. number_unsigned | 256..32767 | int16 | `I`
  20062. number_unsigned | 32768..2147483647 | int32 | `l`
  20063. number_unsigned | 2147483648..9223372036854775807 | int64 | `L`
  20064. number_unsigned | 2147483649..18446744073709551615 | high-precision | `H`
  20065. number_float | *any value* | float64 | `D`
  20066. string | *with shortest length indicator* | string | `S`
  20067. array | *see notes on optimized format* | array | `[`
  20068. object | *see notes on optimized format* | map | `{`
  20069. @note The mapping is **complete** in the sense that any JSON value type
  20070. can be converted to a UBJSON value.
  20071. @note The following values can **not** be converted to a UBJSON value:
  20072. - strings with more than 9223372036854775807 bytes (theoretical)
  20073. @note The following markers are not used in the conversion:
  20074. - `Z`: no-op values are not created.
  20075. - `C`: single-byte strings are serialized with `S` markers.
  20076. @note Any UBJSON output created @ref to_ubjson can be successfully parsed
  20077. by @ref from_ubjson.
  20078. @note If NaN or Infinity are stored inside a JSON number, they are
  20079. serialized properly. This behavior differs from the @ref dump()
  20080. function which serializes NaN or Infinity to `null`.
  20081. @note The optimized formats for containers are supported: Parameter
  20082. @a use_size adds size information to the beginning of a container and
  20083. removes the closing marker. Parameter @a use_type further checks
  20084. whether all elements of a container have the same type and adds the
  20085. type marker to the beginning of the container. The @a use_type
  20086. parameter must only be used together with @a use_size = true. Note
  20087. that @a use_size = true alone may result in larger representations -
  20088. the benefit of this parameter is that the receiving side is
  20089. immediately informed on the number of elements of the container.
  20090. @note If the JSON data contains the binary type, the value stored is a list
  20091. of integers, as suggested by the UBJSON documentation. In particular,
  20092. this means that serialization and the deserialization of a JSON
  20093. containing binary values into UBJSON and back will result in a
  20094. different JSON object.
  20095. @param[in] j JSON value to serialize
  20096. @param[in] use_size whether to add size annotations to container types
  20097. @param[in] use_type whether to add type annotations to container types
  20098. (must be combined with @a use_size = true)
  20099. @return UBJSON serialization as byte vector
  20100. @complexity Linear in the size of the JSON value @a j.
  20101. @liveexample{The example shows the serialization of a JSON value to a byte
  20102. vector in UBJSON format.,to_ubjson}
  20103. @sa http://ubjson.org
  20104. @sa @ref from_ubjson(detail::input_adapter&&, const bool, const bool) for the
  20105. analogous deserialization
  20106. @sa @ref to_cbor(const basic_json& for the related CBOR format
  20107. @sa @ref to_msgpack(const basic_json&) for the related MessagePack format
  20108. @since version 3.1.0
  20109. */
  20110. static std::vector<uint8_t> to_ubjson(const basic_json& j,
  20111. const bool use_size = false,
  20112. const bool use_type = false)
  20113. {
  20114. std::vector<uint8_t> result;
  20115. to_ubjson(j, result, use_size, use_type);
  20116. return result;
  20117. }
  20118. static void to_ubjson(const basic_json& j, detail::output_adapter<uint8_t> o,
  20119. const bool use_size = false, const bool use_type = false)
  20120. {
  20121. binary_writer<uint8_t>(o).write_ubjson(j, use_size, use_type);
  20122. }
  20123. static void to_ubjson(const basic_json& j, detail::output_adapter<char> o,
  20124. const bool use_size = false, const bool use_type = false)
  20125. {
  20126. binary_writer<char>(o).write_ubjson(j, use_size, use_type);
  20127. }
  20128. /*!
  20129. @brief Serializes the given JSON object `j` to BSON and returns a vector
  20130. containing the corresponding BSON-representation.
  20131. BSON (Binary JSON) is a binary format in which zero or more ordered key/value pairs are
  20132. stored as a single entity (a so-called document).
  20133. The library uses the following mapping from JSON values types to BSON types:
  20134. JSON value type | value/range | BSON type | marker
  20135. --------------- | --------------------------------- | ----------- | ------
  20136. null | `null` | null | 0x0A
  20137. boolean | `true`, `false` | boolean | 0x08
  20138. number_integer | -9223372036854775808..-2147483649 | int64 | 0x12
  20139. number_integer | -2147483648..2147483647 | int32 | 0x10
  20140. number_integer | 2147483648..9223372036854775807 | int64 | 0x12
  20141. number_unsigned | 0..2147483647 | int32 | 0x10
  20142. number_unsigned | 2147483648..9223372036854775807 | int64 | 0x12
  20143. number_unsigned | 9223372036854775808..18446744073709551615| -- | --
  20144. number_float | *any value* | double | 0x01
  20145. string | *any value* | string | 0x02
  20146. array | *any value* | document | 0x04
  20147. object | *any value* | document | 0x03
  20148. binary | *any value* | binary | 0x05
  20149. @warning The mapping is **incomplete**, since only JSON-objects (and things
  20150. contained therein) can be serialized to BSON.
  20151. Also, integers larger than 9223372036854775807 cannot be serialized to BSON,
  20152. and the keys may not contain U+0000, since they are serialized a
  20153. zero-terminated c-strings.
  20154. @throw out_of_range.407 if `j.is_number_unsigned() && j.get<std::uint64_t>() > 9223372036854775807`
  20155. @throw out_of_range.409 if a key in `j` contains a NULL (U+0000)
  20156. @throw type_error.317 if `!j.is_object()`
  20157. @pre The input `j` is required to be an object: `j.is_object() == true`.
  20158. @note Any BSON output created via @ref to_bson can be successfully parsed
  20159. by @ref from_bson.
  20160. @param[in] j JSON value to serialize
  20161. @return BSON serialization as byte vector
  20162. @complexity Linear in the size of the JSON value @a j.
  20163. @liveexample{The example shows the serialization of a JSON value to a byte
  20164. vector in BSON format.,to_bson}
  20165. @sa http://bsonspec.org/spec.html
  20166. @sa @ref from_bson(detail::input_adapter&&, const bool strict) for the
  20167. analogous deserialization
  20168. @sa @ref to_ubjson(const basic_json&, const bool, const bool) for the
  20169. related UBJSON format
  20170. @sa @ref to_cbor(const basic_json&) for the related CBOR format
  20171. @sa @ref to_msgpack(const basic_json&) for the related MessagePack format
  20172. */
  20173. static std::vector<uint8_t> to_bson(const basic_json& j)
  20174. {
  20175. std::vector<uint8_t> result;
  20176. to_bson(j, result);
  20177. return result;
  20178. }
  20179. /*!
  20180. @brief Serializes the given JSON object `j` to BSON and forwards the
  20181. corresponding BSON-representation to the given output_adapter `o`.
  20182. @param j The JSON object to convert to BSON.
  20183. @param o The output adapter that receives the binary BSON representation.
  20184. @pre The input `j` shall be an object: `j.is_object() == true`
  20185. @sa @ref to_bson(const basic_json&)
  20186. */
  20187. static void to_bson(const basic_json& j, detail::output_adapter<uint8_t> o)
  20188. {
  20189. binary_writer<uint8_t>(o).write_bson(j);
  20190. }
  20191. /*!
  20192. @copydoc to_bson(const basic_json&, detail::output_adapter<uint8_t>)
  20193. */
  20194. static void to_bson(const basic_json& j, detail::output_adapter<char> o)
  20195. {
  20196. binary_writer<char>(o).write_bson(j);
  20197. }
  20198. /*!
  20199. @brief create a JSON value from an input in CBOR format
  20200. Deserializes a given input @a i to a JSON value using the CBOR (Concise
  20201. Binary Object Representation) serialization format.
  20202. The library maps CBOR types to JSON value types as follows:
  20203. CBOR type | JSON value type | first byte
  20204. ---------------------- | --------------- | ----------
  20205. Integer | number_unsigned | 0x00..0x17
  20206. Unsigned integer | number_unsigned | 0x18
  20207. Unsigned integer | number_unsigned | 0x19
  20208. Unsigned integer | number_unsigned | 0x1A
  20209. Unsigned integer | number_unsigned | 0x1B
  20210. Negative integer | number_integer | 0x20..0x37
  20211. Negative integer | number_integer | 0x38
  20212. Negative integer | number_integer | 0x39
  20213. Negative integer | number_integer | 0x3A
  20214. Negative integer | number_integer | 0x3B
  20215. Byte string | binary | 0x40..0x57
  20216. Byte string | binary | 0x58
  20217. Byte string | binary | 0x59
  20218. Byte string | binary | 0x5A
  20219. Byte string | binary | 0x5B
  20220. UTF-8 string | string | 0x60..0x77
  20221. UTF-8 string | string | 0x78
  20222. UTF-8 string | string | 0x79
  20223. UTF-8 string | string | 0x7A
  20224. UTF-8 string | string | 0x7B
  20225. UTF-8 string | string | 0x7F
  20226. array | array | 0x80..0x97
  20227. array | array | 0x98
  20228. array | array | 0x99
  20229. array | array | 0x9A
  20230. array | array | 0x9B
  20231. array | array | 0x9F
  20232. map | object | 0xA0..0xB7
  20233. map | object | 0xB8
  20234. map | object | 0xB9
  20235. map | object | 0xBA
  20236. map | object | 0xBB
  20237. map | object | 0xBF
  20238. False | `false` | 0xF4
  20239. True | `true` | 0xF5
  20240. Null | `null` | 0xF6
  20241. Half-Precision Float | number_float | 0xF9
  20242. Single-Precision Float | number_float | 0xFA
  20243. Double-Precision Float | number_float | 0xFB
  20244. @warning The mapping is **incomplete** in the sense that not all CBOR
  20245. types can be converted to a JSON value. The following CBOR types
  20246. are not supported and will yield parse errors (parse_error.112):
  20247. - date/time (0xC0..0xC1)
  20248. - bignum (0xC2..0xC3)
  20249. - decimal fraction (0xC4)
  20250. - bigfloat (0xC5)
  20251. - expected conversions (0xD5..0xD7)
  20252. - simple values (0xE0..0xF3, 0xF8)
  20253. - undefined (0xF7)
  20254. @warning CBOR allows map keys of any type, whereas JSON only allows
  20255. strings as keys in object values. Therefore, CBOR maps with keys
  20256. other than UTF-8 strings are rejected (parse_error.113).
  20257. @note Any CBOR output created @ref to_cbor can be successfully parsed by
  20258. @ref from_cbor.
  20259. @param[in] i an input in CBOR format convertible to an input adapter
  20260. @param[in] strict whether to expect the input to be consumed until EOF
  20261. (true by default)
  20262. @param[in] allow_exceptions whether to throw exceptions in case of a
  20263. parse error (optional, true by default)
  20264. @param[in] tag_handler how to treat CBOR tags (optional, error by default)
  20265. @return deserialized JSON value; in case of a parse error and
  20266. @a allow_exceptions set to `false`, the return value will be
  20267. value_t::discarded.
  20268. @throw parse_error.110 if the given input ends prematurely or the end of
  20269. file was not reached when @a strict was set to true
  20270. @throw parse_error.112 if unsupported features from CBOR were
  20271. used in the given input @a v or if the input is not valid CBOR
  20272. @throw parse_error.113 if a string was expected as map key, but not found
  20273. @complexity Linear in the size of the input @a i.
  20274. @liveexample{The example shows the deserialization of a byte vector in CBOR
  20275. format to a JSON value.,from_cbor}
  20276. @sa http://cbor.io
  20277. @sa @ref to_cbor(const basic_json&) for the analogous serialization
  20278. @sa @ref from_msgpack(detail::input_adapter&&, const bool, const bool) for the
  20279. related MessagePack format
  20280. @sa @ref from_ubjson(detail::input_adapter&&, const bool, const bool) for the
  20281. related UBJSON format
  20282. @since version 2.0.9; parameter @a start_index since 2.1.1; changed to
  20283. consume input adapters, removed start_index parameter, and added
  20284. @a strict parameter since 3.0.0; added @a allow_exceptions parameter
  20285. since 3.2.0; added @a tag_handler parameter since 3.9.0.
  20286. */
  20287. template<typename InputType>
  20288. JSON_HEDLEY_WARN_UNUSED_RESULT
  20289. static basic_json from_cbor(InputType&& i,
  20290. const bool strict = true,
  20291. const bool allow_exceptions = true,
  20292. const cbor_tag_handler_t tag_handler = cbor_tag_handler_t::error)
  20293. {
  20294. basic_json result;
  20295. detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
  20296. auto ia = detail::input_adapter(std::forward<InputType>(i));
  20297. const bool res = binary_reader<decltype(ia)>(std::move(ia)).sax_parse(input_format_t::cbor, &sdp, strict, tag_handler);
  20298. return res ? result : basic_json(value_t::discarded);
  20299. }
  20300. /*!
  20301. @copydoc from_cbor(detail::input_adapter&&, const bool, const bool, const cbor_tag_handler_t)
  20302. */
  20303. template<typename IteratorType>
  20304. JSON_HEDLEY_WARN_UNUSED_RESULT
  20305. static basic_json from_cbor(IteratorType first, IteratorType last,
  20306. const bool strict = true,
  20307. const bool allow_exceptions = true,
  20308. const cbor_tag_handler_t tag_handler = cbor_tag_handler_t::error)
  20309. {
  20310. basic_json result;
  20311. detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
  20312. auto ia = detail::input_adapter(std::move(first), std::move(last));
  20313. const bool res = binary_reader<decltype(ia)>(std::move(ia)).sax_parse(input_format_t::cbor, &sdp, strict, tag_handler);
  20314. return res ? result : basic_json(value_t::discarded);
  20315. }
  20316. template<typename T>
  20317. JSON_HEDLEY_WARN_UNUSED_RESULT
  20318. JSON_HEDLEY_DEPRECATED_FOR(3.8.0, from_cbor(ptr, ptr + len))
  20319. static basic_json from_cbor(const T* ptr, std::size_t len,
  20320. const bool strict = true,
  20321. const bool allow_exceptions = true,
  20322. const cbor_tag_handler_t tag_handler = cbor_tag_handler_t::error)
  20323. {
  20324. return from_cbor(ptr, ptr + len, strict, allow_exceptions, tag_handler);
  20325. }
  20326. JSON_HEDLEY_WARN_UNUSED_RESULT
  20327. JSON_HEDLEY_DEPRECATED_FOR(3.8.0, from_cbor(ptr, ptr + len))
  20328. static basic_json from_cbor(detail::span_input_adapter&& i,
  20329. const bool strict = true,
  20330. const bool allow_exceptions = true,
  20331. const cbor_tag_handler_t tag_handler = cbor_tag_handler_t::error)
  20332. {
  20333. basic_json result;
  20334. detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
  20335. auto ia = i.get();
  20336. const bool res = binary_reader<decltype(ia)>(std::move(ia)).sax_parse(input_format_t::cbor, &sdp, strict, tag_handler);
  20337. return res ? result : basic_json(value_t::discarded);
  20338. }
  20339. /*!
  20340. @brief create a JSON value from an input in MessagePack format
  20341. Deserializes a given input @a i to a JSON value using the MessagePack
  20342. serialization format.
  20343. The library maps MessagePack types to JSON value types as follows:
  20344. MessagePack type | JSON value type | first byte
  20345. ---------------- | --------------- | ----------
  20346. positive fixint | number_unsigned | 0x00..0x7F
  20347. fixmap | object | 0x80..0x8F
  20348. fixarray | array | 0x90..0x9F
  20349. fixstr | string | 0xA0..0xBF
  20350. nil | `null` | 0xC0
  20351. false | `false` | 0xC2
  20352. true | `true` | 0xC3
  20353. float 32 | number_float | 0xCA
  20354. float 64 | number_float | 0xCB
  20355. uint 8 | number_unsigned | 0xCC
  20356. uint 16 | number_unsigned | 0xCD
  20357. uint 32 | number_unsigned | 0xCE
  20358. uint 64 | number_unsigned | 0xCF
  20359. int 8 | number_integer | 0xD0
  20360. int 16 | number_integer | 0xD1
  20361. int 32 | number_integer | 0xD2
  20362. int 64 | number_integer | 0xD3
  20363. str 8 | string | 0xD9
  20364. str 16 | string | 0xDA
  20365. str 32 | string | 0xDB
  20366. array 16 | array | 0xDC
  20367. array 32 | array | 0xDD
  20368. map 16 | object | 0xDE
  20369. map 32 | object | 0xDF
  20370. bin 8 | binary | 0xC4
  20371. bin 16 | binary | 0xC5
  20372. bin 32 | binary | 0xC6
  20373. ext 8 | binary | 0xC7
  20374. ext 16 | binary | 0xC8
  20375. ext 32 | binary | 0xC9
  20376. fixext 1 | binary | 0xD4
  20377. fixext 2 | binary | 0xD5
  20378. fixext 4 | binary | 0xD6
  20379. fixext 8 | binary | 0xD7
  20380. fixext 16 | binary | 0xD8
  20381. negative fixint | number_integer | 0xE0-0xFF
  20382. @note Any MessagePack output created @ref to_msgpack can be successfully
  20383. parsed by @ref from_msgpack.
  20384. @param[in] i an input in MessagePack format convertible to an input
  20385. adapter
  20386. @param[in] strict whether to expect the input to be consumed until EOF
  20387. (true by default)
  20388. @param[in] allow_exceptions whether to throw exceptions in case of a
  20389. parse error (optional, true by default)
  20390. @return deserialized JSON value; in case of a parse error and
  20391. @a allow_exceptions set to `false`, the return value will be
  20392. value_t::discarded.
  20393. @throw parse_error.110 if the given input ends prematurely or the end of
  20394. file was not reached when @a strict was set to true
  20395. @throw parse_error.112 if unsupported features from MessagePack were
  20396. used in the given input @a i or if the input is not valid MessagePack
  20397. @throw parse_error.113 if a string was expected as map key, but not found
  20398. @complexity Linear in the size of the input @a i.
  20399. @liveexample{The example shows the deserialization of a byte vector in
  20400. MessagePack format to a JSON value.,from_msgpack}
  20401. @sa http://msgpack.org
  20402. @sa @ref to_msgpack(const basic_json&) for the analogous serialization
  20403. @sa @ref from_cbor(detail::input_adapter&&, const bool, const bool, const cbor_tag_handler_t) for the
  20404. related CBOR format
  20405. @sa @ref from_ubjson(detail::input_adapter&&, const bool, const bool) for
  20406. the related UBJSON format
  20407. @sa @ref from_bson(detail::input_adapter&&, const bool, const bool) for
  20408. the related BSON format
  20409. @since version 2.0.9; parameter @a start_index since 2.1.1; changed to
  20410. consume input adapters, removed start_index parameter, and added
  20411. @a strict parameter since 3.0.0; added @a allow_exceptions parameter
  20412. since 3.2.0
  20413. */
  20414. template<typename InputType>
  20415. JSON_HEDLEY_WARN_UNUSED_RESULT
  20416. static basic_json from_msgpack(InputType&& i,
  20417. const bool strict = true,
  20418. const bool allow_exceptions = true)
  20419. {
  20420. basic_json result;
  20421. detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
  20422. auto ia = detail::input_adapter(std::forward<InputType>(i));
  20423. const bool res = binary_reader<decltype(ia)>(std::move(ia)).sax_parse(input_format_t::msgpack, &sdp, strict);
  20424. return res ? result : basic_json(value_t::discarded);
  20425. }
  20426. /*!
  20427. @copydoc from_msgpack(detail::input_adapter&&, const bool, const bool)
  20428. */
  20429. template<typename IteratorType>
  20430. JSON_HEDLEY_WARN_UNUSED_RESULT
  20431. static basic_json from_msgpack(IteratorType first, IteratorType last,
  20432. const bool strict = true,
  20433. const bool allow_exceptions = true)
  20434. {
  20435. basic_json result;
  20436. detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
  20437. auto ia = detail::input_adapter(std::move(first), std::move(last));
  20438. const bool res = binary_reader<decltype(ia)>(std::move(ia)).sax_parse(input_format_t::msgpack, &sdp, strict);
  20439. return res ? result : basic_json(value_t::discarded);
  20440. }
  20441. template<typename T>
  20442. JSON_HEDLEY_WARN_UNUSED_RESULT
  20443. JSON_HEDLEY_DEPRECATED_FOR(3.8.0, from_msgpack(ptr, ptr + len))
  20444. static basic_json from_msgpack(const T* ptr, std::size_t len,
  20445. const bool strict = true,
  20446. const bool allow_exceptions = true)
  20447. {
  20448. return from_msgpack(ptr, ptr + len, strict, allow_exceptions);
  20449. }
  20450. JSON_HEDLEY_WARN_UNUSED_RESULT
  20451. JSON_HEDLEY_DEPRECATED_FOR(3.8.0, from_msgpack(ptr, ptr + len))
  20452. static basic_json from_msgpack(detail::span_input_adapter&& i,
  20453. const bool strict = true,
  20454. const bool allow_exceptions = true)
  20455. {
  20456. basic_json result;
  20457. detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
  20458. auto ia = i.get();
  20459. const bool res = binary_reader<decltype(ia)>(std::move(ia)).sax_parse(input_format_t::msgpack, &sdp, strict);
  20460. return res ? result : basic_json(value_t::discarded);
  20461. }
  20462. /*!
  20463. @brief create a JSON value from an input in UBJSON format
  20464. Deserializes a given input @a i to a JSON value using the UBJSON (Universal
  20465. Binary JSON) serialization format.
  20466. The library maps UBJSON types to JSON value types as follows:
  20467. UBJSON type | JSON value type | marker
  20468. ----------- | --------------------------------------- | ------
  20469. no-op | *no value, next value is read* | `N`
  20470. null | `null` | `Z`
  20471. false | `false` | `F`
  20472. true | `true` | `T`
  20473. float32 | number_float | `d`
  20474. float64 | number_float | `D`
  20475. uint8 | number_unsigned | `U`
  20476. int8 | number_integer | `i`
  20477. int16 | number_integer | `I`
  20478. int32 | number_integer | `l`
  20479. int64 | number_integer | `L`
  20480. high-precision number | number_integer, number_unsigned, or number_float - depends on number string | 'H'
  20481. string | string | `S`
  20482. char | string | `C`
  20483. array | array (optimized values are supported) | `[`
  20484. object | object (optimized values are supported) | `{`
  20485. @note The mapping is **complete** in the sense that any UBJSON value can
  20486. be converted to a JSON value.
  20487. @param[in] i an input in UBJSON format convertible to an input adapter
  20488. @param[in] strict whether to expect the input to be consumed until EOF
  20489. (true by default)
  20490. @param[in] allow_exceptions whether to throw exceptions in case of a
  20491. parse error (optional, true by default)
  20492. @return deserialized JSON value; in case of a parse error and
  20493. @a allow_exceptions set to `false`, the return value will be
  20494. value_t::discarded.
  20495. @throw parse_error.110 if the given input ends prematurely or the end of
  20496. file was not reached when @a strict was set to true
  20497. @throw parse_error.112 if a parse error occurs
  20498. @throw parse_error.113 if a string could not be parsed successfully
  20499. @complexity Linear in the size of the input @a i.
  20500. @liveexample{The example shows the deserialization of a byte vector in
  20501. UBJSON format to a JSON value.,from_ubjson}
  20502. @sa http://ubjson.org
  20503. @sa @ref to_ubjson(const basic_json&, const bool, const bool) for the
  20504. analogous serialization
  20505. @sa @ref from_cbor(detail::input_adapter&&, const bool, const bool, const cbor_tag_handler_t) for the
  20506. related CBOR format
  20507. @sa @ref from_msgpack(detail::input_adapter&&, const bool, const bool) for
  20508. the related MessagePack format
  20509. @sa @ref from_bson(detail::input_adapter&&, const bool, const bool) for
  20510. the related BSON format
  20511. @since version 3.1.0; added @a allow_exceptions parameter since 3.2.0
  20512. */
  20513. template<typename InputType>
  20514. JSON_HEDLEY_WARN_UNUSED_RESULT
  20515. static basic_json from_ubjson(InputType&& i,
  20516. const bool strict = true,
  20517. const bool allow_exceptions = true)
  20518. {
  20519. basic_json result;
  20520. detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
  20521. auto ia = detail::input_adapter(std::forward<InputType>(i));
  20522. const bool res = binary_reader<decltype(ia)>(std::move(ia)).sax_parse(input_format_t::ubjson, &sdp, strict);
  20523. return res ? result : basic_json(value_t::discarded);
  20524. }
  20525. /*!
  20526. @copydoc from_ubjson(detail::input_adapter&&, const bool, const bool)
  20527. */
  20528. template<typename IteratorType>
  20529. JSON_HEDLEY_WARN_UNUSED_RESULT
  20530. static basic_json from_ubjson(IteratorType first, IteratorType last,
  20531. const bool strict = true,
  20532. const bool allow_exceptions = true)
  20533. {
  20534. basic_json result;
  20535. detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
  20536. auto ia = detail::input_adapter(std::move(first), std::move(last));
  20537. const bool res = binary_reader<decltype(ia)>(std::move(ia)).sax_parse(input_format_t::ubjson, &sdp, strict);
  20538. return res ? result : basic_json(value_t::discarded);
  20539. }
  20540. template<typename T>
  20541. JSON_HEDLEY_WARN_UNUSED_RESULT
  20542. JSON_HEDLEY_DEPRECATED_FOR(3.8.0, from_ubjson(ptr, ptr + len))
  20543. static basic_json from_ubjson(const T* ptr, std::size_t len,
  20544. const bool strict = true,
  20545. const bool allow_exceptions = true)
  20546. {
  20547. return from_ubjson(ptr, ptr + len, strict, allow_exceptions);
  20548. }
  20549. JSON_HEDLEY_WARN_UNUSED_RESULT
  20550. JSON_HEDLEY_DEPRECATED_FOR(3.8.0, from_ubjson(ptr, ptr + len))
  20551. static basic_json from_ubjson(detail::span_input_adapter&& i,
  20552. const bool strict = true,
  20553. const bool allow_exceptions = true)
  20554. {
  20555. basic_json result;
  20556. detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
  20557. auto ia = i.get();
  20558. const bool res = binary_reader<decltype(ia)>(std::move(ia)).sax_parse(input_format_t::ubjson, &sdp, strict);
  20559. return res ? result : basic_json(value_t::discarded);
  20560. }
  20561. /*!
  20562. @brief Create a JSON value from an input in BSON format
  20563. Deserializes a given input @a i to a JSON value using the BSON (Binary JSON)
  20564. serialization format.
  20565. The library maps BSON record types to JSON value types as follows:
  20566. BSON type | BSON marker byte | JSON value type
  20567. --------------- | ---------------- | ---------------------------
  20568. double | 0x01 | number_float
  20569. string | 0x02 | string
  20570. document | 0x03 | object
  20571. array | 0x04 | array
  20572. binary | 0x05 | still unsupported
  20573. undefined | 0x06 | still unsupported
  20574. ObjectId | 0x07 | still unsupported
  20575. boolean | 0x08 | boolean
  20576. UTC Date-Time | 0x09 | still unsupported
  20577. null | 0x0A | null
  20578. Regular Expr. | 0x0B | still unsupported
  20579. DB Pointer | 0x0C | still unsupported
  20580. JavaScript Code | 0x0D | still unsupported
  20581. Symbol | 0x0E | still unsupported
  20582. JavaScript Code | 0x0F | still unsupported
  20583. int32 | 0x10 | number_integer
  20584. Timestamp | 0x11 | still unsupported
  20585. 128-bit decimal float | 0x13 | still unsupported
  20586. Max Key | 0x7F | still unsupported
  20587. Min Key | 0xFF | still unsupported
  20588. @warning The mapping is **incomplete**. The unsupported mappings
  20589. are indicated in the table above.
  20590. @param[in] i an input in BSON format convertible to an input adapter
  20591. @param[in] strict whether to expect the input to be consumed until EOF
  20592. (true by default)
  20593. @param[in] allow_exceptions whether to throw exceptions in case of a
  20594. parse error (optional, true by default)
  20595. @return deserialized JSON value; in case of a parse error and
  20596. @a allow_exceptions set to `false`, the return value will be
  20597. value_t::discarded.
  20598. @throw parse_error.114 if an unsupported BSON record type is encountered
  20599. @complexity Linear in the size of the input @a i.
  20600. @liveexample{The example shows the deserialization of a byte vector in
  20601. BSON format to a JSON value.,from_bson}
  20602. @sa http://bsonspec.org/spec.html
  20603. @sa @ref to_bson(const basic_json&) for the analogous serialization
  20604. @sa @ref from_cbor(detail::input_adapter&&, const bool, const bool, const cbor_tag_handler_t) for the
  20605. related CBOR format
  20606. @sa @ref from_msgpack(detail::input_adapter&&, const bool, const bool) for
  20607. the related MessagePack format
  20608. @sa @ref from_ubjson(detail::input_adapter&&, const bool, const bool) for the
  20609. related UBJSON format
  20610. */
  20611. template<typename InputType>
  20612. JSON_HEDLEY_WARN_UNUSED_RESULT
  20613. static basic_json from_bson(InputType&& i,
  20614. const bool strict = true,
  20615. const bool allow_exceptions = true)
  20616. {
  20617. basic_json result;
  20618. detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
  20619. auto ia = detail::input_adapter(std::forward<InputType>(i));
  20620. const bool res = binary_reader<decltype(ia)>(std::move(ia)).sax_parse(input_format_t::bson, &sdp, strict);
  20621. return res ? result : basic_json(value_t::discarded);
  20622. }
  20623. /*!
  20624. @copydoc from_bson(detail::input_adapter&&, const bool, const bool)
  20625. */
  20626. template<typename IteratorType>
  20627. JSON_HEDLEY_WARN_UNUSED_RESULT
  20628. static basic_json from_bson(IteratorType first, IteratorType last,
  20629. const bool strict = true,
  20630. const bool allow_exceptions = true)
  20631. {
  20632. basic_json result;
  20633. detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
  20634. auto ia = detail::input_adapter(std::move(first), std::move(last));
  20635. const bool res = binary_reader<decltype(ia)>(std::move(ia)).sax_parse(input_format_t::bson, &sdp, strict);
  20636. return res ? result : basic_json(value_t::discarded);
  20637. }
  20638. template<typename T>
  20639. JSON_HEDLEY_WARN_UNUSED_RESULT
  20640. JSON_HEDLEY_DEPRECATED_FOR(3.8.0, from_bson(ptr, ptr + len))
  20641. static basic_json from_bson(const T* ptr, std::size_t len,
  20642. const bool strict = true,
  20643. const bool allow_exceptions = true)
  20644. {
  20645. return from_bson(ptr, ptr + len, strict, allow_exceptions);
  20646. }
  20647. JSON_HEDLEY_WARN_UNUSED_RESULT
  20648. JSON_HEDLEY_DEPRECATED_FOR(3.8.0, from_bson(ptr, ptr + len))
  20649. static basic_json from_bson(detail::span_input_adapter&& i,
  20650. const bool strict = true,
  20651. const bool allow_exceptions = true)
  20652. {
  20653. basic_json result;
  20654. detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
  20655. auto ia = i.get();
  20656. const bool res = binary_reader<decltype(ia)>(std::move(ia)).sax_parse(input_format_t::bson, &sdp, strict);
  20657. return res ? result : basic_json(value_t::discarded);
  20658. }
  20659. /// @}
  20660. //////////////////////////
  20661. // JSON Pointer support //
  20662. //////////////////////////
  20663. /// @name JSON Pointer functions
  20664. /// @{
  20665. /*!
  20666. @brief access specified element via JSON Pointer
  20667. Uses a JSON pointer to retrieve a reference to the respective JSON value.
  20668. No bound checking is performed. Similar to @ref operator[](const typename
  20669. object_t::key_type&), `null` values are created in arrays and objects if
  20670. necessary.
  20671. In particular:
  20672. - If the JSON pointer points to an object key that does not exist, it
  20673. is created an filled with a `null` value before a reference to it
  20674. is returned.
  20675. - If the JSON pointer points to an array index that does not exist, it
  20676. is created an filled with a `null` value before a reference to it
  20677. is returned. All indices between the current maximum and the given
  20678. index are also filled with `null`.
  20679. - The special value `-` is treated as a synonym for the index past the
  20680. end.
  20681. @param[in] ptr a JSON pointer
  20682. @return reference to the element pointed to by @a ptr
  20683. @complexity Constant.
  20684. @throw parse_error.106 if an array index begins with '0'
  20685. @throw parse_error.109 if an array index was not a number
  20686. @throw out_of_range.404 if the JSON pointer can not be resolved
  20687. @liveexample{The behavior is shown in the example.,operatorjson_pointer}
  20688. @since version 2.0.0
  20689. */
  20690. reference operator[](const json_pointer& ptr)
  20691. {
  20692. return ptr.get_unchecked(this);
  20693. }
  20694. /*!
  20695. @brief access specified element via JSON Pointer
  20696. Uses a JSON pointer to retrieve a reference to the respective JSON value.
  20697. No bound checking is performed. The function does not change the JSON
  20698. value; no `null` values are created. In particular, the special value
  20699. `-` yields an exception.
  20700. @param[in] ptr JSON pointer to the desired element
  20701. @return const reference to the element pointed to by @a ptr
  20702. @complexity Constant.
  20703. @throw parse_error.106 if an array index begins with '0'
  20704. @throw parse_error.109 if an array index was not a number
  20705. @throw out_of_range.402 if the array index '-' is used
  20706. @throw out_of_range.404 if the JSON pointer can not be resolved
  20707. @liveexample{The behavior is shown in the example.,operatorjson_pointer_const}
  20708. @since version 2.0.0
  20709. */
  20710. const_reference operator[](const json_pointer& ptr) const
  20711. {
  20712. return ptr.get_unchecked(this);
  20713. }
  20714. /*!
  20715. @brief access specified element via JSON Pointer
  20716. Returns a reference to the element at with specified JSON pointer @a ptr,
  20717. with bounds checking.
  20718. @param[in] ptr JSON pointer to the desired element
  20719. @return reference to the element pointed to by @a ptr
  20720. @throw parse_error.106 if an array index in the passed JSON pointer @a ptr
  20721. begins with '0'. See example below.
  20722. @throw parse_error.109 if an array index in the passed JSON pointer @a ptr
  20723. is not a number. See example below.
  20724. @throw out_of_range.401 if an array index in the passed JSON pointer @a ptr
  20725. is out of range. See example below.
  20726. @throw out_of_range.402 if the array index '-' is used in the passed JSON
  20727. pointer @a ptr. As `at` provides checked access (and no elements are
  20728. implicitly inserted), the index '-' is always invalid. See example below.
  20729. @throw out_of_range.403 if the JSON pointer describes a key of an object
  20730. which cannot be found. See example below.
  20731. @throw out_of_range.404 if the JSON pointer @a ptr can not be resolved.
  20732. See example below.
  20733. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  20734. changes in the JSON value.
  20735. @complexity Constant.
  20736. @since version 2.0.0
  20737. @liveexample{The behavior is shown in the example.,at_json_pointer}
  20738. */
  20739. reference at(const json_pointer& ptr)
  20740. {
  20741. return ptr.get_checked(this);
  20742. }
  20743. /*!
  20744. @brief access specified element via JSON Pointer
  20745. Returns a const reference to the element at with specified JSON pointer @a
  20746. ptr, with bounds checking.
  20747. @param[in] ptr JSON pointer to the desired element
  20748. @return reference to the element pointed to by @a ptr
  20749. @throw parse_error.106 if an array index in the passed JSON pointer @a ptr
  20750. begins with '0'. See example below.
  20751. @throw parse_error.109 if an array index in the passed JSON pointer @a ptr
  20752. is not a number. See example below.
  20753. @throw out_of_range.401 if an array index in the passed JSON pointer @a ptr
  20754. is out of range. See example below.
  20755. @throw out_of_range.402 if the array index '-' is used in the passed JSON
  20756. pointer @a ptr. As `at` provides checked access (and no elements are
  20757. implicitly inserted), the index '-' is always invalid. See example below.
  20758. @throw out_of_range.403 if the JSON pointer describes a key of an object
  20759. which cannot be found. See example below.
  20760. @throw out_of_range.404 if the JSON pointer @a ptr can not be resolved.
  20761. See example below.
  20762. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  20763. changes in the JSON value.
  20764. @complexity Constant.
  20765. @since version 2.0.0
  20766. @liveexample{The behavior is shown in the example.,at_json_pointer_const}
  20767. */
  20768. const_reference at(const json_pointer& ptr) const
  20769. {
  20770. return ptr.get_checked(this);
  20771. }
  20772. /*!
  20773. @brief return flattened JSON value
  20774. The function creates a JSON object whose keys are JSON pointers (see [RFC
  20775. 6901](https://tools.ietf.org/html/rfc6901)) and whose values are all
  20776. primitive. The original JSON value can be restored using the @ref
  20777. unflatten() function.
  20778. @return an object that maps JSON pointers to primitive values
  20779. @note Empty objects and arrays are flattened to `null` and will not be
  20780. reconstructed correctly by the @ref unflatten() function.
  20781. @complexity Linear in the size the JSON value.
  20782. @liveexample{The following code shows how a JSON object is flattened to an
  20783. object whose keys consist of JSON pointers.,flatten}
  20784. @sa @ref unflatten() for the reverse function
  20785. @since version 2.0.0
  20786. */
  20787. basic_json flatten() const
  20788. {
  20789. basic_json result(value_t::object);
  20790. json_pointer::flatten("", *this, result);
  20791. return result;
  20792. }
  20793. /*!
  20794. @brief unflatten a previously flattened JSON value
  20795. The function restores the arbitrary nesting of a JSON value that has been
  20796. flattened before using the @ref flatten() function. The JSON value must
  20797. meet certain constraints:
  20798. 1. The value must be an object.
  20799. 2. The keys must be JSON pointers (see
  20800. [RFC 6901](https://tools.ietf.org/html/rfc6901))
  20801. 3. The mapped values must be primitive JSON types.
  20802. @return the original JSON from a flattened version
  20803. @note Empty objects and arrays are flattened by @ref flatten() to `null`
  20804. values and can not unflattened to their original type. Apart from
  20805. this example, for a JSON value `j`, the following is always true:
  20806. `j == j.flatten().unflatten()`.
  20807. @complexity Linear in the size the JSON value.
  20808. @throw type_error.314 if value is not an object
  20809. @throw type_error.315 if object values are not primitive
  20810. @liveexample{The following code shows how a flattened JSON object is
  20811. unflattened into the original nested JSON object.,unflatten}
  20812. @sa @ref flatten() for the reverse function
  20813. @since version 2.0.0
  20814. */
  20815. basic_json unflatten() const
  20816. {
  20817. return json_pointer::unflatten(*this);
  20818. }
  20819. /// @}
  20820. //////////////////////////
  20821. // JSON Patch functions //
  20822. //////////////////////////
  20823. /// @name JSON Patch functions
  20824. /// @{
  20825. /*!
  20826. @brief applies a JSON patch
  20827. [JSON Patch](http://jsonpatch.com) defines a JSON document structure for
  20828. expressing a sequence of operations to apply to a JSON) document. With
  20829. this function, a JSON Patch is applied to the current JSON value by
  20830. executing all operations from the patch.
  20831. @param[in] json_patch JSON patch document
  20832. @return patched document
  20833. @note The application of a patch is atomic: Either all operations succeed
  20834. and the patched document is returned or an exception is thrown. In
  20835. any case, the original value is not changed: the patch is applied
  20836. to a copy of the value.
  20837. @throw parse_error.104 if the JSON patch does not consist of an array of
  20838. objects
  20839. @throw parse_error.105 if the JSON patch is malformed (e.g., mandatory
  20840. attributes are missing); example: `"operation add must have member path"`
  20841. @throw out_of_range.401 if an array index is out of range.
  20842. @throw out_of_range.403 if a JSON pointer inside the patch could not be
  20843. resolved successfully in the current JSON value; example: `"key baz not
  20844. found"`
  20845. @throw out_of_range.405 if JSON pointer has no parent ("add", "remove",
  20846. "move")
  20847. @throw other_error.501 if "test" operation was unsuccessful
  20848. @complexity Linear in the size of the JSON value and the length of the
  20849. JSON patch. As usually only a fraction of the JSON value is affected by
  20850. the patch, the complexity can usually be neglected.
  20851. @liveexample{The following code shows how a JSON patch is applied to a
  20852. value.,patch}
  20853. @sa @ref diff -- create a JSON patch by comparing two JSON values
  20854. @sa [RFC 6902 (JSON Patch)](https://tools.ietf.org/html/rfc6902)
  20855. @sa [RFC 6901 (JSON Pointer)](https://tools.ietf.org/html/rfc6901)
  20856. @since version 2.0.0
  20857. */
  20858. basic_json patch(const basic_json& json_patch) const
  20859. {
  20860. // make a working copy to apply the patch to
  20861. basic_json result = *this;
  20862. // the valid JSON Patch operations
  20863. enum class patch_operations {add, remove, replace, move, copy, test, invalid};
  20864. const auto get_op = [](const std::string & op)
  20865. {
  20866. if (op == "add")
  20867. {
  20868. return patch_operations::add;
  20869. }
  20870. if (op == "remove")
  20871. {
  20872. return patch_operations::remove;
  20873. }
  20874. if (op == "replace")
  20875. {
  20876. return patch_operations::replace;
  20877. }
  20878. if (op == "move")
  20879. {
  20880. return patch_operations::move;
  20881. }
  20882. if (op == "copy")
  20883. {
  20884. return patch_operations::copy;
  20885. }
  20886. if (op == "test")
  20887. {
  20888. return patch_operations::test;
  20889. }
  20890. return patch_operations::invalid;
  20891. };
  20892. // wrapper for "add" operation; add value at ptr
  20893. const auto operation_add = [&result](json_pointer & ptr, basic_json val)
  20894. {
  20895. // adding to the root of the target document means replacing it
  20896. if (ptr.empty())
  20897. {
  20898. result = val;
  20899. return;
  20900. }
  20901. // make sure the top element of the pointer exists
  20902. json_pointer top_pointer = ptr.top();
  20903. if (top_pointer != ptr)
  20904. {
  20905. result.at(top_pointer);
  20906. }
  20907. // get reference to parent of JSON pointer ptr
  20908. const auto last_path = ptr.back();
  20909. ptr.pop_back();
  20910. basic_json& parent = result[ptr];
  20911. switch (parent.m_type)
  20912. {
  20913. case value_t::null:
  20914. case value_t::object:
  20915. {
  20916. // use operator[] to add value
  20917. parent[last_path] = val;
  20918. break;
  20919. }
  20920. case value_t::array:
  20921. {
  20922. if (last_path == "-")
  20923. {
  20924. // special case: append to back
  20925. parent.push_back(val);
  20926. }
  20927. else
  20928. {
  20929. const auto idx = json_pointer::array_index(last_path);
  20930. if (JSON_HEDLEY_UNLIKELY(idx > parent.size()))
  20931. {
  20932. // avoid undefined behavior
  20933. JSON_THROW(out_of_range::create(401, "array index " + std::to_string(idx) + " is out of range"));
  20934. }
  20935. // default case: insert add offset
  20936. parent.insert(parent.begin() + static_cast<difference_type>(idx), val);
  20937. }
  20938. break;
  20939. }
  20940. // if there exists a parent it cannot be primitive
  20941. default: // LCOV_EXCL_LINE
  20942. JSON_ASSERT(false); // LCOV_EXCL_LINE
  20943. }
  20944. };
  20945. // wrapper for "remove" operation; remove value at ptr
  20946. const auto operation_remove = [&result](json_pointer & ptr)
  20947. {
  20948. // get reference to parent of JSON pointer ptr
  20949. const auto last_path = ptr.back();
  20950. ptr.pop_back();
  20951. basic_json& parent = result.at(ptr);
  20952. // remove child
  20953. if (parent.is_object())
  20954. {
  20955. // perform range check
  20956. auto it = parent.find(last_path);
  20957. if (JSON_HEDLEY_LIKELY(it != parent.end()))
  20958. {
  20959. parent.erase(it);
  20960. }
  20961. else
  20962. {
  20963. JSON_THROW(out_of_range::create(403, "key '" + last_path + "' not found"));
  20964. }
  20965. }
  20966. else if (parent.is_array())
  20967. {
  20968. // note erase performs range check
  20969. parent.erase(json_pointer::array_index(last_path));
  20970. }
  20971. };
  20972. // type check: top level value must be an array
  20973. if (JSON_HEDLEY_UNLIKELY(!json_patch.is_array()))
  20974. {
  20975. JSON_THROW(parse_error::create(104, 0, "JSON patch must be an array of objects"));
  20976. }
  20977. // iterate and apply the operations
  20978. for (const auto& val : json_patch)
  20979. {
  20980. // wrapper to get a value for an operation
  20981. const auto get_value = [&val](const std::string & op,
  20982. const std::string & member,
  20983. bool string_type) -> basic_json &
  20984. {
  20985. // find value
  20986. auto it = val.m_value.object->find(member);
  20987. // context-sensitive error message
  20988. const auto error_msg = (op == "op") ? "operation" : "operation '" + op + "'";
  20989. // check if desired value is present
  20990. if (JSON_HEDLEY_UNLIKELY(it == val.m_value.object->end()))
  20991. {
  20992. JSON_THROW(parse_error::create(105, 0, error_msg + " must have member '" + member + "'"));
  20993. }
  20994. // check if result is of type string
  20995. if (JSON_HEDLEY_UNLIKELY(string_type && !it->second.is_string()))
  20996. {
  20997. JSON_THROW(parse_error::create(105, 0, error_msg + " must have string member '" + member + "'"));
  20998. }
  20999. // no error: return value
  21000. return it->second;
  21001. };
  21002. // type check: every element of the array must be an object
  21003. if (JSON_HEDLEY_UNLIKELY(!val.is_object()))
  21004. {
  21005. JSON_THROW(parse_error::create(104, 0, "JSON patch must be an array of objects"));
  21006. }
  21007. // collect mandatory members
  21008. const auto op = get_value("op", "op", true).template get<std::string>();
  21009. const auto path = get_value(op, "path", true).template get<std::string>();
  21010. json_pointer ptr(path);
  21011. switch (get_op(op))
  21012. {
  21013. case patch_operations::add:
  21014. {
  21015. operation_add(ptr, get_value("add", "value", false));
  21016. break;
  21017. }
  21018. case patch_operations::remove:
  21019. {
  21020. operation_remove(ptr);
  21021. break;
  21022. }
  21023. case patch_operations::replace:
  21024. {
  21025. // the "path" location must exist - use at()
  21026. result.at(ptr) = get_value("replace", "value", false);
  21027. break;
  21028. }
  21029. case patch_operations::move:
  21030. {
  21031. const auto from_path = get_value("move", "from", true).template get<std::string>();
  21032. json_pointer from_ptr(from_path);
  21033. // the "from" location must exist - use at()
  21034. basic_json v = result.at(from_ptr);
  21035. // The move operation is functionally identical to a
  21036. // "remove" operation on the "from" location, followed
  21037. // immediately by an "add" operation at the target
  21038. // location with the value that was just removed.
  21039. operation_remove(from_ptr);
  21040. operation_add(ptr, v);
  21041. break;
  21042. }
  21043. case patch_operations::copy:
  21044. {
  21045. const auto from_path = get_value("copy", "from", true).template get<std::string>();
  21046. const json_pointer from_ptr(from_path);
  21047. // the "from" location must exist - use at()
  21048. basic_json v = result.at(from_ptr);
  21049. // The copy is functionally identical to an "add"
  21050. // operation at the target location using the value
  21051. // specified in the "from" member.
  21052. operation_add(ptr, v);
  21053. break;
  21054. }
  21055. case patch_operations::test:
  21056. {
  21057. bool success = false;
  21058. JSON_TRY
  21059. {
  21060. // check if "value" matches the one at "path"
  21061. // the "path" location must exist - use at()
  21062. success = (result.at(ptr) == get_value("test", "value", false));
  21063. }
  21064. JSON_INTERNAL_CATCH (out_of_range&)
  21065. {
  21066. // ignore out of range errors: success remains false
  21067. }
  21068. // throw an exception if test fails
  21069. if (JSON_HEDLEY_UNLIKELY(!success))
  21070. {
  21071. JSON_THROW(other_error::create(501, "unsuccessful: " + val.dump()));
  21072. }
  21073. break;
  21074. }
  21075. default:
  21076. {
  21077. // op must be "add", "remove", "replace", "move", "copy", or
  21078. // "test"
  21079. JSON_THROW(parse_error::create(105, 0, "operation value '" + op + "' is invalid"));
  21080. }
  21081. }
  21082. }
  21083. return result;
  21084. }
  21085. /*!
  21086. @brief creates a diff as a JSON patch
  21087. Creates a [JSON Patch](http://jsonpatch.com) so that value @a source can
  21088. be changed into the value @a target by calling @ref patch function.
  21089. @invariant For two JSON values @a source and @a target, the following code
  21090. yields always `true`:
  21091. @code {.cpp}
  21092. source.patch(diff(source, target)) == target;
  21093. @endcode
  21094. @note Currently, only `remove`, `add`, and `replace` operations are
  21095. generated.
  21096. @param[in] source JSON value to compare from
  21097. @param[in] target JSON value to compare against
  21098. @param[in] path helper value to create JSON pointers
  21099. @return a JSON patch to convert the @a source to @a target
  21100. @complexity Linear in the lengths of @a source and @a target.
  21101. @liveexample{The following code shows how a JSON patch is created as a
  21102. diff for two JSON values.,diff}
  21103. @sa @ref patch -- apply a JSON patch
  21104. @sa @ref merge_patch -- apply a JSON Merge Patch
  21105. @sa [RFC 6902 (JSON Patch)](https://tools.ietf.org/html/rfc6902)
  21106. @since version 2.0.0
  21107. */
  21108. JSON_HEDLEY_WARN_UNUSED_RESULT
  21109. static basic_json diff(const basic_json& source, const basic_json& target,
  21110. const std::string& path = "")
  21111. {
  21112. // the patch
  21113. basic_json result(value_t::array);
  21114. // if the values are the same, return empty patch
  21115. if (source == target)
  21116. {
  21117. return result;
  21118. }
  21119. if (source.type() != target.type())
  21120. {
  21121. // different types: replace value
  21122. result.push_back(
  21123. {
  21124. {"op", "replace"}, {"path", path}, {"value", target}
  21125. });
  21126. return result;
  21127. }
  21128. switch (source.type())
  21129. {
  21130. case value_t::array:
  21131. {
  21132. // first pass: traverse common elements
  21133. std::size_t i = 0;
  21134. while (i < source.size() && i < target.size())
  21135. {
  21136. // recursive call to compare array values at index i
  21137. auto temp_diff = diff(source[i], target[i], path + "/" + std::to_string(i));
  21138. result.insert(result.end(), temp_diff.begin(), temp_diff.end());
  21139. ++i;
  21140. }
  21141. // i now reached the end of at least one array
  21142. // in a second pass, traverse the remaining elements
  21143. // remove my remaining elements
  21144. const auto end_index = static_cast<difference_type>(result.size());
  21145. while (i < source.size())
  21146. {
  21147. // add operations in reverse order to avoid invalid
  21148. // indices
  21149. result.insert(result.begin() + end_index, object(
  21150. {
  21151. {"op", "remove"},
  21152. {"path", path + "/" + std::to_string(i)}
  21153. }));
  21154. ++i;
  21155. }
  21156. // add other remaining elements
  21157. while (i < target.size())
  21158. {
  21159. result.push_back(
  21160. {
  21161. {"op", "add"},
  21162. {"path", path + "/-"},
  21163. {"value", target[i]}
  21164. });
  21165. ++i;
  21166. }
  21167. break;
  21168. }
  21169. case value_t::object:
  21170. {
  21171. // first pass: traverse this object's elements
  21172. for (auto it = source.cbegin(); it != source.cend(); ++it)
  21173. {
  21174. // escape the key name to be used in a JSON patch
  21175. const auto key = json_pointer::escape(it.key());
  21176. if (target.find(it.key()) != target.end())
  21177. {
  21178. // recursive call to compare object values at key it
  21179. auto temp_diff = diff(it.value(), target[it.key()], path + "/" + key);
  21180. result.insert(result.end(), temp_diff.begin(), temp_diff.end());
  21181. }
  21182. else
  21183. {
  21184. // found a key that is not in o -> remove it
  21185. result.push_back(object(
  21186. {
  21187. {"op", "remove"}, {"path", path + "/" + key}
  21188. }));
  21189. }
  21190. }
  21191. // second pass: traverse other object's elements
  21192. for (auto it = target.cbegin(); it != target.cend(); ++it)
  21193. {
  21194. if (source.find(it.key()) == source.end())
  21195. {
  21196. // found a key that is not in this -> add it
  21197. const auto key = json_pointer::escape(it.key());
  21198. result.push_back(
  21199. {
  21200. {"op", "add"}, {"path", path + "/" + key},
  21201. {"value", it.value()}
  21202. });
  21203. }
  21204. }
  21205. break;
  21206. }
  21207. default:
  21208. {
  21209. // both primitive type: replace value
  21210. result.push_back(
  21211. {
  21212. {"op", "replace"}, {"path", path}, {"value", target}
  21213. });
  21214. break;
  21215. }
  21216. }
  21217. return result;
  21218. }
  21219. /// @}
  21220. ////////////////////////////////
  21221. // JSON Merge Patch functions //
  21222. ////////////////////////////////
  21223. /// @name JSON Merge Patch functions
  21224. /// @{
  21225. /*!
  21226. @brief applies a JSON Merge Patch
  21227. The merge patch format is primarily intended for use with the HTTP PATCH
  21228. method as a means of describing a set of modifications to a target
  21229. resource's content. This function applies a merge patch to the current
  21230. JSON value.
  21231. The function implements the following algorithm from Section 2 of
  21232. [RFC 7396 (JSON Merge Patch)](https://tools.ietf.org/html/rfc7396):
  21233. ```
  21234. define MergePatch(Target, Patch):
  21235. if Patch is an Object:
  21236. if Target is not an Object:
  21237. Target = {} // Ignore the contents and set it to an empty Object
  21238. for each Name/Value pair in Patch:
  21239. if Value is null:
  21240. if Name exists in Target:
  21241. remove the Name/Value pair from Target
  21242. else:
  21243. Target[Name] = MergePatch(Target[Name], Value)
  21244. return Target
  21245. else:
  21246. return Patch
  21247. ```
  21248. Thereby, `Target` is the current object; that is, the patch is applied to
  21249. the current value.
  21250. @param[in] apply_patch the patch to apply
  21251. @complexity Linear in the lengths of @a patch.
  21252. @liveexample{The following code shows how a JSON Merge Patch is applied to
  21253. a JSON document.,merge_patch}
  21254. @sa @ref patch -- apply a JSON patch
  21255. @sa [RFC 7396 (JSON Merge Patch)](https://tools.ietf.org/html/rfc7396)
  21256. @since version 3.0.0
  21257. */
  21258. void merge_patch(const basic_json& apply_patch)
  21259. {
  21260. if (apply_patch.is_object())
  21261. {
  21262. if (!is_object())
  21263. {
  21264. *this = object();
  21265. }
  21266. for (auto it = apply_patch.begin(); it != apply_patch.end(); ++it)
  21267. {
  21268. if (it.value().is_null())
  21269. {
  21270. erase(it.key());
  21271. }
  21272. else
  21273. {
  21274. operator[](it.key()).merge_patch(it.value());
  21275. }
  21276. }
  21277. }
  21278. else
  21279. {
  21280. *this = apply_patch;
  21281. }
  21282. }
  21283. /// @}
  21284. };
  21285. /*!
  21286. @brief user-defined to_string function for JSON values
  21287. This function implements a user-defined to_string for JSON objects.
  21288. @param[in] j a JSON object
  21289. @return a std::string object
  21290. */
  21291. NLOHMANN_BASIC_JSON_TPL_DECLARATION
  21292. std::string to_string(const NLOHMANN_BASIC_JSON_TPL& j)
  21293. {
  21294. return j.dump();
  21295. }
  21296. } // namespace nlohmann
  21297. ///////////////////////
  21298. // nonmember support //
  21299. ///////////////////////
  21300. // specialization of std::swap, and std::hash
  21301. namespace std
  21302. {
  21303. /// hash value for JSON objects
  21304. template<>
  21305. struct hash<nlohmann::json>
  21306. {
  21307. /*!
  21308. @brief return a hash value for a JSON object
  21309. @since version 1.0.0
  21310. */
  21311. std::size_t operator()(const nlohmann::json& j) const
  21312. {
  21313. return nlohmann::detail::hash(j);
  21314. }
  21315. };
  21316. /// specialization for std::less<value_t>
  21317. /// @note: do not remove the space after '<',
  21318. /// see https://github.com/nlohmann/json/pull/679
  21319. template<>
  21320. struct less<::nlohmann::detail::value_t>
  21321. {
  21322. /*!
  21323. @brief compare two value_t enum values
  21324. @since version 3.0.0
  21325. */
  21326. bool operator()(nlohmann::detail::value_t lhs,
  21327. nlohmann::detail::value_t rhs) const noexcept
  21328. {
  21329. return nlohmann::detail::operator<(lhs, rhs);
  21330. }
  21331. };
  21332. // C++20 prohibit function specialization in the std namespace.
  21333. #ifndef JSON_HAS_CPP_20
  21334. /*!
  21335. @brief exchanges the values of two JSON objects
  21336. @since version 1.0.0
  21337. */
  21338. template<>
  21339. inline void swap<nlohmann::json>(nlohmann::json& j1, nlohmann::json& j2) noexcept(
  21340. is_nothrow_move_constructible<nlohmann::json>::value&&
  21341. is_nothrow_move_assignable<nlohmann::json>::value
  21342. )
  21343. {
  21344. j1.swap(j2);
  21345. }
  21346. #endif
  21347. } // namespace std
  21348. /*!
  21349. @brief user-defined string literal for JSON values
  21350. This operator implements a user-defined string literal for JSON objects. It
  21351. can be used by adding `"_json"` to a string literal and returns a JSON object
  21352. if no parse error occurred.
  21353. @param[in] s a string representation of a JSON object
  21354. @param[in] n the length of string @a s
  21355. @return a JSON object
  21356. @since version 1.0.0
  21357. */
  21358. JSON_HEDLEY_NON_NULL(1)
  21359. inline nlohmann::json operator "" _json(const char* s, std::size_t n)
  21360. {
  21361. return nlohmann::json::parse(s, s + n);
  21362. }
  21363. /*!
  21364. @brief user-defined string literal for JSON pointer
  21365. This operator implements a user-defined string literal for JSON Pointers. It
  21366. can be used by adding `"_json_pointer"` to a string literal and returns a JSON pointer
  21367. object if no parse error occurred.
  21368. @param[in] s a string representation of a JSON Pointer
  21369. @param[in] n the length of string @a s
  21370. @return a JSON pointer object
  21371. @since version 2.0.0
  21372. */
  21373. JSON_HEDLEY_NON_NULL(1)
  21374. inline nlohmann::json::json_pointer operator "" _json_pointer(const char* s, std::size_t n)
  21375. {
  21376. return nlohmann::json::json_pointer(std::string(s, n));
  21377. }
  21378. // #include <nlohmann/detail/macro_unscope.hpp>
  21379. // restore GCC/clang diagnostic settings
  21380. #if defined(__clang__) || defined(__GNUC__) || defined(__GNUG__)
  21381. #pragma GCC diagnostic pop
  21382. #endif
  21383. #if defined(__clang__)
  21384. #pragma GCC diagnostic pop
  21385. #endif
  21386. // clean up
  21387. #undef JSON_ASSERT
  21388. #undef JSON_INTERNAL_CATCH
  21389. #undef JSON_CATCH
  21390. #undef JSON_THROW
  21391. #undef JSON_TRY
  21392. #undef JSON_HAS_CPP_14
  21393. #undef JSON_HAS_CPP_17
  21394. #undef NLOHMANN_BASIC_JSON_TPL_DECLARATION
  21395. #undef NLOHMANN_BASIC_JSON_TPL
  21396. #undef JSON_EXPLICIT
  21397. // #include <nlohmann/thirdparty/hedley/hedley_undef.hpp>
  21398. #undef JSON_HEDLEY_ALWAYS_INLINE
  21399. #undef JSON_HEDLEY_ARM_VERSION
  21400. #undef JSON_HEDLEY_ARM_VERSION_CHECK
  21401. #undef JSON_HEDLEY_ARRAY_PARAM
  21402. #undef JSON_HEDLEY_ASSUME
  21403. #undef JSON_HEDLEY_BEGIN_C_DECLS
  21404. #undef JSON_HEDLEY_CLANG_HAS_ATTRIBUTE
  21405. #undef JSON_HEDLEY_CLANG_HAS_BUILTIN
  21406. #undef JSON_HEDLEY_CLANG_HAS_CPP_ATTRIBUTE
  21407. #undef JSON_HEDLEY_CLANG_HAS_DECLSPEC_DECLSPEC_ATTRIBUTE
  21408. #undef JSON_HEDLEY_CLANG_HAS_EXTENSION
  21409. #undef JSON_HEDLEY_CLANG_HAS_FEATURE
  21410. #undef JSON_HEDLEY_CLANG_HAS_WARNING
  21411. #undef JSON_HEDLEY_COMPCERT_VERSION
  21412. #undef JSON_HEDLEY_COMPCERT_VERSION_CHECK
  21413. #undef JSON_HEDLEY_CONCAT
  21414. #undef JSON_HEDLEY_CONCAT3
  21415. #undef JSON_HEDLEY_CONCAT3_EX
  21416. #undef JSON_HEDLEY_CONCAT_EX
  21417. #undef JSON_HEDLEY_CONST
  21418. #undef JSON_HEDLEY_CONSTEXPR
  21419. #undef JSON_HEDLEY_CONST_CAST
  21420. #undef JSON_HEDLEY_CPP_CAST
  21421. #undef JSON_HEDLEY_CRAY_VERSION
  21422. #undef JSON_HEDLEY_CRAY_VERSION_CHECK
  21423. #undef JSON_HEDLEY_C_DECL
  21424. #undef JSON_HEDLEY_DEPRECATED
  21425. #undef JSON_HEDLEY_DEPRECATED_FOR
  21426. #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL
  21427. #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_
  21428. #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED
  21429. #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES
  21430. #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS
  21431. #undef JSON_HEDLEY_DIAGNOSTIC_POP
  21432. #undef JSON_HEDLEY_DIAGNOSTIC_PUSH
  21433. #undef JSON_HEDLEY_DMC_VERSION
  21434. #undef JSON_HEDLEY_DMC_VERSION_CHECK
  21435. #undef JSON_HEDLEY_EMPTY_BASES
  21436. #undef JSON_HEDLEY_EMSCRIPTEN_VERSION
  21437. #undef JSON_HEDLEY_EMSCRIPTEN_VERSION_CHECK
  21438. #undef JSON_HEDLEY_END_C_DECLS
  21439. #undef JSON_HEDLEY_FLAGS
  21440. #undef JSON_HEDLEY_FLAGS_CAST
  21441. #undef JSON_HEDLEY_GCC_HAS_ATTRIBUTE
  21442. #undef JSON_HEDLEY_GCC_HAS_BUILTIN
  21443. #undef JSON_HEDLEY_GCC_HAS_CPP_ATTRIBUTE
  21444. #undef JSON_HEDLEY_GCC_HAS_DECLSPEC_ATTRIBUTE
  21445. #undef JSON_HEDLEY_GCC_HAS_EXTENSION
  21446. #undef JSON_HEDLEY_GCC_HAS_FEATURE
  21447. #undef JSON_HEDLEY_GCC_HAS_WARNING
  21448. #undef JSON_HEDLEY_GCC_NOT_CLANG_VERSION_CHECK
  21449. #undef JSON_HEDLEY_GCC_VERSION
  21450. #undef JSON_HEDLEY_GCC_VERSION_CHECK
  21451. #undef JSON_HEDLEY_GNUC_HAS_ATTRIBUTE
  21452. #undef JSON_HEDLEY_GNUC_HAS_BUILTIN
  21453. #undef JSON_HEDLEY_GNUC_HAS_CPP_ATTRIBUTE
  21454. #undef JSON_HEDLEY_GNUC_HAS_DECLSPEC_ATTRIBUTE
  21455. #undef JSON_HEDLEY_GNUC_HAS_EXTENSION
  21456. #undef JSON_HEDLEY_GNUC_HAS_FEATURE
  21457. #undef JSON_HEDLEY_GNUC_HAS_WARNING
  21458. #undef JSON_HEDLEY_GNUC_VERSION
  21459. #undef JSON_HEDLEY_GNUC_VERSION_CHECK
  21460. #undef JSON_HEDLEY_HAS_ATTRIBUTE
  21461. #undef JSON_HEDLEY_HAS_BUILTIN
  21462. #undef JSON_HEDLEY_HAS_CPP_ATTRIBUTE
  21463. #undef JSON_HEDLEY_HAS_CPP_ATTRIBUTE_NS
  21464. #undef JSON_HEDLEY_HAS_DECLSPEC_ATTRIBUTE
  21465. #undef JSON_HEDLEY_HAS_EXTENSION
  21466. #undef JSON_HEDLEY_HAS_FEATURE
  21467. #undef JSON_HEDLEY_HAS_WARNING
  21468. #undef JSON_HEDLEY_IAR_VERSION
  21469. #undef JSON_HEDLEY_IAR_VERSION_CHECK
  21470. #undef JSON_HEDLEY_IBM_VERSION
  21471. #undef JSON_HEDLEY_IBM_VERSION_CHECK
  21472. #undef JSON_HEDLEY_IMPORT
  21473. #undef JSON_HEDLEY_INLINE
  21474. #undef JSON_HEDLEY_INTEL_VERSION
  21475. #undef JSON_HEDLEY_INTEL_VERSION_CHECK
  21476. #undef JSON_HEDLEY_IS_CONSTANT
  21477. #undef JSON_HEDLEY_IS_CONSTEXPR_
  21478. #undef JSON_HEDLEY_LIKELY
  21479. #undef JSON_HEDLEY_MALLOC
  21480. #undef JSON_HEDLEY_MESSAGE
  21481. #undef JSON_HEDLEY_MSVC_VERSION
  21482. #undef JSON_HEDLEY_MSVC_VERSION_CHECK
  21483. #undef JSON_HEDLEY_NEVER_INLINE
  21484. #undef JSON_HEDLEY_NON_NULL
  21485. #undef JSON_HEDLEY_NO_ESCAPE
  21486. #undef JSON_HEDLEY_NO_RETURN
  21487. #undef JSON_HEDLEY_NO_THROW
  21488. #undef JSON_HEDLEY_NULL
  21489. #undef JSON_HEDLEY_PELLES_VERSION
  21490. #undef JSON_HEDLEY_PELLES_VERSION_CHECK
  21491. #undef JSON_HEDLEY_PGI_VERSION
  21492. #undef JSON_HEDLEY_PGI_VERSION_CHECK
  21493. #undef JSON_HEDLEY_PREDICT
  21494. #undef JSON_HEDLEY_PRINTF_FORMAT
  21495. #undef JSON_HEDLEY_PRIVATE
  21496. #undef JSON_HEDLEY_PUBLIC
  21497. #undef JSON_HEDLEY_PURE
  21498. #undef JSON_HEDLEY_REINTERPRET_CAST
  21499. #undef JSON_HEDLEY_REQUIRE
  21500. #undef JSON_HEDLEY_REQUIRE_CONSTEXPR
  21501. #undef JSON_HEDLEY_REQUIRE_MSG
  21502. #undef JSON_HEDLEY_RESTRICT
  21503. #undef JSON_HEDLEY_RETURNS_NON_NULL
  21504. #undef JSON_HEDLEY_SENTINEL
  21505. #undef JSON_HEDLEY_STATIC_ASSERT
  21506. #undef JSON_HEDLEY_STATIC_CAST
  21507. #undef JSON_HEDLEY_STRINGIFY
  21508. #undef JSON_HEDLEY_STRINGIFY_EX
  21509. #undef JSON_HEDLEY_SUNPRO_VERSION
  21510. #undef JSON_HEDLEY_SUNPRO_VERSION_CHECK
  21511. #undef JSON_HEDLEY_TINYC_VERSION
  21512. #undef JSON_HEDLEY_TINYC_VERSION_CHECK
  21513. #undef JSON_HEDLEY_TI_ARMCL_VERSION
  21514. #undef JSON_HEDLEY_TI_ARMCL_VERSION_CHECK
  21515. #undef JSON_HEDLEY_TI_CL2000_VERSION
  21516. #undef JSON_HEDLEY_TI_CL2000_VERSION_CHECK
  21517. #undef JSON_HEDLEY_TI_CL430_VERSION
  21518. #undef JSON_HEDLEY_TI_CL430_VERSION_CHECK
  21519. #undef JSON_HEDLEY_TI_CL6X_VERSION
  21520. #undef JSON_HEDLEY_TI_CL6X_VERSION_CHECK
  21521. #undef JSON_HEDLEY_TI_CL7X_VERSION
  21522. #undef JSON_HEDLEY_TI_CL7X_VERSION_CHECK
  21523. #undef JSON_HEDLEY_TI_CLPRU_VERSION
  21524. #undef JSON_HEDLEY_TI_CLPRU_VERSION_CHECK
  21525. #undef JSON_HEDLEY_TI_VERSION
  21526. #undef JSON_HEDLEY_TI_VERSION_CHECK
  21527. #undef JSON_HEDLEY_UNAVAILABLE
  21528. #undef JSON_HEDLEY_UNLIKELY
  21529. #undef JSON_HEDLEY_UNPREDICTABLE
  21530. #undef JSON_HEDLEY_UNREACHABLE
  21531. #undef JSON_HEDLEY_UNREACHABLE_RETURN
  21532. #undef JSON_HEDLEY_VERSION
  21533. #undef JSON_HEDLEY_VERSION_DECODE_MAJOR
  21534. #undef JSON_HEDLEY_VERSION_DECODE_MINOR
  21535. #undef JSON_HEDLEY_VERSION_DECODE_REVISION
  21536. #undef JSON_HEDLEY_VERSION_ENCODE
  21537. #undef JSON_HEDLEY_WARNING
  21538. #undef JSON_HEDLEY_WARN_UNUSED_RESULT
  21539. #undef JSON_HEDLEY_WARN_UNUSED_RESULT_MSG
  21540. #undef JSON_HEDLEY_FALL_THROUGH
  21541. #endif // INCLUDE_NLOHMANN_JSON_HPP_