json.hpp 905 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447
  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_