選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

json.hpp 782KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684
  1. /*
  2. __ _____ _____ _____
  3. __| | __| | | | JSON for Modern C++
  4. | | |__ | | | | | | version 3.7.0
  5. |_____|_____|_____|_|___| https://github.com/nlohmann/json
  6. Licensed under the MIT License <http://opensource.org/licenses/MIT>.
  7. SPDX-License-Identifier: MIT
  8. Copyright (c) 2013-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 7
  29. #define NLOHMANN_JSON_VERSION_PATCH 0
  30. #include <algorithm> // all_of, find, for_each
  31. #include <cassert> // assert
  32. #include <ciso646> // and, not, or
  33. #include <cstddef> // nullptr_t, ptrdiff_t, size_t
  34. #include <functional> // hash, less
  35. #include <initializer_list> // initializer_list
  36. #include <iosfwd> // istream, ostream
  37. #include <iterator> // random_access_iterator_tag
  38. #include <memory> // unique_ptr
  39. #include <numeric> // accumulate
  40. #include <string> // string, stoi, to_string
  41. #include <utility> // declval, forward, move, pair, swap
  42. #include <vector> // vector
  43. // #include <nlohmann/adl_serializer.hpp>
  44. #include <utility>
  45. // #include <nlohmann/detail/conversions/from_json.hpp>
  46. #include <algorithm> // transform
  47. #include <array> // array
  48. #include <ciso646> // and, not
  49. #include <forward_list> // forward_list
  50. #include <iterator> // inserter, front_inserter, end
  51. #include <map> // map
  52. #include <string> // string
  53. #include <tuple> // tuple, make_tuple
  54. #include <type_traits> // is_arithmetic, is_same, is_enum, underlying_type, is_convertible
  55. #include <unordered_map> // unordered_map
  56. #include <utility> // pair, declval
  57. #include <valarray> // valarray
  58. // #include <nlohmann/detail/exceptions.hpp>
  59. #include <exception> // exception
  60. #include <stdexcept> // runtime_error
  61. #include <string> // to_string
  62. // #include <nlohmann/detail/input/position_t.hpp>
  63. #include <cstddef> // size_t
  64. namespace nlohmann
  65. {
  66. namespace detail
  67. {
  68. /// struct to capture the start position of the current token
  69. struct position_t
  70. {
  71. /// the total number of characters read
  72. std::size_t chars_read_total = 0;
  73. /// the number of characters read in the current line
  74. std::size_t chars_read_current_line = 0;
  75. /// the number of lines read
  76. std::size_t lines_read = 0;
  77. /// conversion to size_t to preserve SAX interface
  78. constexpr operator size_t() const
  79. {
  80. return chars_read_total;
  81. }
  82. };
  83. } // namespace detail
  84. } // namespace nlohmann
  85. // #include <nlohmann/detail/macro_scope.hpp>
  86. #include <utility> // pair
  87. // #include <nlohmann/thirdparty/hedley/hedley.hpp>
  88. /* Hedley - https://nemequ.github.io/hedley
  89. * Created by Evan Nemerson <evan@nemerson.com>
  90. *
  91. * To the extent possible under law, the author(s) have dedicated all
  92. * copyright and related and neighboring rights to this software to
  93. * the public domain worldwide. This software is distributed without
  94. * any warranty.
  95. *
  96. * For details, see <http://creativecommons.org/publicdomain/zero/1.0/>.
  97. * SPDX-License-Identifier: CC0-1.0
  98. */
  99. #if !defined(JSON_HEDLEY_VERSION) || (JSON_HEDLEY_VERSION < 9)
  100. #if defined(JSON_HEDLEY_VERSION)
  101. #undef JSON_HEDLEY_VERSION
  102. #endif
  103. #define JSON_HEDLEY_VERSION 9
  104. #if defined(JSON_HEDLEY_STRINGIFY_EX)
  105. #undef JSON_HEDLEY_STRINGIFY_EX
  106. #endif
  107. #define JSON_HEDLEY_STRINGIFY_EX(x) #x
  108. #if defined(JSON_HEDLEY_STRINGIFY)
  109. #undef JSON_HEDLEY_STRINGIFY
  110. #endif
  111. #define JSON_HEDLEY_STRINGIFY(x) JSON_HEDLEY_STRINGIFY_EX(x)
  112. #if defined(JSON_HEDLEY_CONCAT_EX)
  113. #undef JSON_HEDLEY_CONCAT_EX
  114. #endif
  115. #define JSON_HEDLEY_CONCAT_EX(a,b) a##b
  116. #if defined(JSON_HEDLEY_CONCAT)
  117. #undef JSON_HEDLEY_CONCAT
  118. #endif
  119. #define JSON_HEDLEY_CONCAT(a,b) JSON_HEDLEY_CONCAT_EX(a,b)
  120. #if defined(JSON_HEDLEY_VERSION_ENCODE)
  121. #undef JSON_HEDLEY_VERSION_ENCODE
  122. #endif
  123. #define JSON_HEDLEY_VERSION_ENCODE(major,minor,revision) (((major) * 1000000) + ((minor) * 1000) + (revision))
  124. #if defined(JSON_HEDLEY_VERSION_DECODE_MAJOR)
  125. #undef JSON_HEDLEY_VERSION_DECODE_MAJOR
  126. #endif
  127. #define JSON_HEDLEY_VERSION_DECODE_MAJOR(version) ((version) / 1000000)
  128. #if defined(JSON_HEDLEY_VERSION_DECODE_MINOR)
  129. #undef JSON_HEDLEY_VERSION_DECODE_MINOR
  130. #endif
  131. #define JSON_HEDLEY_VERSION_DECODE_MINOR(version) (((version) % 1000000) / 1000)
  132. #if defined(JSON_HEDLEY_VERSION_DECODE_REVISION)
  133. #undef JSON_HEDLEY_VERSION_DECODE_REVISION
  134. #endif
  135. #define JSON_HEDLEY_VERSION_DECODE_REVISION(version) ((version) % 1000)
  136. #if defined(JSON_HEDLEY_GNUC_VERSION)
  137. #undef JSON_HEDLEY_GNUC_VERSION
  138. #endif
  139. #if defined(__GNUC__) && defined(__GNUC_PATCHLEVEL__)
  140. #define JSON_HEDLEY_GNUC_VERSION JSON_HEDLEY_VERSION_ENCODE(__GNUC__, __GNUC_MINOR__, __GNUC_PATCHLEVEL__)
  141. #elif defined(__GNUC__)
  142. #define JSON_HEDLEY_GNUC_VERSION JSON_HEDLEY_VERSION_ENCODE(__GNUC__, __GNUC_MINOR__, 0)
  143. #endif
  144. #if defined(JSON_HEDLEY_GNUC_VERSION_CHECK)
  145. #undef JSON_HEDLEY_GNUC_VERSION_CHECK
  146. #endif
  147. #if defined(JSON_HEDLEY_GNUC_VERSION)
  148. #define JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_GNUC_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
  149. #else
  150. #define JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch) (0)
  151. #endif
  152. #if defined(JSON_HEDLEY_MSVC_VERSION)
  153. #undef JSON_HEDLEY_MSVC_VERSION
  154. #endif
  155. #if defined(_MSC_FULL_VER) && (_MSC_FULL_VER >= 140000000)
  156. #define JSON_HEDLEY_MSVC_VERSION JSON_HEDLEY_VERSION_ENCODE(_MSC_FULL_VER / 10000000, (_MSC_FULL_VER % 10000000) / 100000, (_MSC_FULL_VER % 100000) / 100)
  157. #elif defined(_MSC_FULL_VER)
  158. #define JSON_HEDLEY_MSVC_VERSION JSON_HEDLEY_VERSION_ENCODE(_MSC_FULL_VER / 1000000, (_MSC_FULL_VER % 1000000) / 10000, (_MSC_FULL_VER % 10000) / 10)
  159. #elif defined(_MSC_VER)
  160. #define JSON_HEDLEY_MSVC_VERSION JSON_HEDLEY_VERSION_ENCODE(_MSC_VER / 100, _MSC_VER % 100, 0)
  161. #endif
  162. #if defined(JSON_HEDLEY_MSVC_VERSION_CHECK)
  163. #undef JSON_HEDLEY_MSVC_VERSION_CHECK
  164. #endif
  165. #if !defined(_MSC_VER)
  166. #define JSON_HEDLEY_MSVC_VERSION_CHECK(major,minor,patch) (0)
  167. #elif defined(_MSC_VER) && (_MSC_VER >= 1400)
  168. #define JSON_HEDLEY_MSVC_VERSION_CHECK(major,minor,patch) (_MSC_FULL_VER >= ((major * 10000000) + (minor * 100000) + (patch)))
  169. #elif defined(_MSC_VER) && (_MSC_VER >= 1200)
  170. #define JSON_HEDLEY_MSVC_VERSION_CHECK(major,minor,patch) (_MSC_FULL_VER >= ((major * 1000000) + (minor * 10000) + (patch)))
  171. #else
  172. #define JSON_HEDLEY_MSVC_VERSION_CHECK(major,minor,patch) (_MSC_VER >= ((major * 100) + (minor)))
  173. #endif
  174. #if defined(JSON_HEDLEY_INTEL_VERSION)
  175. #undef JSON_HEDLEY_INTEL_VERSION
  176. #endif
  177. #if defined(__INTEL_COMPILER) && defined(__INTEL_COMPILER_UPDATE)
  178. #define JSON_HEDLEY_INTEL_VERSION JSON_HEDLEY_VERSION_ENCODE(__INTEL_COMPILER / 100, __INTEL_COMPILER % 100, __INTEL_COMPILER_UPDATE)
  179. #elif defined(__INTEL_COMPILER)
  180. #define JSON_HEDLEY_INTEL_VERSION JSON_HEDLEY_VERSION_ENCODE(__INTEL_COMPILER / 100, __INTEL_COMPILER % 100, 0)
  181. #endif
  182. #if defined(JSON_HEDLEY_INTEL_VERSION_CHECK)
  183. #undef JSON_HEDLEY_INTEL_VERSION_CHECK
  184. #endif
  185. #if defined(JSON_HEDLEY_INTEL_VERSION)
  186. #define JSON_HEDLEY_INTEL_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_INTEL_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
  187. #else
  188. #define JSON_HEDLEY_INTEL_VERSION_CHECK(major,minor,patch) (0)
  189. #endif
  190. #if defined(JSON_HEDLEY_PGI_VERSION)
  191. #undef JSON_HEDLEY_PGI_VERSION
  192. #endif
  193. #if defined(__PGI) && defined(__PGIC__) && defined(__PGIC_MINOR__) && defined(__PGIC_PATCHLEVEL__)
  194. #define JSON_HEDLEY_PGI_VERSION JSON_HEDLEY_VERSION_ENCODE(__PGIC__, __PGIC_MINOR__, __PGIC_PATCHLEVEL__)
  195. #endif
  196. #if defined(JSON_HEDLEY_PGI_VERSION_CHECK)
  197. #undef JSON_HEDLEY_PGI_VERSION_CHECK
  198. #endif
  199. #if defined(JSON_HEDLEY_PGI_VERSION)
  200. #define JSON_HEDLEY_PGI_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_PGI_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
  201. #else
  202. #define JSON_HEDLEY_PGI_VERSION_CHECK(major,minor,patch) (0)
  203. #endif
  204. #if defined(JSON_HEDLEY_SUNPRO_VERSION)
  205. #undef JSON_HEDLEY_SUNPRO_VERSION
  206. #endif
  207. #if defined(__SUNPRO_C) && (__SUNPRO_C > 0x1000)
  208. #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)
  209. #elif defined(__SUNPRO_C)
  210. #define JSON_HEDLEY_SUNPRO_VERSION JSON_HEDLEY_VERSION_ENCODE((__SUNPRO_C >> 8) & 0xf, (__SUNPRO_C >> 4) & 0xf, (__SUNPRO_C) & 0xf)
  211. #elif defined(__SUNPRO_CC) && (__SUNPRO_CC > 0x1000)
  212. #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)
  213. #elif defined(__SUNPRO_CC)
  214. #define JSON_HEDLEY_SUNPRO_VERSION JSON_HEDLEY_VERSION_ENCODE((__SUNPRO_CC >> 8) & 0xf, (__SUNPRO_CC >> 4) & 0xf, (__SUNPRO_CC) & 0xf)
  215. #endif
  216. #if defined(JSON_HEDLEY_SUNPRO_VERSION_CHECK)
  217. #undef JSON_HEDLEY_SUNPRO_VERSION_CHECK
  218. #endif
  219. #if defined(JSON_HEDLEY_SUNPRO_VERSION)
  220. #define JSON_HEDLEY_SUNPRO_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_SUNPRO_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
  221. #else
  222. #define JSON_HEDLEY_SUNPRO_VERSION_CHECK(major,minor,patch) (0)
  223. #endif
  224. #if defined(JSON_HEDLEY_EMSCRIPTEN_VERSION)
  225. #undef JSON_HEDLEY_EMSCRIPTEN_VERSION
  226. #endif
  227. #if defined(__EMSCRIPTEN__)
  228. #define JSON_HEDLEY_EMSCRIPTEN_VERSION JSON_HEDLEY_VERSION_ENCODE(__EMSCRIPTEN_major__, __EMSCRIPTEN_minor__, __EMSCRIPTEN_tiny__)
  229. #endif
  230. #if defined(JSON_HEDLEY_EMSCRIPTEN_VERSION_CHECK)
  231. #undef JSON_HEDLEY_EMSCRIPTEN_VERSION_CHECK
  232. #endif
  233. #if defined(JSON_HEDLEY_EMSCRIPTEN_VERSION)
  234. #define JSON_HEDLEY_EMSCRIPTEN_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_EMSCRIPTEN_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
  235. #else
  236. #define JSON_HEDLEY_EMSCRIPTEN_VERSION_CHECK(major,minor,patch) (0)
  237. #endif
  238. #if defined(JSON_HEDLEY_ARM_VERSION)
  239. #undef JSON_HEDLEY_ARM_VERSION
  240. #endif
  241. #if defined(__CC_ARM) && defined(__ARMCOMPILER_VERSION)
  242. #define JSON_HEDLEY_ARM_VERSION JSON_HEDLEY_VERSION_ENCODE(__ARMCOMPILER_VERSION / 1000000, (__ARMCOMPILER_VERSION % 1000000) / 10000, (__ARMCOMPILER_VERSION % 10000) / 100)
  243. #elif defined(__CC_ARM) && defined(__ARMCC_VERSION)
  244. #define JSON_HEDLEY_ARM_VERSION JSON_HEDLEY_VERSION_ENCODE(__ARMCC_VERSION / 1000000, (__ARMCC_VERSION % 1000000) / 10000, (__ARMCC_VERSION % 10000) / 100)
  245. #endif
  246. #if defined(JSON_HEDLEY_ARM_VERSION_CHECK)
  247. #undef JSON_HEDLEY_ARM_VERSION_CHECK
  248. #endif
  249. #if defined(JSON_HEDLEY_ARM_VERSION)
  250. #define JSON_HEDLEY_ARM_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_ARM_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
  251. #else
  252. #define JSON_HEDLEY_ARM_VERSION_CHECK(major,minor,patch) (0)
  253. #endif
  254. #if defined(JSON_HEDLEY_IBM_VERSION)
  255. #undef JSON_HEDLEY_IBM_VERSION
  256. #endif
  257. #if defined(__ibmxl__)
  258. #define JSON_HEDLEY_IBM_VERSION JSON_HEDLEY_VERSION_ENCODE(__ibmxl_version__, __ibmxl_release__, __ibmxl_modification__)
  259. #elif defined(__xlC__) && defined(__xlC_ver__)
  260. #define JSON_HEDLEY_IBM_VERSION JSON_HEDLEY_VERSION_ENCODE(__xlC__ >> 8, __xlC__ & 0xff, (__xlC_ver__ >> 8) & 0xff)
  261. #elif defined(__xlC__)
  262. #define JSON_HEDLEY_IBM_VERSION JSON_HEDLEY_VERSION_ENCODE(__xlC__ >> 8, __xlC__ & 0xff, 0)
  263. #endif
  264. #if defined(JSON_HEDLEY_IBM_VERSION_CHECK)
  265. #undef JSON_HEDLEY_IBM_VERSION_CHECK
  266. #endif
  267. #if defined(JSON_HEDLEY_IBM_VERSION)
  268. #define JSON_HEDLEY_IBM_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_IBM_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
  269. #else
  270. #define JSON_HEDLEY_IBM_VERSION_CHECK(major,minor,patch) (0)
  271. #endif
  272. #if defined(JSON_HEDLEY_TI_VERSION)
  273. #undef JSON_HEDLEY_TI_VERSION
  274. #endif
  275. #if defined(__TI_COMPILER_VERSION__)
  276. #define JSON_HEDLEY_TI_VERSION JSON_HEDLEY_VERSION_ENCODE(__TI_COMPILER_VERSION__ / 1000000, (__TI_COMPILER_VERSION__ % 1000000) / 1000, (__TI_COMPILER_VERSION__ % 1000))
  277. #endif
  278. #if defined(JSON_HEDLEY_TI_VERSION_CHECK)
  279. #undef JSON_HEDLEY_TI_VERSION_CHECK
  280. #endif
  281. #if defined(JSON_HEDLEY_TI_VERSION)
  282. #define JSON_HEDLEY_TI_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_TI_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
  283. #else
  284. #define JSON_HEDLEY_TI_VERSION_CHECK(major,minor,patch) (0)
  285. #endif
  286. #if defined(JSON_HEDLEY_CRAY_VERSION)
  287. #undef JSON_HEDLEY_CRAY_VERSION
  288. #endif
  289. #if defined(_CRAYC)
  290. #if defined(_RELEASE_PATCHLEVEL)
  291. #define JSON_HEDLEY_CRAY_VERSION JSON_HEDLEY_VERSION_ENCODE(_RELEASE_MAJOR, _RELEASE_MINOR, _RELEASE_PATCHLEVEL)
  292. #else
  293. #define JSON_HEDLEY_CRAY_VERSION JSON_HEDLEY_VERSION_ENCODE(_RELEASE_MAJOR, _RELEASE_MINOR, 0)
  294. #endif
  295. #endif
  296. #if defined(JSON_HEDLEY_CRAY_VERSION_CHECK)
  297. #undef JSON_HEDLEY_CRAY_VERSION_CHECK
  298. #endif
  299. #if defined(JSON_HEDLEY_CRAY_VERSION)
  300. #define JSON_HEDLEY_CRAY_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_CRAY_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
  301. #else
  302. #define JSON_HEDLEY_CRAY_VERSION_CHECK(major,minor,patch) (0)
  303. #endif
  304. #if defined(JSON_HEDLEY_IAR_VERSION)
  305. #undef JSON_HEDLEY_IAR_VERSION
  306. #endif
  307. #if defined(__IAR_SYSTEMS_ICC__)
  308. #if __VER__ > 1000
  309. #define JSON_HEDLEY_IAR_VERSION JSON_HEDLEY_VERSION_ENCODE((__VER__ / 1000000), ((__VER__ / 1000) % 1000), (__VER__ % 1000))
  310. #else
  311. #define JSON_HEDLEY_IAR_VERSION JSON_HEDLEY_VERSION_ENCODE(VER / 100, __VER__ % 100, 0)
  312. #endif
  313. #endif
  314. #if defined(JSON_HEDLEY_IAR_VERSION_CHECK)
  315. #undef JSON_HEDLEY_IAR_VERSION_CHECK
  316. #endif
  317. #if defined(JSON_HEDLEY_IAR_VERSION)
  318. #define JSON_HEDLEY_IAR_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_IAR_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
  319. #else
  320. #define JSON_HEDLEY_IAR_VERSION_CHECK(major,minor,patch) (0)
  321. #endif
  322. #if defined(JSON_HEDLEY_TINYC_VERSION)
  323. #undef JSON_HEDLEY_TINYC_VERSION
  324. #endif
  325. #if defined(__TINYC__)
  326. #define JSON_HEDLEY_TINYC_VERSION JSON_HEDLEY_VERSION_ENCODE(__TINYC__ / 1000, (__TINYC__ / 100) % 10, __TINYC__ % 100)
  327. #endif
  328. #if defined(JSON_HEDLEY_TINYC_VERSION_CHECK)
  329. #undef JSON_HEDLEY_TINYC_VERSION_CHECK
  330. #endif
  331. #if defined(JSON_HEDLEY_TINYC_VERSION)
  332. #define JSON_HEDLEY_TINYC_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_TINYC_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
  333. #else
  334. #define JSON_HEDLEY_TINYC_VERSION_CHECK(major,minor,patch) (0)
  335. #endif
  336. #if defined(JSON_HEDLEY_DMC_VERSION)
  337. #undef JSON_HEDLEY_DMC_VERSION
  338. #endif
  339. #if defined(__DMC__)
  340. #define JSON_HEDLEY_DMC_VERSION JSON_HEDLEY_VERSION_ENCODE(__DMC__ >> 8, (__DMC__ >> 4) & 0xf, __DMC__ & 0xf)
  341. #endif
  342. #if defined(JSON_HEDLEY_DMC_VERSION_CHECK)
  343. #undef JSON_HEDLEY_DMC_VERSION_CHECK
  344. #endif
  345. #if defined(JSON_HEDLEY_DMC_VERSION)
  346. #define JSON_HEDLEY_DMC_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_DMC_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
  347. #else
  348. #define JSON_HEDLEY_DMC_VERSION_CHECK(major,minor,patch) (0)
  349. #endif
  350. #if defined(JSON_HEDLEY_COMPCERT_VERSION)
  351. #undef JSON_HEDLEY_COMPCERT_VERSION
  352. #endif
  353. #if defined(__COMPCERT_VERSION__)
  354. #define JSON_HEDLEY_COMPCERT_VERSION JSON_HEDLEY_VERSION_ENCODE(__COMPCERT_VERSION__ / 10000, (__COMPCERT_VERSION__ / 100) % 100, __COMPCERT_VERSION__ % 100)
  355. #endif
  356. #if defined(JSON_HEDLEY_COMPCERT_VERSION_CHECK)
  357. #undef JSON_HEDLEY_COMPCERT_VERSION_CHECK
  358. #endif
  359. #if defined(JSON_HEDLEY_COMPCERT_VERSION)
  360. #define JSON_HEDLEY_COMPCERT_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_COMPCERT_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
  361. #else
  362. #define JSON_HEDLEY_COMPCERT_VERSION_CHECK(major,minor,patch) (0)
  363. #endif
  364. #if defined(JSON_HEDLEY_PELLES_VERSION)
  365. #undef JSON_HEDLEY_PELLES_VERSION
  366. #endif
  367. #if defined(__POCC__)
  368. #define JSON_HEDLEY_PELLES_VERSION JSON_HEDLEY_VERSION_ENCODE(__POCC__ / 100, __POCC__ % 100, 0)
  369. #endif
  370. #if defined(JSON_HEDLEY_PELLES_VERSION_CHECK)
  371. #undef JSON_HEDLEY_PELLES_VERSION_CHECK
  372. #endif
  373. #if defined(JSON_HEDLEY_PELLES_VERSION)
  374. #define JSON_HEDLEY_PELLES_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_PELLES_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
  375. #else
  376. #define JSON_HEDLEY_PELLES_VERSION_CHECK(major,minor,patch) (0)
  377. #endif
  378. #if defined(JSON_HEDLEY_GCC_VERSION)
  379. #undef JSON_HEDLEY_GCC_VERSION
  380. #endif
  381. #if \
  382. defined(JSON_HEDLEY_GNUC_VERSION) && \
  383. !defined(__clang__) && \
  384. !defined(JSON_HEDLEY_INTEL_VERSION) && \
  385. !defined(JSON_HEDLEY_PGI_VERSION) && \
  386. !defined(JSON_HEDLEY_ARM_VERSION) && \
  387. !defined(JSON_HEDLEY_TI_VERSION) && \
  388. !defined(__COMPCERT__)
  389. #define JSON_HEDLEY_GCC_VERSION JSON_HEDLEY_GNUC_VERSION
  390. #endif
  391. #if defined(JSON_HEDLEY_GCC_VERSION_CHECK)
  392. #undef JSON_HEDLEY_GCC_VERSION_CHECK
  393. #endif
  394. #if defined(JSON_HEDLEY_GCC_VERSION)
  395. #define JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_GCC_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
  396. #else
  397. #define JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch) (0)
  398. #endif
  399. #if defined(JSON_HEDLEY_HAS_ATTRIBUTE)
  400. #undef JSON_HEDLEY_HAS_ATTRIBUTE
  401. #endif
  402. #if defined(__has_attribute)
  403. #define JSON_HEDLEY_HAS_ATTRIBUTE(attribute) __has_attribute(attribute)
  404. #else
  405. #define JSON_HEDLEY_HAS_ATTRIBUTE(attribute) (0)
  406. #endif
  407. #if defined(JSON_HEDLEY_GNUC_HAS_ATTRIBUTE)
  408. #undef JSON_HEDLEY_GNUC_HAS_ATTRIBUTE
  409. #endif
  410. #if defined(__has_attribute)
  411. #define JSON_HEDLEY_GNUC_HAS_ATTRIBUTE(attribute,major,minor,patch) __has_attribute(attribute)
  412. #else
  413. #define JSON_HEDLEY_GNUC_HAS_ATTRIBUTE(attribute,major,minor,patch) JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch)
  414. #endif
  415. #if defined(JSON_HEDLEY_GCC_HAS_ATTRIBUTE)
  416. #undef JSON_HEDLEY_GCC_HAS_ATTRIBUTE
  417. #endif
  418. #if defined(__has_attribute)
  419. #define JSON_HEDLEY_GCC_HAS_ATTRIBUTE(attribute,major,minor,patch) __has_attribute(attribute)
  420. #else
  421. #define JSON_HEDLEY_GCC_HAS_ATTRIBUTE(attribute,major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch)
  422. #endif
  423. #if defined(JSON_HEDLEY_HAS_CPP_ATTRIBUTE)
  424. #undef JSON_HEDLEY_HAS_CPP_ATTRIBUTE
  425. #endif
  426. #if defined(__has_cpp_attribute) && defined(__cplusplus)
  427. #define JSON_HEDLEY_HAS_CPP_ATTRIBUTE(attribute) __has_cpp_attribute(attribute)
  428. #else
  429. #define JSON_HEDLEY_HAS_CPP_ATTRIBUTE(attribute) (0)
  430. #endif
  431. #if defined(JSON_HEDLEY_GNUC_HAS_CPP_ATTRIBUTE)
  432. #undef JSON_HEDLEY_GNUC_HAS_CPP_ATTRIBUTE
  433. #endif
  434. #if defined(__has_cpp_attribute) && defined(__cplusplus)
  435. #define JSON_HEDLEY_GNUC_HAS_CPP_ATTRIBUTE(attribute,major,minor,patch) __has_cpp_attribute(attribute)
  436. #else
  437. #define JSON_HEDLEY_GNUC_HAS_CPP_ATTRIBUTE(attribute,major,minor,patch) JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch)
  438. #endif
  439. #if defined(JSON_HEDLEY_GCC_HAS_CPP_ATTRIBUTE)
  440. #undef JSON_HEDLEY_GCC_HAS_CPP_ATTRIBUTE
  441. #endif
  442. #if defined(__has_cpp_attribute) && defined(__cplusplus)
  443. #define JSON_HEDLEY_GCC_HAS_CPP_ATTRIBUTE(attribute,major,minor,patch) __has_cpp_attribute(attribute)
  444. #else
  445. #define JSON_HEDLEY_GCC_HAS_CPP_ATTRIBUTE(attribute,major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch)
  446. #endif
  447. #if defined(JSON_HEDLEY_HAS_BUILTIN)
  448. #undef JSON_HEDLEY_HAS_BUILTIN
  449. #endif
  450. #if defined(__has_builtin)
  451. #define JSON_HEDLEY_HAS_BUILTIN(builtin) __has_builtin(builtin)
  452. #else
  453. #define JSON_HEDLEY_HAS_BUILTIN(builtin) (0)
  454. #endif
  455. #if defined(JSON_HEDLEY_GNUC_HAS_BUILTIN)
  456. #undef JSON_HEDLEY_GNUC_HAS_BUILTIN
  457. #endif
  458. #if defined(__has_builtin)
  459. #define JSON_HEDLEY_GNUC_HAS_BUILTIN(builtin,major,minor,patch) __has_builtin(builtin)
  460. #else
  461. #define JSON_HEDLEY_GNUC_HAS_BUILTIN(builtin,major,minor,patch) JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch)
  462. #endif
  463. #if defined(JSON_HEDLEY_GCC_HAS_BUILTIN)
  464. #undef JSON_HEDLEY_GCC_HAS_BUILTIN
  465. #endif
  466. #if defined(__has_builtin)
  467. #define JSON_HEDLEY_GCC_HAS_BUILTIN(builtin,major,minor,patch) __has_builtin(builtin)
  468. #else
  469. #define JSON_HEDLEY_GCC_HAS_BUILTIN(builtin,major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch)
  470. #endif
  471. #if defined(JSON_HEDLEY_HAS_FEATURE)
  472. #undef JSON_HEDLEY_HAS_FEATURE
  473. #endif
  474. #if defined(__has_feature)
  475. #define JSON_HEDLEY_HAS_FEATURE(feature) __has_feature(feature)
  476. #else
  477. #define JSON_HEDLEY_HAS_FEATURE(feature) (0)
  478. #endif
  479. #if defined(JSON_HEDLEY_GNUC_HAS_FEATURE)
  480. #undef JSON_HEDLEY_GNUC_HAS_FEATURE
  481. #endif
  482. #if defined(__has_feature)
  483. #define JSON_HEDLEY_GNUC_HAS_FEATURE(feature,major,minor,patch) __has_feature(feature)
  484. #else
  485. #define JSON_HEDLEY_GNUC_HAS_FEATURE(feature,major,minor,patch) JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch)
  486. #endif
  487. #if defined(JSON_HEDLEY_GCC_HAS_FEATURE)
  488. #undef JSON_HEDLEY_GCC_HAS_FEATURE
  489. #endif
  490. #if defined(__has_feature)
  491. #define JSON_HEDLEY_GCC_HAS_FEATURE(feature,major,minor,patch) __has_feature(feature)
  492. #else
  493. #define JSON_HEDLEY_GCC_HAS_FEATURE(feature,major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch)
  494. #endif
  495. #if defined(JSON_HEDLEY_HAS_EXTENSION)
  496. #undef JSON_HEDLEY_HAS_EXTENSION
  497. #endif
  498. #if defined(__has_extension)
  499. #define JSON_HEDLEY_HAS_EXTENSION(extension) __has_extension(extension)
  500. #else
  501. #define JSON_HEDLEY_HAS_EXTENSION(extension) (0)
  502. #endif
  503. #if defined(JSON_HEDLEY_GNUC_HAS_EXTENSION)
  504. #undef JSON_HEDLEY_GNUC_HAS_EXTENSION
  505. #endif
  506. #if defined(__has_extension)
  507. #define JSON_HEDLEY_GNUC_HAS_EXTENSION(extension,major,minor,patch) __has_extension(extension)
  508. #else
  509. #define JSON_HEDLEY_GNUC_HAS_EXTENSION(extension,major,minor,patch) JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch)
  510. #endif
  511. #if defined(JSON_HEDLEY_GCC_HAS_EXTENSION)
  512. #undef JSON_HEDLEY_GCC_HAS_EXTENSION
  513. #endif
  514. #if defined(__has_extension)
  515. #define JSON_HEDLEY_GCC_HAS_EXTENSION(extension,major,minor,patch) __has_extension(extension)
  516. #else
  517. #define JSON_HEDLEY_GCC_HAS_EXTENSION(extension,major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch)
  518. #endif
  519. #if defined(JSON_HEDLEY_HAS_DECLSPEC_ATTRIBUTE)
  520. #undef JSON_HEDLEY_HAS_DECLSPEC_ATTRIBUTE
  521. #endif
  522. #if defined(__has_declspec_attribute)
  523. #define JSON_HEDLEY_HAS_DECLSPEC_ATTRIBUTE(attribute) __has_declspec_attribute(attribute)
  524. #else
  525. #define JSON_HEDLEY_HAS_DECLSPEC_ATTRIBUTE(attribute) (0)
  526. #endif
  527. #if defined(JSON_HEDLEY_GNUC_HAS_DECLSPEC_ATTRIBUTE)
  528. #undef JSON_HEDLEY_GNUC_HAS_DECLSPEC_ATTRIBUTE
  529. #endif
  530. #if defined(__has_declspec_attribute)
  531. #define JSON_HEDLEY_GNUC_HAS_DECLSPEC_ATTRIBUTE(attribute,major,minor,patch) __has_declspec_attribute(attribute)
  532. #else
  533. #define JSON_HEDLEY_GNUC_HAS_DECLSPEC_ATTRIBUTE(attribute,major,minor,patch) JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch)
  534. #endif
  535. #if defined(JSON_HEDLEY_GCC_HAS_DECLSPEC_ATTRIBUTE)
  536. #undef JSON_HEDLEY_GCC_HAS_DECLSPEC_ATTRIBUTE
  537. #endif
  538. #if defined(__has_declspec_attribute)
  539. #define JSON_HEDLEY_GCC_HAS_DECLSPEC_ATTRIBUTE(attribute,major,minor,patch) __has_declspec_attribute(attribute)
  540. #else
  541. #define JSON_HEDLEY_GCC_HAS_DECLSPEC_ATTRIBUTE(attribute,major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch)
  542. #endif
  543. #if defined(JSON_HEDLEY_HAS_WARNING)
  544. #undef JSON_HEDLEY_HAS_WARNING
  545. #endif
  546. #if defined(__has_warning)
  547. #define JSON_HEDLEY_HAS_WARNING(warning) __has_warning(warning)
  548. #else
  549. #define JSON_HEDLEY_HAS_WARNING(warning) (0)
  550. #endif
  551. #if defined(JSON_HEDLEY_GNUC_HAS_WARNING)
  552. #undef JSON_HEDLEY_GNUC_HAS_WARNING
  553. #endif
  554. #if defined(__has_warning)
  555. #define JSON_HEDLEY_GNUC_HAS_WARNING(warning,major,minor,patch) __has_warning(warning)
  556. #else
  557. #define JSON_HEDLEY_GNUC_HAS_WARNING(warning,major,minor,patch) JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch)
  558. #endif
  559. #if defined(JSON_HEDLEY_GCC_HAS_WARNING)
  560. #undef JSON_HEDLEY_GCC_HAS_WARNING
  561. #endif
  562. #if defined(__has_warning)
  563. #define JSON_HEDLEY_GCC_HAS_WARNING(warning,major,minor,patch) __has_warning(warning)
  564. #else
  565. #define JSON_HEDLEY_GCC_HAS_WARNING(warning,major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch)
  566. #endif
  567. #if \
  568. (defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L)) || \
  569. defined(__clang__) || \
  570. JSON_HEDLEY_GCC_VERSION_CHECK(3,0,0) || \
  571. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
  572. JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0) || \
  573. JSON_HEDLEY_PGI_VERSION_CHECK(18,4,0) || \
  574. JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \
  575. JSON_HEDLEY_TI_VERSION_CHECK(6,0,0) || \
  576. JSON_HEDLEY_CRAY_VERSION_CHECK(5,0,0) || \
  577. JSON_HEDLEY_TINYC_VERSION_CHECK(0,9,17) || \
  578. JSON_HEDLEY_SUNPRO_VERSION_CHECK(8,0,0) || \
  579. (JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) && defined(__C99_PRAGMA_OPERATOR))
  580. #define JSON_HEDLEY_PRAGMA(value) _Pragma(#value)
  581. #elif JSON_HEDLEY_MSVC_VERSION_CHECK(15,0,0)
  582. #define JSON_HEDLEY_PRAGMA(value) __pragma(value)
  583. #else
  584. #define JSON_HEDLEY_PRAGMA(value)
  585. #endif
  586. #if defined(JSON_HEDLEY_DIAGNOSTIC_PUSH)
  587. #undef JSON_HEDLEY_DIAGNOSTIC_PUSH
  588. #endif
  589. #if defined(JSON_HEDLEY_DIAGNOSTIC_POP)
  590. #undef JSON_HEDLEY_DIAGNOSTIC_POP
  591. #endif
  592. #if defined(__clang__)
  593. #define JSON_HEDLEY_DIAGNOSTIC_PUSH _Pragma("clang diagnostic push")
  594. #define JSON_HEDLEY_DIAGNOSTIC_POP _Pragma("clang diagnostic pop")
  595. #elif JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0)
  596. #define JSON_HEDLEY_DIAGNOSTIC_PUSH _Pragma("warning(push)")
  597. #define JSON_HEDLEY_DIAGNOSTIC_POP _Pragma("warning(pop)")
  598. #elif JSON_HEDLEY_GCC_VERSION_CHECK(4,6,0)
  599. #define JSON_HEDLEY_DIAGNOSTIC_PUSH _Pragma("GCC diagnostic push")
  600. #define JSON_HEDLEY_DIAGNOSTIC_POP _Pragma("GCC diagnostic pop")
  601. #elif JSON_HEDLEY_MSVC_VERSION_CHECK(15,0,0)
  602. #define JSON_HEDLEY_DIAGNOSTIC_PUSH __pragma(warning(push))
  603. #define JSON_HEDLEY_DIAGNOSTIC_POP __pragma(warning(pop))
  604. #elif JSON_HEDLEY_ARM_VERSION_CHECK(5,6,0)
  605. #define JSON_HEDLEY_DIAGNOSTIC_PUSH _Pragma("push")
  606. #define JSON_HEDLEY_DIAGNOSTIC_POP _Pragma("pop")
  607. #elif JSON_HEDLEY_TI_VERSION_CHECK(8,1,0)
  608. #define JSON_HEDLEY_DIAGNOSTIC_PUSH _Pragma("diag_push")
  609. #define JSON_HEDLEY_DIAGNOSTIC_POP _Pragma("diag_pop")
  610. #elif JSON_HEDLEY_PELLES_VERSION_CHECK(2,90,0)
  611. #define JSON_HEDLEY_DIAGNOSTIC_PUSH _Pragma("warning(push)")
  612. #define JSON_HEDLEY_DIAGNOSTIC_POP _Pragma("warning(pop)")
  613. #else
  614. #define JSON_HEDLEY_DIAGNOSTIC_PUSH
  615. #define JSON_HEDLEY_DIAGNOSTIC_POP
  616. #endif
  617. #if defined(JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED)
  618. #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED
  619. #endif
  620. #if JSON_HEDLEY_HAS_WARNING("-Wdeprecated-declarations")
  621. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("clang diagnostic ignored \"-Wdeprecated-declarations\"")
  622. #elif JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0)
  623. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("warning(disable:1478 1786)")
  624. #elif JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0)
  625. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("diag_suppress 1215,1444")
  626. #elif JSON_HEDLEY_GCC_VERSION_CHECK(4,3,0)
  627. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("GCC diagnostic ignored \"-Wdeprecated-declarations\"")
  628. #elif JSON_HEDLEY_MSVC_VERSION_CHECK(15,0,0)
  629. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED __pragma(warning(disable:4996))
  630. #elif JSON_HEDLEY_TI_VERSION_CHECK(8,0,0)
  631. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("diag_suppress 1291,1718")
  632. #elif JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,13,0) && !defined(__cplusplus)
  633. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("error_messages(off,E_DEPRECATED_ATT,E_DEPRECATED_ATT_MESS)")
  634. #elif JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,13,0) && defined(__cplusplus)
  635. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("error_messages(off,symdeprecated,symdeprecated2)")
  636. #elif JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0)
  637. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("diag_suppress=Pe1444,Pe1215")
  638. #elif JSON_HEDLEY_PELLES_VERSION_CHECK(2,90,0)
  639. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("warn(disable:2241)")
  640. #else
  641. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED
  642. #endif
  643. #if defined(JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS)
  644. #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS
  645. #endif
  646. #if JSON_HEDLEY_HAS_WARNING("-Wunknown-pragmas")
  647. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("clang diagnostic ignored \"-Wunknown-pragmas\"")
  648. #elif JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0)
  649. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("warning(disable:161)")
  650. #elif JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0)
  651. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("diag_suppress 1675")
  652. #elif JSON_HEDLEY_GCC_VERSION_CHECK(4,3,0)
  653. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("GCC diagnostic ignored \"-Wunknown-pragmas\"")
  654. #elif JSON_HEDLEY_MSVC_VERSION_CHECK(15,0,0)
  655. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS __pragma(warning(disable:4068))
  656. #elif JSON_HEDLEY_TI_VERSION_CHECK(8,0,0)
  657. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("diag_suppress 163")
  658. #elif JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0)
  659. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("diag_suppress=Pe161")
  660. #else
  661. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS
  662. #endif
  663. #if defined(JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL)
  664. #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL
  665. #endif
  666. #if JSON_HEDLEY_HAS_WARNING("-Wcast-qual")
  667. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL _Pragma("clang diagnostic ignored \"-Wcast-qual\"")
  668. #elif JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0)
  669. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL _Pragma("warning(disable:2203 2331)")
  670. #elif JSON_HEDLEY_GCC_VERSION_CHECK(3,0,0)
  671. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL _Pragma("GCC diagnostic ignored \"-Wcast-qual\"")
  672. #else
  673. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL
  674. #endif
  675. #if defined(JSON_HEDLEY_DEPRECATED)
  676. #undef JSON_HEDLEY_DEPRECATED
  677. #endif
  678. #if defined(JSON_HEDLEY_DEPRECATED_FOR)
  679. #undef JSON_HEDLEY_DEPRECATED_FOR
  680. #endif
  681. #if defined(__cplusplus) && (__cplusplus >= 201402L)
  682. #define JSON_HEDLEY_DEPRECATED(since) [[deprecated("Since " #since)]]
  683. #define JSON_HEDLEY_DEPRECATED_FOR(since, replacement) [[deprecated("Since " #since "; use " #replacement)]]
  684. #elif \
  685. JSON_HEDLEY_HAS_EXTENSION(attribute_deprecated_with_message) || \
  686. JSON_HEDLEY_GCC_VERSION_CHECK(4,5,0) || \
  687. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
  688. JSON_HEDLEY_ARM_VERSION_CHECK(5,6,0) || \
  689. JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,13,0) || \
  690. JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0) || \
  691. JSON_HEDLEY_TI_VERSION_CHECK(8,3,0)
  692. #define JSON_HEDLEY_DEPRECATED(since) __attribute__((__deprecated__("Since " #since)))
  693. #define JSON_HEDLEY_DEPRECATED_FOR(since, replacement) __attribute__((__deprecated__("Since " #since "; use " #replacement)))
  694. #elif \
  695. JSON_HEDLEY_HAS_ATTRIBUTE(deprecated) || \
  696. JSON_HEDLEY_GCC_VERSION_CHECK(3,1,0) || \
  697. JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \
  698. JSON_HEDLEY_TI_VERSION_CHECK(8,0,0) || \
  699. (JSON_HEDLEY_TI_VERSION_CHECK(7,3,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__))
  700. #define JSON_HEDLEY_DEPRECATED(since) __attribute__((__deprecated__))
  701. #define JSON_HEDLEY_DEPRECATED_FOR(since, replacement) __attribute__((__deprecated__))
  702. #elif JSON_HEDLEY_MSVC_VERSION_CHECK(14,0,0)
  703. #define JSON_HEDLEY_DEPRECATED(since) __declspec(deprecated("Since " # since))
  704. #define JSON_HEDLEY_DEPRECATED_FOR(since, replacement) __declspec(deprecated("Since " #since "; use " #replacement))
  705. #elif \
  706. JSON_HEDLEY_MSVC_VERSION_CHECK(13,10,0) || \
  707. JSON_HEDLEY_PELLES_VERSION_CHECK(6,50,0)
  708. #define JSON_HEDLEY_DEPRECATED(since) _declspec(deprecated)
  709. #define JSON_HEDLEY_DEPRECATED_FOR(since, replacement) __declspec(deprecated)
  710. #elif JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0)
  711. #define JSON_HEDLEY_DEPRECATED(since) _Pragma("deprecated")
  712. #define JSON_HEDLEY_DEPRECATED_FOR(since, replacement) _Pragma("deprecated")
  713. #else
  714. #define JSON_HEDLEY_DEPRECATED(since)
  715. #define JSON_HEDLEY_DEPRECATED_FOR(since, replacement)
  716. #endif
  717. #if defined(JSON_HEDLEY_UNAVAILABLE)
  718. #undef JSON_HEDLEY_UNAVAILABLE
  719. #endif
  720. #if \
  721. JSON_HEDLEY_HAS_ATTRIBUTE(warning) || \
  722. JSON_HEDLEY_GCC_VERSION_CHECK(4,3,0) || \
  723. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0)
  724. #define JSON_HEDLEY_UNAVAILABLE(available_since) __attribute__((__warning__("Not available until " #available_since)))
  725. #else
  726. #define JSON_HEDLEY_UNAVAILABLE(available_since)
  727. #endif
  728. #if defined(JSON_HEDLEY_WARN_UNUSED_RESULT)
  729. #undef JSON_HEDLEY_WARN_UNUSED_RESULT
  730. #endif
  731. #if defined(__cplusplus) && (__cplusplus >= 201703L)
  732. #define JSON_HEDLEY_WARN_UNUSED_RESULT [[nodiscard]]
  733. #elif \
  734. JSON_HEDLEY_HAS_ATTRIBUTE(warn_unused_result) || \
  735. JSON_HEDLEY_GCC_VERSION_CHECK(3,4,0) || \
  736. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
  737. JSON_HEDLEY_TI_VERSION_CHECK(8,0,0) || \
  738. (JSON_HEDLEY_TI_VERSION_CHECK(7,3,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  739. (JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,15,0) && defined(__cplusplus)) || \
  740. JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0)
  741. #define JSON_HEDLEY_WARN_UNUSED_RESULT __attribute__((__warn_unused_result__))
  742. #elif defined(_Check_return_) /* SAL */
  743. #define JSON_HEDLEY_WARN_UNUSED_RESULT _Check_return_
  744. #else
  745. #define JSON_HEDLEY_WARN_UNUSED_RESULT
  746. #endif
  747. #if defined(JSON_HEDLEY_SENTINEL)
  748. #undef JSON_HEDLEY_SENTINEL
  749. #endif
  750. #if \
  751. JSON_HEDLEY_HAS_ATTRIBUTE(sentinel) || \
  752. JSON_HEDLEY_GCC_VERSION_CHECK(4,0,0) || \
  753. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
  754. JSON_HEDLEY_ARM_VERSION_CHECK(5,4,0)
  755. #define JSON_HEDLEY_SENTINEL(position) __attribute__((__sentinel__(position)))
  756. #else
  757. #define JSON_HEDLEY_SENTINEL(position)
  758. #endif
  759. #if defined(JSON_HEDLEY_NO_RETURN)
  760. #undef JSON_HEDLEY_NO_RETURN
  761. #endif
  762. #if JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0)
  763. #define JSON_HEDLEY_NO_RETURN __noreturn
  764. #elif JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0)
  765. #define JSON_HEDLEY_NO_RETURN __attribute__((__noreturn__))
  766. #elif defined(__STDC_VERSION__) && __STDC_VERSION__ >= 201112L
  767. #define JSON_HEDLEY_NO_RETURN _Noreturn
  768. #elif defined(__cplusplus) && (__cplusplus >= 201103L)
  769. #define JSON_HEDLEY_NO_RETURN [[noreturn]]
  770. #elif \
  771. JSON_HEDLEY_HAS_ATTRIBUTE(noreturn) || \
  772. JSON_HEDLEY_GCC_VERSION_CHECK(3,2,0) || \
  773. JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,11,0) || \
  774. JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \
  775. JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \
  776. JSON_HEDLEY_TI_VERSION_CHECK(18,0,0) || \
  777. (JSON_HEDLEY_TI_VERSION_CHECK(17,3,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__))
  778. #define JSON_HEDLEY_NO_RETURN __attribute__((__noreturn__))
  779. #elif JSON_HEDLEY_MSVC_VERSION_CHECK(13,10,0)
  780. #define JSON_HEDLEY_NO_RETURN __declspec(noreturn)
  781. #elif JSON_HEDLEY_TI_VERSION_CHECK(6,0,0) && defined(__cplusplus)
  782. #define JSON_HEDLEY_NO_RETURN _Pragma("FUNC_NEVER_RETURNS;")
  783. #elif JSON_HEDLEY_COMPCERT_VERSION_CHECK(3,2,0)
  784. #define JSON_HEDLEY_NO_RETURN __attribute((noreturn))
  785. #elif JSON_HEDLEY_PELLES_VERSION_CHECK(9,0,0)
  786. #define JSON_HEDLEY_NO_RETURN __declspec(noreturn)
  787. #else
  788. #define JSON_HEDLEY_NO_RETURN
  789. #endif
  790. #if defined(JSON_HEDLEY_UNREACHABLE)
  791. #undef JSON_HEDLEY_UNREACHABLE
  792. #endif
  793. #if defined(JSON_HEDLEY_UNREACHABLE_RETURN)
  794. #undef JSON_HEDLEY_UNREACHABLE_RETURN
  795. #endif
  796. #if \
  797. (JSON_HEDLEY_HAS_BUILTIN(__builtin_unreachable) && (!defined(JSON_HEDLEY_ARM_VERSION))) || \
  798. JSON_HEDLEY_GCC_VERSION_CHECK(4,5,0) || \
  799. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
  800. JSON_HEDLEY_IBM_VERSION_CHECK(13,1,5)
  801. #define JSON_HEDLEY_UNREACHABLE() __builtin_unreachable()
  802. #elif JSON_HEDLEY_MSVC_VERSION_CHECK(13,10,0)
  803. #define JSON_HEDLEY_UNREACHABLE() __assume(0)
  804. #elif JSON_HEDLEY_TI_VERSION_CHECK(6,0,0)
  805. #if defined(__cplusplus)
  806. #define JSON_HEDLEY_UNREACHABLE() std::_nassert(0)
  807. #else
  808. #define JSON_HEDLEY_UNREACHABLE() _nassert(0)
  809. #endif
  810. #define JSON_HEDLEY_UNREACHABLE_RETURN(value) return value
  811. #elif defined(EXIT_FAILURE)
  812. #define JSON_HEDLEY_UNREACHABLE() abort()
  813. #else
  814. #define JSON_HEDLEY_UNREACHABLE()
  815. #define JSON_HEDLEY_UNREACHABLE_RETURN(value) return value
  816. #endif
  817. #if !defined(JSON_HEDLEY_UNREACHABLE_RETURN)
  818. #define JSON_HEDLEY_UNREACHABLE_RETURN(value) JSON_HEDLEY_UNREACHABLE()
  819. #endif
  820. #if defined(JSON_HEDLEY_ASSUME)
  821. #undef JSON_HEDLEY_ASSUME
  822. #endif
  823. #if \
  824. JSON_HEDLEY_MSVC_VERSION_CHECK(13,10,0) || \
  825. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0)
  826. #define JSON_HEDLEY_ASSUME(expr) __assume(expr)
  827. #elif JSON_HEDLEY_HAS_BUILTIN(__builtin_assume)
  828. #define JSON_HEDLEY_ASSUME(expr) __builtin_assume(expr)
  829. #elif JSON_HEDLEY_TI_VERSION_CHECK(6,0,0)
  830. #if defined(__cplusplus)
  831. #define JSON_HEDLEY_ASSUME(expr) std::_nassert(expr)
  832. #else
  833. #define JSON_HEDLEY_ASSUME(expr) _nassert(expr)
  834. #endif
  835. #elif \
  836. (JSON_HEDLEY_HAS_BUILTIN(__builtin_unreachable) && !defined(JSON_HEDLEY_ARM_VERSION)) || \
  837. JSON_HEDLEY_GCC_VERSION_CHECK(4,5,0) || \
  838. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
  839. JSON_HEDLEY_IBM_VERSION_CHECK(13,1,5)
  840. #define JSON_HEDLEY_ASSUME(expr) ((void) ((expr) ? 1 : (__builtin_unreachable(), 1)))
  841. #else
  842. #define JSON_HEDLEY_ASSUME(expr) ((void) (expr))
  843. #endif
  844. JSON_HEDLEY_DIAGNOSTIC_PUSH
  845. #if \
  846. JSON_HEDLEY_HAS_WARNING("-Wvariadic-macros") || \
  847. JSON_HEDLEY_GCC_VERSION_CHECK(4,0,0)
  848. #if defined(__clang__)
  849. #pragma clang diagnostic ignored "-Wvariadic-macros"
  850. #elif defined(JSON_HEDLEY_GCC_VERSION)
  851. #pragma GCC diagnostic ignored "-Wvariadic-macros"
  852. #endif
  853. #endif
  854. #if defined(JSON_HEDLEY_NON_NULL)
  855. #undef JSON_HEDLEY_NON_NULL
  856. #endif
  857. #if \
  858. JSON_HEDLEY_HAS_ATTRIBUTE(nonnull) || \
  859. JSON_HEDLEY_GCC_VERSION_CHECK(3,3,0) || \
  860. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
  861. JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0)
  862. #define JSON_HEDLEY_NON_NULL(...) __attribute__((__nonnull__(__VA_ARGS__)))
  863. #else
  864. #define JSON_HEDLEY_NON_NULL(...)
  865. #endif
  866. JSON_HEDLEY_DIAGNOSTIC_POP
  867. #if defined(JSON_HEDLEY_PRINTF_FORMAT)
  868. #undef JSON_HEDLEY_PRINTF_FORMAT
  869. #endif
  870. #if defined(__MINGW32__) && JSON_HEDLEY_GCC_HAS_ATTRIBUTE(format,4,4,0) && !defined(__USE_MINGW_ANSI_STDIO)
  871. #define JSON_HEDLEY_PRINTF_FORMAT(string_idx,first_to_check) __attribute__((__format__(ms_printf, string_idx, first_to_check)))
  872. #elif defined(__MINGW32__) && JSON_HEDLEY_GCC_HAS_ATTRIBUTE(format,4,4,0) && defined(__USE_MINGW_ANSI_STDIO)
  873. #define JSON_HEDLEY_PRINTF_FORMAT(string_idx,first_to_check) __attribute__((__format__(gnu_printf, string_idx, first_to_check)))
  874. #elif \
  875. JSON_HEDLEY_HAS_ATTRIBUTE(format) || \
  876. JSON_HEDLEY_GCC_VERSION_CHECK(3,1,0) || \
  877. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
  878. JSON_HEDLEY_ARM_VERSION_CHECK(5,6,0) || \
  879. JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \
  880. JSON_HEDLEY_TI_VERSION_CHECK(8,0,0) || \
  881. (JSON_HEDLEY_TI_VERSION_CHECK(7,3,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__))
  882. #define JSON_HEDLEY_PRINTF_FORMAT(string_idx,first_to_check) __attribute__((__format__(__printf__, string_idx, first_to_check)))
  883. #elif JSON_HEDLEY_PELLES_VERSION_CHECK(6,0,0)
  884. #define JSON_HEDLEY_PRINTF_FORMAT(string_idx,first_to_check) __declspec(vaformat(printf,string_idx,first_to_check))
  885. #else
  886. #define JSON_HEDLEY_PRINTF_FORMAT(string_idx,first_to_check)
  887. #endif
  888. #if defined(JSON_HEDLEY_CONSTEXPR)
  889. #undef JSON_HEDLEY_CONSTEXPR
  890. #endif
  891. #if defined(__cplusplus)
  892. #if __cplusplus >= 201103L
  893. #define JSON_HEDLEY_CONSTEXPR constexpr
  894. #endif
  895. #endif
  896. #if !defined(JSON_HEDLEY_CONSTEXPR)
  897. #define JSON_HEDLEY_CONSTEXPR
  898. #endif
  899. #if defined(JSON_HEDLEY_PREDICT)
  900. #undef JSON_HEDLEY_PREDICT
  901. #endif
  902. #if defined(JSON_HEDLEY_LIKELY)
  903. #undef JSON_HEDLEY_LIKELY
  904. #endif
  905. #if defined(JSON_HEDLEY_UNLIKELY)
  906. #undef JSON_HEDLEY_UNLIKELY
  907. #endif
  908. #if defined(JSON_HEDLEY_UNPREDICTABLE)
  909. #undef JSON_HEDLEY_UNPREDICTABLE
  910. #endif
  911. #if JSON_HEDLEY_HAS_BUILTIN(__builtin_unpredictable)
  912. #define JSON_HEDLEY_UNPREDICTABLE(expr) __builtin_unpredictable(!!(expr))
  913. #endif
  914. #if \
  915. JSON_HEDLEY_HAS_BUILTIN(__builtin_expect_with_probability) || \
  916. JSON_HEDLEY_GCC_VERSION_CHECK(9,0,0)
  917. # define JSON_HEDLEY_PREDICT(expr, value, probability) __builtin_expect_with_probability(expr, value, probability)
  918. # define JSON_HEDLEY_PREDICT_TRUE(expr, probability) __builtin_expect_with_probability(!!(expr), 1, probability)
  919. # define JSON_HEDLEY_PREDICT_FALSE(expr, probability) __builtin_expect_with_probability(!!(expr), 0, probability)
  920. # define JSON_HEDLEY_LIKELY(expr) __builtin_expect(!!(expr), 1)
  921. # define JSON_HEDLEY_UNLIKELY(expr) __builtin_expect(!!(expr), 0)
  922. #if !defined(JSON_HEDLEY_BUILTIN_UNPREDICTABLE)
  923. #define JSON_HEDLEY_BUILTIN_UNPREDICTABLE(expr) __builtin_expect_with_probability(!!(expr), 1, 0.5)
  924. #endif
  925. #elif \
  926. JSON_HEDLEY_HAS_BUILTIN(__builtin_expect) || \
  927. JSON_HEDLEY_GCC_VERSION_CHECK(3,0,0) || \
  928. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
  929. (JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,15,0) && defined(__cplusplus)) || \
  930. JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \
  931. JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \
  932. JSON_HEDLEY_TI_VERSION_CHECK(6,1,0) || \
  933. JSON_HEDLEY_TINYC_VERSION_CHECK(0,9,27)
  934. # define JSON_HEDLEY_PREDICT(expr, expected, probability) \
  935. (((probability) >= 0.9) ? __builtin_expect(!!(expr), (expected)) : (((void) (expected)), !!(expr)))
  936. # define JSON_HEDLEY_PREDICT_TRUE(expr, probability) \
  937. (__extension__ ({ \
  938. JSON_HEDLEY_CONSTEXPR double hedley_probability_ = (probability); \
  939. ((hedley_probability_ >= 0.9) ? __builtin_expect(!!(expr), 1) : ((hedley_probability_ <= 0.1) ? __builtin_expect(!!(expr), 0) : !!(expr))); \
  940. }))
  941. # define JSON_HEDLEY_PREDICT_FALSE(expr, probability) \
  942. (__extension__ ({ \
  943. JSON_HEDLEY_CONSTEXPR double hedley_probability_ = (probability); \
  944. ((hedley_probability_ >= 0.9) ? __builtin_expect(!!(expr), 0) : ((hedley_probability_ <= 0.1) ? __builtin_expect(!!(expr), 1) : !!(expr))); \
  945. }))
  946. # define JSON_HEDLEY_LIKELY(expr) __builtin_expect(!!(expr), 1)
  947. # define JSON_HEDLEY_UNLIKELY(expr) __builtin_expect(!!(expr), 0)
  948. #else
  949. # define JSON_HEDLEY_PREDICT(expr, expected, probability) (((void) (expected)), !!(expr))
  950. # define JSON_HEDLEY_PREDICT_TRUE(expr, probability) (!!(expr))
  951. # define JSON_HEDLEY_PREDICT_FALSE(expr, probability) (!!(expr))
  952. # define JSON_HEDLEY_LIKELY(expr) (!!(expr))
  953. # define JSON_HEDLEY_UNLIKELY(expr) (!!(expr))
  954. #endif
  955. #if !defined(JSON_HEDLEY_UNPREDICTABLE)
  956. #define JSON_HEDLEY_UNPREDICTABLE(expr) JSON_HEDLEY_PREDICT(expr, 1, 0.5)
  957. #endif
  958. #if defined(JSON_HEDLEY_MALLOC)
  959. #undef JSON_HEDLEY_MALLOC
  960. #endif
  961. #if \
  962. JSON_HEDLEY_HAS_ATTRIBUTE(malloc) || \
  963. JSON_HEDLEY_GCC_VERSION_CHECK(3,1,0) || \
  964. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
  965. JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,11,0) || \
  966. JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \
  967. JSON_HEDLEY_IBM_VERSION_CHECK(12,1,0) || \
  968. JSON_HEDLEY_TI_VERSION_CHECK(8,0,0) || \
  969. (JSON_HEDLEY_TI_VERSION_CHECK(7,3,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__))
  970. #define JSON_HEDLEY_MALLOC __attribute__((__malloc__))
  971. #elif JSON_HEDLEY_MSVC_VERSION_CHECK(14, 0, 0)
  972. #define JSON_HEDLEY_MALLOC __declspec(restrict)
  973. #else
  974. #define JSON_HEDLEY_MALLOC
  975. #endif
  976. #if defined(JSON_HEDLEY_PURE)
  977. #undef JSON_HEDLEY_PURE
  978. #endif
  979. #if \
  980. JSON_HEDLEY_HAS_ATTRIBUTE(pure) || \
  981. JSON_HEDLEY_GCC_VERSION_CHECK(2,96,0) || \
  982. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
  983. JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,11,0) || \
  984. JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \
  985. JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \
  986. JSON_HEDLEY_TI_VERSION_CHECK(8,0,0) || \
  987. (JSON_HEDLEY_TI_VERSION_CHECK(7,3,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  988. JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0)
  989. #define JSON_HEDLEY_PURE __attribute__((__pure__))
  990. #elif JSON_HEDLEY_TI_VERSION_CHECK(6,0,0) && defined(__cplusplus)
  991. #define JSON_HEDLEY_PURE _Pragma("FUNC_IS_PURE;")
  992. #else
  993. #define JSON_HEDLEY_PURE
  994. #endif
  995. #if defined(JSON_HEDLEY_CONST)
  996. #undef JSON_HEDLEY_CONST
  997. #endif
  998. #if \
  999. JSON_HEDLEY_HAS_ATTRIBUTE(const) || \
  1000. JSON_HEDLEY_GCC_VERSION_CHECK(2,5,0) || \
  1001. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
  1002. JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,11,0) || \
  1003. JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \
  1004. JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \
  1005. JSON_HEDLEY_TI_VERSION_CHECK(8,0,0) || \
  1006. (JSON_HEDLEY_TI_VERSION_CHECK(7,3,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  1007. JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0)
  1008. #define JSON_HEDLEY_CONST __attribute__((__const__))
  1009. #else
  1010. #define JSON_HEDLEY_CONST JSON_HEDLEY_PURE
  1011. #endif
  1012. #if defined(JSON_HEDLEY_RESTRICT)
  1013. #undef JSON_HEDLEY_RESTRICT
  1014. #endif
  1015. #if defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) && !defined(__cplusplus)
  1016. #define JSON_HEDLEY_RESTRICT restrict
  1017. #elif \
  1018. JSON_HEDLEY_GCC_VERSION_CHECK(3,1,0) || \
  1019. JSON_HEDLEY_MSVC_VERSION_CHECK(14,0,0) || \
  1020. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
  1021. JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \
  1022. JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \
  1023. JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0) || \
  1024. JSON_HEDLEY_TI_VERSION_CHECK(8,0,0) || \
  1025. (JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,14,0) && defined(__cplusplus)) || \
  1026. JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0) || \
  1027. defined(__clang__)
  1028. #define JSON_HEDLEY_RESTRICT __restrict
  1029. #elif JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,3,0) && !defined(__cplusplus)
  1030. #define JSON_HEDLEY_RESTRICT _Restrict
  1031. #else
  1032. #define JSON_HEDLEY_RESTRICT
  1033. #endif
  1034. #if defined(JSON_HEDLEY_INLINE)
  1035. #undef JSON_HEDLEY_INLINE
  1036. #endif
  1037. #if \
  1038. (defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L)) || \
  1039. (defined(__cplusplus) && (__cplusplus >= 199711L))
  1040. #define JSON_HEDLEY_INLINE inline
  1041. #elif \
  1042. defined(JSON_HEDLEY_GCC_VERSION) || \
  1043. JSON_HEDLEY_ARM_VERSION_CHECK(6,2,0)
  1044. #define JSON_HEDLEY_INLINE __inline__
  1045. #elif \
  1046. JSON_HEDLEY_MSVC_VERSION_CHECK(12,0,0) || \
  1047. JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \
  1048. JSON_HEDLEY_TI_VERSION_CHECK(8,0,0)
  1049. #define JSON_HEDLEY_INLINE __inline
  1050. #else
  1051. #define JSON_HEDLEY_INLINE
  1052. #endif
  1053. #if defined(JSON_HEDLEY_ALWAYS_INLINE)
  1054. #undef JSON_HEDLEY_ALWAYS_INLINE
  1055. #endif
  1056. #if \
  1057. JSON_HEDLEY_HAS_ATTRIBUTE(always_inline) || \
  1058. JSON_HEDLEY_GCC_VERSION_CHECK(4,0,0) || \
  1059. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,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(8,0,0) || \
  1064. (JSON_HEDLEY_TI_VERSION_CHECK(7,3,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__))
  1065. #define JSON_HEDLEY_ALWAYS_INLINE __attribute__((__always_inline__)) JSON_HEDLEY_INLINE
  1066. #elif JSON_HEDLEY_MSVC_VERSION_CHECK(12,0,0)
  1067. #define JSON_HEDLEY_ALWAYS_INLINE __forceinline
  1068. #elif JSON_HEDLEY_TI_VERSION_CHECK(7,0,0) && defined(__cplusplus)
  1069. #define JSON_HEDLEY_ALWAYS_INLINE _Pragma("FUNC_ALWAYS_INLINE;")
  1070. #elif JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0)
  1071. #define JSON_HEDLEY_ALWAYS_INLINE _Pragma("inline=forced")
  1072. #else
  1073. #define JSON_HEDLEY_ALWAYS_INLINE JSON_HEDLEY_INLINE
  1074. #endif
  1075. #if defined(JSON_HEDLEY_NEVER_INLINE)
  1076. #undef JSON_HEDLEY_NEVER_INLINE
  1077. #endif
  1078. #if \
  1079. JSON_HEDLEY_HAS_ATTRIBUTE(noinline) || \
  1080. JSON_HEDLEY_GCC_VERSION_CHECK(4,0,0) || \
  1081. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
  1082. JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,11,0) || \
  1083. JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \
  1084. JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \
  1085. JSON_HEDLEY_TI_VERSION_CHECK(8,0,0) || \
  1086. (JSON_HEDLEY_TI_VERSION_CHECK(7,3,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__))
  1087. #define JSON_HEDLEY_NEVER_INLINE __attribute__((__noinline__))
  1088. #elif JSON_HEDLEY_MSVC_VERSION_CHECK(13,10,0)
  1089. #define JSON_HEDLEY_NEVER_INLINE __declspec(noinline)
  1090. #elif JSON_HEDLEY_PGI_VERSION_CHECK(10,2,0)
  1091. #define JSON_HEDLEY_NEVER_INLINE _Pragma("noinline")
  1092. #elif JSON_HEDLEY_TI_VERSION_CHECK(6,0,0) && defined(__cplusplus)
  1093. #define JSON_HEDLEY_NEVER_INLINE _Pragma("FUNC_CANNOT_INLINE;")
  1094. #elif JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0)
  1095. #define JSON_HEDLEY_NEVER_INLINE _Pragma("inline=never")
  1096. #elif JSON_HEDLEY_COMPCERT_VERSION_CHECK(3,2,0)
  1097. #define JSON_HEDLEY_NEVER_INLINE __attribute((noinline))
  1098. #elif JSON_HEDLEY_PELLES_VERSION_CHECK(9,0,0)
  1099. #define JSON_HEDLEY_NEVER_INLINE __declspec(noinline)
  1100. #else
  1101. #define JSON_HEDLEY_NEVER_INLINE
  1102. #endif
  1103. #if defined(JSON_HEDLEY_PRIVATE)
  1104. #undef JSON_HEDLEY_PRIVATE
  1105. #endif
  1106. #if defined(JSON_HEDLEY_PUBLIC)
  1107. #undef JSON_HEDLEY_PUBLIC
  1108. #endif
  1109. #if defined(JSON_HEDLEY_IMPORT)
  1110. #undef JSON_HEDLEY_IMPORT
  1111. #endif
  1112. #if defined(_WIN32) || defined(__CYGWIN__)
  1113. #define JSON_HEDLEY_PRIVATE
  1114. #define JSON_HEDLEY_PUBLIC __declspec(dllexport)
  1115. #define JSON_HEDLEY_IMPORT __declspec(dllimport)
  1116. #else
  1117. #if \
  1118. JSON_HEDLEY_HAS_ATTRIBUTE(visibility) || \
  1119. JSON_HEDLEY_GCC_VERSION_CHECK(3,3,0) || \
  1120. JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,11,0) || \
  1121. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
  1122. JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \
  1123. JSON_HEDLEY_IBM_VERSION_CHECK(13,1,0) || \
  1124. JSON_HEDLEY_TI_VERSION_CHECK(8,0,0) || \
  1125. (JSON_HEDLEY_TI_VERSION_CHECK(7,3,0) && defined(__TI_EABI__) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__))
  1126. #define JSON_HEDLEY_PRIVATE __attribute__((__visibility__("hidden")))
  1127. #define JSON_HEDLEY_PUBLIC __attribute__((__visibility__("default")))
  1128. #else
  1129. #define JSON_HEDLEY_PRIVATE
  1130. #define JSON_HEDLEY_PUBLIC
  1131. #endif
  1132. #define JSON_HEDLEY_IMPORT extern
  1133. #endif
  1134. #if defined(JSON_HEDLEY_NO_THROW)
  1135. #undef JSON_HEDLEY_NO_THROW
  1136. #endif
  1137. #if \
  1138. JSON_HEDLEY_HAS_ATTRIBUTE(nothrow) || \
  1139. JSON_HEDLEY_GCC_VERSION_CHECK(3,3,0) || \
  1140. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0)
  1141. #define JSON_HEDLEY_NO_THROW __attribute__((__nothrow__))
  1142. #elif \
  1143. JSON_HEDLEY_MSVC_VERSION_CHECK(13,1,0) || \
  1144. JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0)
  1145. #define JSON_HEDLEY_NO_THROW __declspec(nothrow)
  1146. #else
  1147. #define JSON_HEDLEY_NO_THROW
  1148. #endif
  1149. #if defined(JSON_HEDLEY_FALL_THROUGH)
  1150. #undef JSON_HEDLEY_FALL_THROUGH
  1151. #endif
  1152. #if \
  1153. defined(__cplusplus) && \
  1154. (!defined(JSON_HEDLEY_SUNPRO_VERSION) || JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,15,0)) && \
  1155. !defined(JSON_HEDLEY_PGI_VERSION)
  1156. #if \
  1157. (__cplusplus >= 201703L) || \
  1158. ((__cplusplus >= 201103L) && JSON_HEDLEY_HAS_CPP_ATTRIBUTE(fallthrough))
  1159. #define JSON_HEDLEY_FALL_THROUGH [[fallthrough]]
  1160. #elif (__cplusplus >= 201103L) && JSON_HEDLEY_HAS_CPP_ATTRIBUTE(clang::fallthrough)
  1161. #define JSON_HEDLEY_FALL_THROUGH [[clang::fallthrough]]
  1162. #elif (__cplusplus >= 201103L) && JSON_HEDLEY_GCC_VERSION_CHECK(7,0,0)
  1163. #define JSON_HEDLEY_FALL_THROUGH [[gnu::fallthrough]]
  1164. #endif
  1165. #endif
  1166. #if !defined(JSON_HEDLEY_FALL_THROUGH)
  1167. #if JSON_HEDLEY_GNUC_HAS_ATTRIBUTE(fallthrough,7,0,0) && !defined(JSON_HEDLEY_PGI_VERSION)
  1168. #define JSON_HEDLEY_FALL_THROUGH __attribute__((__fallthrough__))
  1169. #elif defined(__fallthrough) /* SAL */
  1170. #define JSON_HEDLEY_FALL_THROUGH __fallthrough
  1171. #else
  1172. #define JSON_HEDLEY_FALL_THROUGH
  1173. #endif
  1174. #endif
  1175. #if defined(JSON_HEDLEY_RETURNS_NON_NULL)
  1176. #undef JSON_HEDLEY_RETURNS_NON_NULL
  1177. #endif
  1178. #if \
  1179. JSON_HEDLEY_HAS_ATTRIBUTE(returns_nonnull) || \
  1180. JSON_HEDLEY_GCC_VERSION_CHECK(4,9,0)
  1181. #define JSON_HEDLEY_RETURNS_NON_NULL __attribute__((__returns_nonnull__))
  1182. #elif defined(_Ret_notnull_) /* SAL */
  1183. #define JSON_HEDLEY_RETURNS_NON_NULL _Ret_notnull_
  1184. #else
  1185. #define JSON_HEDLEY_RETURNS_NON_NULL
  1186. #endif
  1187. #if defined(JSON_HEDLEY_ARRAY_PARAM)
  1188. #undef JSON_HEDLEY_ARRAY_PARAM
  1189. #endif
  1190. #if \
  1191. defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) && \
  1192. !defined(__STDC_NO_VLA__) && \
  1193. !defined(__cplusplus) && \
  1194. !defined(JSON_HEDLEY_PGI_VERSION) && \
  1195. !defined(JSON_HEDLEY_TINYC_VERSION)
  1196. #define JSON_HEDLEY_ARRAY_PARAM(name) (name)
  1197. #else
  1198. #define JSON_HEDLEY_ARRAY_PARAM(name)
  1199. #endif
  1200. #if defined(JSON_HEDLEY_IS_CONSTANT)
  1201. #undef JSON_HEDLEY_IS_CONSTANT
  1202. #endif
  1203. #if defined(JSON_HEDLEY_REQUIRE_CONSTEXPR)
  1204. #undef JSON_HEDLEY_REQUIRE_CONSTEXPR
  1205. #endif
  1206. /* Note the double-underscore. For internal use only; no API
  1207. * guarantees! */
  1208. #if defined(JSON_HEDLEY__IS_CONSTEXPR)
  1209. #undef JSON_HEDLEY__IS_CONSTEXPR
  1210. #endif
  1211. #if \
  1212. JSON_HEDLEY_HAS_BUILTIN(__builtin_constant_p) || \
  1213. JSON_HEDLEY_GCC_VERSION_CHECK(3,4,0) || \
  1214. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
  1215. JSON_HEDLEY_TINYC_VERSION_CHECK(0,9,19) || \
  1216. JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \
  1217. JSON_HEDLEY_IBM_VERSION_CHECK(13,1,0) || \
  1218. JSON_HEDLEY_TI_VERSION_CHECK(6,1,0) || \
  1219. JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,10,0) || \
  1220. JSON_HEDLEY_CRAY_VERSION_CHECK(8,1,0)
  1221. #define JSON_HEDLEY_IS_CONSTANT(expr) __builtin_constant_p(expr)
  1222. #endif
  1223. #if !defined(__cplusplus)
  1224. # if \
  1225. JSON_HEDLEY_HAS_BUILTIN(__builtin_types_compatible_p) || \
  1226. JSON_HEDLEY_GCC_VERSION_CHECK(3,4,0) || \
  1227. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
  1228. JSON_HEDLEY_IBM_VERSION_CHECK(13,1,0) || \
  1229. JSON_HEDLEY_CRAY_VERSION_CHECK(8,1,0) || \
  1230. JSON_HEDLEY_ARM_VERSION_CHECK(5,4,0) || \
  1231. JSON_HEDLEY_TINYC_VERSION_CHECK(0,9,24)
  1232. #if defined(__INTPTR_TYPE__)
  1233. #define JSON_HEDLEY__IS_CONSTEXPR(expr) __builtin_types_compatible_p(__typeof__((1 ? (void*) ((__INTPTR_TYPE__) ((expr) * 0)) : (int*) 0)), int*)
  1234. #else
  1235. #include <stdint.h>
  1236. #define JSON_HEDLEY__IS_CONSTEXPR(expr) __builtin_types_compatible_p(__typeof__((1 ? (void*) ((intptr_t) ((expr) * 0)) : (int*) 0)), int*)
  1237. #endif
  1238. # elif \
  1239. (defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 201112L) && !defined(JSON_HEDLEY_SUNPRO_VERSION) && !defined(JSON_HEDLEY_PGI_VERSION)) || \
  1240. JSON_HEDLEY_HAS_EXTENSION(c_generic_selections) || \
  1241. JSON_HEDLEY_GCC_VERSION_CHECK(4,9,0) || \
  1242. JSON_HEDLEY_INTEL_VERSION_CHECK(17,0,0) || \
  1243. JSON_HEDLEY_IBM_VERSION_CHECK(12,1,0) || \
  1244. JSON_HEDLEY_ARM_VERSION_CHECK(5,3,0)
  1245. #if defined(__INTPTR_TYPE__)
  1246. #define JSON_HEDLEY__IS_CONSTEXPR(expr) _Generic((1 ? (void*) ((__INTPTR_TYPE__) ((expr) * 0)) : (int*) 0), int*: 1, void*: 0)
  1247. #else
  1248. #include <stdint.h>
  1249. #define JSON_HEDLEY__IS_CONSTEXPR(expr) _Generic((1 ? (void*) ((intptr_t) * 0) : (int*) 0), int*: 1, void*: 0)
  1250. #endif
  1251. # elif \
  1252. defined(JSON_HEDLEY_GCC_VERSION) || \
  1253. defined(JSON_HEDLEY_INTEL_VERSION) || \
  1254. defined(JSON_HEDLEY_TINYC_VERSION) || \
  1255. defined(JSON_HEDLEY_TI_VERSION) || \
  1256. defined(__clang__)
  1257. # define JSON_HEDLEY__IS_CONSTEXPR(expr) ( \
  1258. sizeof(void) != \
  1259. sizeof(*( \
  1260. 1 ? \
  1261. ((void*) ((expr) * 0L) ) : \
  1262. ((struct { char v[sizeof(void) * 2]; } *) 1) \
  1263. ) \
  1264. ) \
  1265. )
  1266. # endif
  1267. #endif
  1268. #if defined(JSON_HEDLEY__IS_CONSTEXPR)
  1269. #if !defined(JSON_HEDLEY_IS_CONSTANT)
  1270. #define JSON_HEDLEY_IS_CONSTANT(expr) JSON_HEDLEY__IS_CONSTEXPR(expr)
  1271. #endif
  1272. #define JSON_HEDLEY_REQUIRE_CONSTEXPR(expr) (JSON_HEDLEY__IS_CONSTEXPR(expr) ? (expr) : (-1))
  1273. #else
  1274. #if !defined(JSON_HEDLEY_IS_CONSTANT)
  1275. #define JSON_HEDLEY_IS_CONSTANT(expr) (0)
  1276. #endif
  1277. #define JSON_HEDLEY_REQUIRE_CONSTEXPR(expr) (expr)
  1278. #endif
  1279. #if defined(JSON_HEDLEY_BEGIN_C_DECLS)
  1280. #undef JSON_HEDLEY_BEGIN_C_DECLS
  1281. #endif
  1282. #if defined(JSON_HEDLEY_END_C_DECLS)
  1283. #undef JSON_HEDLEY_END_C_DECLS
  1284. #endif
  1285. #if defined(JSON_HEDLEY_C_DECL)
  1286. #undef JSON_HEDLEY_C_DECL
  1287. #endif
  1288. #if defined(__cplusplus)
  1289. #define JSON_HEDLEY_BEGIN_C_DECLS extern "C" {
  1290. #define JSON_HEDLEY_END_C_DECLS }
  1291. #define JSON_HEDLEY_C_DECL extern "C"
  1292. #else
  1293. #define JSON_HEDLEY_BEGIN_C_DECLS
  1294. #define JSON_HEDLEY_END_C_DECLS
  1295. #define JSON_HEDLEY_C_DECL
  1296. #endif
  1297. #if defined(JSON_HEDLEY_STATIC_ASSERT)
  1298. #undef JSON_HEDLEY_STATIC_ASSERT
  1299. #endif
  1300. #if \
  1301. !defined(__cplusplus) && ( \
  1302. (defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 201112L)) || \
  1303. JSON_HEDLEY_HAS_FEATURE(c_static_assert) || \
  1304. JSON_HEDLEY_GCC_VERSION_CHECK(6,0,0) || \
  1305. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
  1306. defined(_Static_assert) \
  1307. )
  1308. # define JSON_HEDLEY_STATIC_ASSERT(expr, message) _Static_assert(expr, message)
  1309. #elif \
  1310. (defined(__cplusplus) && (__cplusplus >= 201703L)) || \
  1311. JSON_HEDLEY_MSVC_VERSION_CHECK(16,0,0) || \
  1312. (defined(__cplusplus) && JSON_HEDLEY_TI_VERSION_CHECK(8,3,0))
  1313. # define JSON_HEDLEY_STATIC_ASSERT(expr, message) static_assert(expr, message)
  1314. #elif defined(__cplusplus) && (__cplusplus >= 201103L)
  1315. # define JSON_HEDLEY_STATIC_ASSERT(expr, message) static_assert(expr)
  1316. #else
  1317. # define JSON_HEDLEY_STATIC_ASSERT(expr, message)
  1318. #endif
  1319. #if defined(JSON_HEDLEY_CONST_CAST)
  1320. #undef JSON_HEDLEY_CONST_CAST
  1321. #endif
  1322. #if defined(__cplusplus)
  1323. # define JSON_HEDLEY_CONST_CAST(T, expr) (const_cast<T>(expr))
  1324. #elif \
  1325. JSON_HEDLEY_HAS_WARNING("-Wcast-qual") || \
  1326. JSON_HEDLEY_GCC_VERSION_CHECK(4,6,0) || \
  1327. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0)
  1328. # define JSON_HEDLEY_CONST_CAST(T, expr) (__extension__ ({ \
  1329. JSON_HEDLEY_DIAGNOSTIC_PUSH \
  1330. JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL \
  1331. ((T) (expr)); \
  1332. JSON_HEDLEY_DIAGNOSTIC_POP \
  1333. }))
  1334. #else
  1335. # define JSON_HEDLEY_CONST_CAST(T, expr) ((T) (expr))
  1336. #endif
  1337. #if defined(JSON_HEDLEY_REINTERPRET_CAST)
  1338. #undef JSON_HEDLEY_REINTERPRET_CAST
  1339. #endif
  1340. #if defined(__cplusplus)
  1341. #define JSON_HEDLEY_REINTERPRET_CAST(T, expr) (reinterpret_cast<T>(expr))
  1342. #else
  1343. #define JSON_HEDLEY_REINTERPRET_CAST(T, expr) (*((T*) &(expr)))
  1344. #endif
  1345. #if defined(JSON_HEDLEY_STATIC_CAST)
  1346. #undef JSON_HEDLEY_STATIC_CAST
  1347. #endif
  1348. #if defined(__cplusplus)
  1349. #define JSON_HEDLEY_STATIC_CAST(T, expr) (static_cast<T>(expr))
  1350. #else
  1351. #define JSON_HEDLEY_STATIC_CAST(T, expr) ((T) (expr))
  1352. #endif
  1353. #if defined(JSON_HEDLEY_CPP_CAST)
  1354. #undef JSON_HEDLEY_CPP_CAST
  1355. #endif
  1356. #if defined(__cplusplus)
  1357. #define JSON_HEDLEY_CPP_CAST(T, expr) static_cast<T>(expr)
  1358. #else
  1359. #define JSON_HEDLEY_CPP_CAST(T, expr) (expr)
  1360. #endif
  1361. #if defined(JSON_HEDLEY_MESSAGE)
  1362. #undef JSON_HEDLEY_MESSAGE
  1363. #endif
  1364. #if JSON_HEDLEY_HAS_WARNING("-Wunknown-pragmas")
  1365. # define JSON_HEDLEY_MESSAGE(msg) \
  1366. JSON_HEDLEY_DIAGNOSTIC_PUSH \
  1367. JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS \
  1368. JSON_HEDLEY_PRAGMA(message msg) \
  1369. JSON_HEDLEY_DIAGNOSTIC_POP
  1370. #elif \
  1371. JSON_HEDLEY_GCC_VERSION_CHECK(4,4,0) || \
  1372. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0)
  1373. # define JSON_HEDLEY_MESSAGE(msg) JSON_HEDLEY_PRAGMA(message msg)
  1374. #elif JSON_HEDLEY_CRAY_VERSION_CHECK(5,0,0)
  1375. # define JSON_HEDLEY_MESSAGE(msg) JSON_HEDLEY_PRAGMA(_CRI message msg)
  1376. #elif JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0)
  1377. # define JSON_HEDLEY_MESSAGE(msg) JSON_HEDLEY_PRAGMA(message(msg))
  1378. #elif JSON_HEDLEY_PELLES_VERSION_CHECK(2,0,0)
  1379. # define JSON_HEDLEY_MESSAGE(msg) JSON_HEDLEY_PRAGMA(message(msg))
  1380. #else
  1381. # define JSON_HEDLEY_MESSAGE(msg)
  1382. #endif
  1383. #if defined(JSON_HEDLEY_WARNING)
  1384. #undef JSON_HEDLEY_WARNING
  1385. #endif
  1386. #if JSON_HEDLEY_HAS_WARNING("-Wunknown-pragmas")
  1387. # define JSON_HEDLEY_WARNING(msg) \
  1388. JSON_HEDLEY_DIAGNOSTIC_PUSH \
  1389. JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS \
  1390. JSON_HEDLEY_PRAGMA(clang warning msg) \
  1391. JSON_HEDLEY_DIAGNOSTIC_POP
  1392. #elif \
  1393. JSON_HEDLEY_GCC_VERSION_CHECK(4,8,0) || \
  1394. JSON_HEDLEY_PGI_VERSION_CHECK(18,4,0)
  1395. # define JSON_HEDLEY_WARNING(msg) JSON_HEDLEY_PRAGMA(GCC warning msg)
  1396. #elif JSON_HEDLEY_MSVC_VERSION_CHECK(15,0,0)
  1397. # define JSON_HEDLEY_WARNING(msg) JSON_HEDLEY_PRAGMA(message(msg))
  1398. #else
  1399. # define JSON_HEDLEY_WARNING(msg) JSON_HEDLEY_MESSAGE(msg)
  1400. #endif
  1401. #if defined(JSON_HEDLEY_REQUIRE_MSG)
  1402. #undef JSON_HEDLEY_REQUIRE_MSG
  1403. #endif
  1404. #if JSON_HEDLEY_HAS_ATTRIBUTE(diagnose_if)
  1405. # if JSON_HEDLEY_HAS_WARNING("-Wgcc-compat")
  1406. # define JSON_HEDLEY_REQUIRE_MSG(expr, msg) \
  1407. JSON_HEDLEY_DIAGNOSTIC_PUSH \
  1408. _Pragma("clang diagnostic ignored \"-Wgcc-compat\"") \
  1409. __attribute__((__diagnose_if__(!(expr), msg, "error"))) \
  1410. JSON_HEDLEY_DIAGNOSTIC_POP
  1411. # else
  1412. # define JSON_HEDLEY_REQUIRE_MSG(expr, msg) __attribute__((__diagnose_if__(!(expr), msg, "error")))
  1413. # endif
  1414. #else
  1415. # define JSON_HEDLEY_REQUIRE_MSG(expr, msg)
  1416. #endif
  1417. #if defined(JSON_HEDLEY_REQUIRE)
  1418. #undef JSON_HEDLEY_REQUIRE
  1419. #endif
  1420. #define JSON_HEDLEY_REQUIRE(expr) JSON_HEDLEY_REQUIRE_MSG(expr, #expr)
  1421. #if defined(JSON_HEDLEY_FLAGS)
  1422. #undef JSON_HEDLEY_FLAGS
  1423. #endif
  1424. #if JSON_HEDLEY_HAS_ATTRIBUTE(flag_enum)
  1425. #define JSON_HEDLEY_FLAGS __attribute__((__flag_enum__))
  1426. #endif
  1427. #if defined(JSON_HEDLEY_FLAGS_CAST)
  1428. #undef JSON_HEDLEY_FLAGS_CAST
  1429. #endif
  1430. #if JSON_HEDLEY_INTEL_VERSION_CHECK(19,0,0)
  1431. # define JSON_HEDLEY_FLAGS_CAST(T, expr) (__extension__ ({ \
  1432. JSON_HEDLEY_DIAGNOSTIC_PUSH \
  1433. _Pragma("warning(disable:188)") \
  1434. ((T) (expr)); \
  1435. JSON_HEDLEY_DIAGNOSTIC_POP \
  1436. }))
  1437. #else
  1438. # define JSON_HEDLEY_FLAGS_CAST(T, expr) JSON_HEDLEY_STATIC_CAST(T, expr)
  1439. #endif
  1440. /* Remaining macros are deprecated. */
  1441. #if defined(JSON_HEDLEY_GCC_NOT_CLANG_VERSION_CHECK)
  1442. #undef JSON_HEDLEY_GCC_NOT_CLANG_VERSION_CHECK
  1443. #endif
  1444. #if defined(__clang__)
  1445. #define JSON_HEDLEY_GCC_NOT_CLANG_VERSION_CHECK(major,minor,patch) (0)
  1446. #else
  1447. #define JSON_HEDLEY_GCC_NOT_CLANG_VERSION_CHECK(major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch)
  1448. #endif
  1449. #if defined(JSON_HEDLEY_CLANG_HAS_ATTRIBUTE)
  1450. #undef JSON_HEDLEY_CLANG_HAS_ATTRIBUTE
  1451. #endif
  1452. #define JSON_HEDLEY_CLANG_HAS_ATTRIBUTE(attribute) JSON_HEDLEY_HAS_ATTRIBUTE(attribute)
  1453. #if defined(JSON_HEDLEY_CLANG_HAS_CPP_ATTRIBUTE)
  1454. #undef JSON_HEDLEY_CLANG_HAS_CPP_ATTRIBUTE
  1455. #endif
  1456. #define JSON_HEDLEY_CLANG_HAS_CPP_ATTRIBUTE(attribute) JSON_HEDLEY_HAS_CPP_ATTRIBUTE(attribute)
  1457. #if defined(JSON_HEDLEY_CLANG_HAS_BUILTIN)
  1458. #undef JSON_HEDLEY_CLANG_HAS_BUILTIN
  1459. #endif
  1460. #define JSON_HEDLEY_CLANG_HAS_BUILTIN(builtin) JSON_HEDLEY_HAS_BUILTIN(builtin)
  1461. #if defined(JSON_HEDLEY_CLANG_HAS_FEATURE)
  1462. #undef JSON_HEDLEY_CLANG_HAS_FEATURE
  1463. #endif
  1464. #define JSON_HEDLEY_CLANG_HAS_FEATURE(feature) JSON_HEDLEY_HAS_FEATURE(feature)
  1465. #if defined(JSON_HEDLEY_CLANG_HAS_EXTENSION)
  1466. #undef JSON_HEDLEY_CLANG_HAS_EXTENSION
  1467. #endif
  1468. #define JSON_HEDLEY_CLANG_HAS_EXTENSION(extension) JSON_HEDLEY_HAS_EXTENSION(extension)
  1469. #if defined(JSON_HEDLEY_CLANG_HAS_DECLSPEC_DECLSPEC_ATTRIBUTE)
  1470. #undef JSON_HEDLEY_CLANG_HAS_DECLSPEC_DECLSPEC_ATTRIBUTE
  1471. #endif
  1472. #define JSON_HEDLEY_CLANG_HAS_DECLSPEC_ATTRIBUTE(attribute) JSON_HEDLEY_HAS_DECLSPEC_ATTRIBUTE(attribute)
  1473. #if defined(JSON_HEDLEY_CLANG_HAS_WARNING)
  1474. #undef JSON_HEDLEY_CLANG_HAS_WARNING
  1475. #endif
  1476. #define JSON_HEDLEY_CLANG_HAS_WARNING(warning) JSON_HEDLEY_HAS_WARNING(warning)
  1477. #endif /* !defined(JSON_HEDLEY_VERSION) || (JSON_HEDLEY_VERSION < X) */
  1478. // This file contains all internal macro definitions
  1479. // You MUST include macro_unscope.hpp at the end of json.hpp to undef all of them
  1480. // exclude unsupported compilers
  1481. #if !defined(JSON_SKIP_UNSUPPORTED_COMPILER_CHECK)
  1482. #if defined(__clang__)
  1483. #if (__clang_major__ * 10000 + __clang_minor__ * 100 + __clang_patchlevel__) < 30400
  1484. #error "unsupported Clang version - see https://github.com/nlohmann/json#supported-compilers"
  1485. #endif
  1486. #elif defined(__GNUC__) && !(defined(__ICC) || defined(__INTEL_COMPILER))
  1487. #if (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__) < 40800
  1488. #error "unsupported GCC version - see https://github.com/nlohmann/json#supported-compilers"
  1489. #endif
  1490. #endif
  1491. #endif
  1492. // C++ language standard detection
  1493. #if (defined(__cplusplus) && __cplusplus >= 201703L) || (defined(_HAS_CXX17) && _HAS_CXX17 == 1) // fix for issue #464
  1494. #define JSON_HAS_CPP_17
  1495. #define JSON_HAS_CPP_14
  1496. #elif (defined(__cplusplus) && __cplusplus >= 201402L) || (defined(_HAS_CXX14) && _HAS_CXX14 == 1)
  1497. #define JSON_HAS_CPP_14
  1498. #endif
  1499. // disable float-equal warnings on GCC/clang
  1500. #if defined(__clang__) || defined(__GNUC__) || defined(__GNUG__)
  1501. #pragma GCC diagnostic push
  1502. #pragma GCC diagnostic ignored "-Wfloat-equal"
  1503. #endif
  1504. // disable documentation warnings on clang
  1505. #if defined(__clang__)
  1506. #pragma GCC diagnostic push
  1507. #pragma GCC diagnostic ignored "-Wdocumentation"
  1508. #endif
  1509. // allow to disable exceptions
  1510. #if (defined(__cpp_exceptions) || defined(__EXCEPTIONS) || defined(_CPPUNWIND)) && !defined(JSON_NOEXCEPTION)
  1511. #define JSON_THROW(exception) throw exception
  1512. #define JSON_TRY try
  1513. #define JSON_CATCH(exception) catch(exception)
  1514. #define JSON_INTERNAL_CATCH(exception) catch(exception)
  1515. #else
  1516. #include <cstdlib>
  1517. #define JSON_THROW(exception) std::abort()
  1518. #define JSON_TRY if(true)
  1519. #define JSON_CATCH(exception) if(false)
  1520. #define JSON_INTERNAL_CATCH(exception) if(false)
  1521. #endif
  1522. // override exception macros
  1523. #if defined(JSON_THROW_USER)
  1524. #undef JSON_THROW
  1525. #define JSON_THROW JSON_THROW_USER
  1526. #endif
  1527. #if defined(JSON_TRY_USER)
  1528. #undef JSON_TRY
  1529. #define JSON_TRY JSON_TRY_USER
  1530. #endif
  1531. #if defined(JSON_CATCH_USER)
  1532. #undef JSON_CATCH
  1533. #define JSON_CATCH JSON_CATCH_USER
  1534. #undef JSON_INTERNAL_CATCH
  1535. #define JSON_INTERNAL_CATCH JSON_CATCH_USER
  1536. #endif
  1537. #if defined(JSON_INTERNAL_CATCH_USER)
  1538. #undef JSON_INTERNAL_CATCH
  1539. #define JSON_INTERNAL_CATCH JSON_INTERNAL_CATCH_USER
  1540. #endif
  1541. /*!
  1542. @brief macro to briefly define a mapping between an enum and JSON
  1543. @def NLOHMANN_JSON_SERIALIZE_ENUM
  1544. @since version 3.4.0
  1545. */
  1546. #define NLOHMANN_JSON_SERIALIZE_ENUM(ENUM_TYPE, ...) \
  1547. template<typename BasicJsonType> \
  1548. inline void to_json(BasicJsonType& j, const ENUM_TYPE& e) \
  1549. { \
  1550. static_assert(std::is_enum<ENUM_TYPE>::value, #ENUM_TYPE " must be an enum!"); \
  1551. static const std::pair<ENUM_TYPE, BasicJsonType> m[] = __VA_ARGS__; \
  1552. auto it = std::find_if(std::begin(m), std::end(m), \
  1553. [e](const std::pair<ENUM_TYPE, BasicJsonType>& ej_pair) -> bool \
  1554. { \
  1555. return ej_pair.first == e; \
  1556. }); \
  1557. j = ((it != std::end(m)) ? it : std::begin(m))->second; \
  1558. } \
  1559. template<typename BasicJsonType> \
  1560. inline void from_json(const BasicJsonType& j, ENUM_TYPE& e) \
  1561. { \
  1562. static_assert(std::is_enum<ENUM_TYPE>::value, #ENUM_TYPE " must be an enum!"); \
  1563. static const std::pair<ENUM_TYPE, BasicJsonType> m[] = __VA_ARGS__; \
  1564. auto it = std::find_if(std::begin(m), std::end(m), \
  1565. [j](const std::pair<ENUM_TYPE, BasicJsonType>& ej_pair) -> bool \
  1566. { \
  1567. return ej_pair.second == j; \
  1568. }); \
  1569. e = ((it != std::end(m)) ? it : std::begin(m))->first; \
  1570. }
  1571. // Ugly macros to avoid uglier copy-paste when specializing basic_json. They
  1572. // may be removed in the future once the class is split.
  1573. #define NLOHMANN_BASIC_JSON_TPL_DECLARATION \
  1574. template<template<typename, typename, typename...> class ObjectType, \
  1575. template<typename, typename...> class ArrayType, \
  1576. class StringType, class BooleanType, class NumberIntegerType, \
  1577. class NumberUnsignedType, class NumberFloatType, \
  1578. template<typename> class AllocatorType, \
  1579. template<typename, typename = void> class JSONSerializer>
  1580. #define NLOHMANN_BASIC_JSON_TPL \
  1581. basic_json<ObjectType, ArrayType, StringType, BooleanType, \
  1582. NumberIntegerType, NumberUnsignedType, NumberFloatType, \
  1583. AllocatorType, JSONSerializer>
  1584. namespace nlohmann
  1585. {
  1586. namespace detail
  1587. {
  1588. ////////////////
  1589. // exceptions //
  1590. ////////////////
  1591. /*!
  1592. @brief general exception of the @ref basic_json class
  1593. This class is an extension of `std::exception` objects with a member @a id for
  1594. exception ids. It is used as the base class for all exceptions thrown by the
  1595. @ref basic_json class. This class can hence be used as "wildcard" to catch
  1596. exceptions.
  1597. Subclasses:
  1598. - @ref parse_error for exceptions indicating a parse error
  1599. - @ref invalid_iterator for exceptions indicating errors with iterators
  1600. - @ref type_error for exceptions indicating executing a member function with
  1601. a wrong type
  1602. - @ref out_of_range for exceptions indicating access out of the defined range
  1603. - @ref other_error for exceptions indicating other library errors
  1604. @internal
  1605. @note To have nothrow-copy-constructible exceptions, we internally use
  1606. `std::runtime_error` which can cope with arbitrary-length error messages.
  1607. Intermediate strings are built with static functions and then passed to
  1608. the actual constructor.
  1609. @endinternal
  1610. @liveexample{The following code shows how arbitrary library exceptions can be
  1611. caught.,exception}
  1612. @since version 3.0.0
  1613. */
  1614. class exception : public std::exception
  1615. {
  1616. public:
  1617. /// returns the explanatory string
  1618. JSON_HEDLEY_RETURNS_NON_NULL
  1619. const char* what() const noexcept override
  1620. {
  1621. return m.what();
  1622. }
  1623. /// the id of the exception
  1624. const int id;
  1625. protected:
  1626. JSON_HEDLEY_NON_NULL(3)
  1627. exception(int id_, const char* what_arg) : id(id_), m(what_arg) {}
  1628. static std::string name(const std::string& ename, int id_)
  1629. {
  1630. return "[json.exception." + ename + "." + std::to_string(id_) + "] ";
  1631. }
  1632. private:
  1633. /// an exception object as storage for error messages
  1634. std::runtime_error m;
  1635. };
  1636. /*!
  1637. @brief exception indicating a parse error
  1638. This exception is thrown by the library when a parse error occurs. Parse errors
  1639. can occur during the deserialization of JSON text, CBOR, MessagePack, as well
  1640. as when using JSON Patch.
  1641. Member @a byte holds the byte index of the last read character in the input
  1642. file.
  1643. Exceptions have ids 1xx.
  1644. name / id | example message | description
  1645. ------------------------------ | --------------- | -------------------------
  1646. 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.
  1647. 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.
  1648. 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.
  1649. 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.
  1650. 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.
  1651. 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`.
  1652. 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.
  1653. 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.
  1654. json.exception.parse_error.109 | parse error: array index 'one' is not a number | A JSON Pointer array index must be a number.
  1655. 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.
  1656. 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.
  1657. 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.
  1658. json.exception.parse_error.114 | parse error: Unsupported BSON record type 0x0F | The parsing of the corresponding BSON record type is not implemented (yet).
  1659. @note For an input with n bytes, 1 is the index of the first character and n+1
  1660. is the index of the terminating null byte or the end of file. This also
  1661. holds true when reading a byte vector (CBOR or MessagePack).
  1662. @liveexample{The following code shows how a `parse_error` exception can be
  1663. caught.,parse_error}
  1664. @sa - @ref exception for the base class of the library exceptions
  1665. @sa - @ref invalid_iterator for exceptions indicating errors with iterators
  1666. @sa - @ref type_error for exceptions indicating executing a member function with
  1667. a wrong type
  1668. @sa - @ref out_of_range for exceptions indicating access out of the defined range
  1669. @sa - @ref other_error for exceptions indicating other library errors
  1670. @since version 3.0.0
  1671. */
  1672. class parse_error : public exception
  1673. {
  1674. public:
  1675. /*!
  1676. @brief create a parse error exception
  1677. @param[in] id_ the id of the exception
  1678. @param[in] pos the position where the error occurred (or with
  1679. chars_read_total=0 if the position cannot be
  1680. determined)
  1681. @param[in] what_arg the explanatory string
  1682. @return parse_error object
  1683. */
  1684. static parse_error create(int id_, const position_t& pos, const std::string& what_arg)
  1685. {
  1686. std::string w = exception::name("parse_error", id_) + "parse error" +
  1687. position_string(pos) + ": " + what_arg;
  1688. return parse_error(id_, pos.chars_read_total, w.c_str());
  1689. }
  1690. static parse_error create(int id_, std::size_t byte_, const std::string& what_arg)
  1691. {
  1692. std::string w = exception::name("parse_error", id_) + "parse error" +
  1693. (byte_ != 0 ? (" at byte " + std::to_string(byte_)) : "") +
  1694. ": " + what_arg;
  1695. return parse_error(id_, byte_, w.c_str());
  1696. }
  1697. /*!
  1698. @brief byte index of the parse error
  1699. The byte index of the last read character in the input file.
  1700. @note For an input with n bytes, 1 is the index of the first character and
  1701. n+1 is the index of the terminating null byte or the end of file.
  1702. This also holds true when reading a byte vector (CBOR or MessagePack).
  1703. */
  1704. const std::size_t byte;
  1705. private:
  1706. parse_error(int id_, std::size_t byte_, const char* what_arg)
  1707. : exception(id_, what_arg), byte(byte_) {}
  1708. static std::string position_string(const position_t& pos)
  1709. {
  1710. return " at line " + std::to_string(pos.lines_read + 1) +
  1711. ", column " + std::to_string(pos.chars_read_current_line);
  1712. }
  1713. };
  1714. /*!
  1715. @brief exception indicating errors with iterators
  1716. This exception is thrown if iterators passed to a library function do not match
  1717. the expected semantics.
  1718. Exceptions have ids 2xx.
  1719. name / id | example message | description
  1720. ----------------------------------- | --------------- | -------------------------
  1721. 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.
  1722. 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.
  1723. 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.
  1724. 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.
  1725. 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.
  1726. 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.
  1727. 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.
  1728. 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.
  1729. 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.
  1730. 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.
  1731. 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.
  1732. json.exception.invalid_iterator.212 | cannot compare iterators of different containers | When two iterators are compared, they must belong to the same container.
  1733. json.exception.invalid_iterator.213 | cannot compare order of object iterators | The order of object iterators cannot be compared, because JSON objects are unordered.
  1734. 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().
  1735. @liveexample{The following code shows how an `invalid_iterator` exception can be
  1736. caught.,invalid_iterator}
  1737. @sa - @ref exception for the base class of the library exceptions
  1738. @sa - @ref parse_error for exceptions indicating a parse error
  1739. @sa - @ref type_error for exceptions indicating executing a member function with
  1740. a wrong type
  1741. @sa - @ref out_of_range for exceptions indicating access out of the defined range
  1742. @sa - @ref other_error for exceptions indicating other library errors
  1743. @since version 3.0.0
  1744. */
  1745. class invalid_iterator : public exception
  1746. {
  1747. public:
  1748. static invalid_iterator create(int id_, const std::string& what_arg)
  1749. {
  1750. std::string w = exception::name("invalid_iterator", id_) + what_arg;
  1751. return invalid_iterator(id_, w.c_str());
  1752. }
  1753. private:
  1754. JSON_HEDLEY_NON_NULL(3)
  1755. invalid_iterator(int id_, const char* what_arg)
  1756. : exception(id_, what_arg) {}
  1757. };
  1758. /*!
  1759. @brief exception indicating executing a member function with a wrong type
  1760. This exception is thrown in case of a type error; that is, a library function is
  1761. executed on a JSON value whose type does not match the expected semantics.
  1762. Exceptions have ids 3xx.
  1763. name / id | example message | description
  1764. ----------------------------- | --------------- | -------------------------
  1765. 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.
  1766. 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.
  1767. 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 &.
  1768. json.exception.type_error.304 | cannot use at() with string | The @ref at() member functions can only be executed for certain JSON types.
  1769. json.exception.type_error.305 | cannot use operator[] with string | The @ref operator[] member functions can only be executed for certain JSON types.
  1770. json.exception.type_error.306 | cannot use value() with string | The @ref value() member functions can only be executed for certain JSON types.
  1771. json.exception.type_error.307 | cannot use erase() with string | The @ref erase() member functions can only be executed for certain JSON types.
  1772. 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.
  1773. json.exception.type_error.309 | cannot use insert() with | The @ref insert() member functions can only be executed for certain JSON types.
  1774. json.exception.type_error.310 | cannot use swap() with number | The @ref swap() member functions can only be executed for certain JSON types.
  1775. 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.
  1776. json.exception.type_error.312 | cannot use update() with string | The @ref update() member functions can only be executed for certain JSON types.
  1777. 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.
  1778. json.exception.type_error.314 | only objects can be unflattened | The @ref unflatten function only works for an object whose keys are JSON Pointers.
  1779. 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.
  1780. 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. |
  1781. 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) |
  1782. @liveexample{The following code shows how a `type_error` exception can be
  1783. caught.,type_error}
  1784. @sa - @ref exception for the base class of the library exceptions
  1785. @sa - @ref parse_error for exceptions indicating a parse error
  1786. @sa - @ref invalid_iterator for exceptions indicating errors with iterators
  1787. @sa - @ref out_of_range for exceptions indicating access out of the defined range
  1788. @sa - @ref other_error for exceptions indicating other library errors
  1789. @since version 3.0.0
  1790. */
  1791. class type_error : public exception
  1792. {
  1793. public:
  1794. static type_error create(int id_, const std::string& what_arg)
  1795. {
  1796. std::string w = exception::name("type_error", id_) + what_arg;
  1797. return type_error(id_, w.c_str());
  1798. }
  1799. private:
  1800. JSON_HEDLEY_NON_NULL(3)
  1801. type_error(int id_, const char* what_arg) : exception(id_, what_arg) {}
  1802. };
  1803. /*!
  1804. @brief exception indicating access out of the defined range
  1805. This exception is thrown in case a library function is called on an input
  1806. parameter that exceeds the expected range, for instance in case of array
  1807. indices or nonexisting object keys.
  1808. Exceptions have ids 4xx.
  1809. name / id | example message | description
  1810. ------------------------------- | --------------- | -------------------------
  1811. 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.
  1812. 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.
  1813. json.exception.out_of_range.403 | key 'foo' not found | The provided key was not found in the JSON object.
  1814. json.exception.out_of_range.404 | unresolved reference token 'foo' | A reference token in a JSON Pointer could not be resolved.
  1815. 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.
  1816. 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.
  1817. json.exception.out_of_range.407 | number overflow serializing '9223372036854775808' | UBJSON and BSON only support integer numbers up to 9223372036854775807. |
  1818. json.exception.out_of_range.408 | excessive array size: 8658170730974374167 | The size (following `#`) of an UBJSON array or object exceeds the maximal capacity. |
  1819. 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 |
  1820. @liveexample{The following code shows how an `out_of_range` exception can be
  1821. caught.,out_of_range}
  1822. @sa - @ref exception for the base class of the library exceptions
  1823. @sa - @ref parse_error for exceptions indicating a parse error
  1824. @sa - @ref invalid_iterator for exceptions indicating errors with iterators
  1825. @sa - @ref type_error for exceptions indicating executing a member function with
  1826. a wrong type
  1827. @sa - @ref other_error for exceptions indicating other library errors
  1828. @since version 3.0.0
  1829. */
  1830. class out_of_range : public exception
  1831. {
  1832. public:
  1833. static out_of_range create(int id_, const std::string& what_arg)
  1834. {
  1835. std::string w = exception::name("out_of_range", id_) + what_arg;
  1836. return out_of_range(id_, w.c_str());
  1837. }
  1838. private:
  1839. JSON_HEDLEY_NON_NULL(3)
  1840. out_of_range(int id_, const char* what_arg) : exception(id_, what_arg) {}
  1841. };
  1842. /*!
  1843. @brief exception indicating other library errors
  1844. This exception is thrown in case of errors that cannot be classified with the
  1845. other exception types.
  1846. Exceptions have ids 5xx.
  1847. name / id | example message | description
  1848. ------------------------------ | --------------- | -------------------------
  1849. json.exception.other_error.501 | unsuccessful: {"op":"test","path":"/baz", "value":"bar"} | A JSON Patch operation 'test' failed. The unsuccessful operation is also printed.
  1850. @sa - @ref exception for the base class of the library exceptions
  1851. @sa - @ref parse_error for exceptions indicating a parse error
  1852. @sa - @ref invalid_iterator for exceptions indicating errors with iterators
  1853. @sa - @ref type_error for exceptions indicating executing a member function with
  1854. a wrong type
  1855. @sa - @ref out_of_range for exceptions indicating access out of the defined range
  1856. @liveexample{The following code shows how an `other_error` exception can be
  1857. caught.,other_error}
  1858. @since version 3.0.0
  1859. */
  1860. class other_error : public exception
  1861. {
  1862. public:
  1863. static other_error create(int id_, const std::string& what_arg)
  1864. {
  1865. std::string w = exception::name("other_error", id_) + what_arg;
  1866. return other_error(id_, w.c_str());
  1867. }
  1868. private:
  1869. JSON_HEDLEY_NON_NULL(3)
  1870. other_error(int id_, const char* what_arg) : exception(id_, what_arg) {}
  1871. };
  1872. } // namespace detail
  1873. } // namespace nlohmann
  1874. // #include <nlohmann/detail/macro_scope.hpp>
  1875. // #include <nlohmann/detail/meta/cpp_future.hpp>
  1876. #include <ciso646> // not
  1877. #include <cstddef> // size_t
  1878. #include <type_traits> // conditional, enable_if, false_type, integral_constant, is_constructible, is_integral, is_same, remove_cv, remove_reference, true_type
  1879. namespace nlohmann
  1880. {
  1881. namespace detail
  1882. {
  1883. // alias templates to reduce boilerplate
  1884. template<bool B, typename T = void>
  1885. using enable_if_t = typename std::enable_if<B, T>::type;
  1886. template<typename T>
  1887. using uncvref_t = typename std::remove_cv<typename std::remove_reference<T>::type>::type;
  1888. // implementation of C++14 index_sequence and affiliates
  1889. // source: https://stackoverflow.com/a/32223343
  1890. template<std::size_t... Ints>
  1891. struct index_sequence
  1892. {
  1893. using type = index_sequence;
  1894. using value_type = std::size_t;
  1895. static constexpr std::size_t size() noexcept
  1896. {
  1897. return sizeof...(Ints);
  1898. }
  1899. };
  1900. template<class Sequence1, class Sequence2>
  1901. struct merge_and_renumber;
  1902. template<std::size_t... I1, std::size_t... I2>
  1903. struct merge_and_renumber<index_sequence<I1...>, index_sequence<I2...>>
  1904. : index_sequence < I1..., (sizeof...(I1) + I2)... > {};
  1905. template<std::size_t N>
  1906. struct make_index_sequence
  1907. : merge_and_renumber < typename make_index_sequence < N / 2 >::type,
  1908. typename make_index_sequence < N - N / 2 >::type > {};
  1909. template<> struct make_index_sequence<0> : index_sequence<> {};
  1910. template<> struct make_index_sequence<1> : index_sequence<0> {};
  1911. template<typename... Ts>
  1912. using index_sequence_for = make_index_sequence<sizeof...(Ts)>;
  1913. // dispatch utility (taken from ranges-v3)
  1914. template<unsigned N> struct priority_tag : priority_tag < N - 1 > {};
  1915. template<> struct priority_tag<0> {};
  1916. // taken from ranges-v3
  1917. template<typename T>
  1918. struct static_const
  1919. {
  1920. static constexpr T value{};
  1921. };
  1922. template<typename T>
  1923. constexpr T static_const<T>::value;
  1924. } // namespace detail
  1925. } // namespace nlohmann
  1926. // #include <nlohmann/detail/meta/type_traits.hpp>
  1927. #include <ciso646> // not
  1928. #include <limits> // numeric_limits
  1929. #include <type_traits> // false_type, is_constructible, is_integral, is_same, true_type
  1930. #include <utility> // declval
  1931. // #include <nlohmann/detail/iterators/iterator_traits.hpp>
  1932. #include <iterator> // random_access_iterator_tag
  1933. // #include <nlohmann/detail/meta/void_t.hpp>
  1934. namespace nlohmann
  1935. {
  1936. namespace detail
  1937. {
  1938. template <typename ...Ts> struct make_void
  1939. {
  1940. using type = void;
  1941. };
  1942. template <typename ...Ts> using void_t = typename make_void<Ts...>::type;
  1943. } // namespace detail
  1944. } // namespace nlohmann
  1945. // #include <nlohmann/detail/meta/cpp_future.hpp>
  1946. namespace nlohmann
  1947. {
  1948. namespace detail
  1949. {
  1950. template <typename It, typename = void>
  1951. struct iterator_types {};
  1952. template <typename It>
  1953. struct iterator_types <
  1954. It,
  1955. void_t<typename It::difference_type, typename It::value_type, typename It::pointer,
  1956. typename It::reference, typename It::iterator_category >>
  1957. {
  1958. using difference_type = typename It::difference_type;
  1959. using value_type = typename It::value_type;
  1960. using pointer = typename It::pointer;
  1961. using reference = typename It::reference;
  1962. using iterator_category = typename It::iterator_category;
  1963. };
  1964. // This is required as some compilers implement std::iterator_traits in a way that
  1965. // doesn't work with SFINAE. See https://github.com/nlohmann/json/issues/1341.
  1966. template <typename T, typename = void>
  1967. struct iterator_traits
  1968. {
  1969. };
  1970. template <typename T>
  1971. struct iterator_traits < T, enable_if_t < !std::is_pointer<T>::value >>
  1972. : iterator_types<T>
  1973. {
  1974. };
  1975. template <typename T>
  1976. struct iterator_traits<T*, enable_if_t<std::is_object<T>::value>>
  1977. {
  1978. using iterator_category = std::random_access_iterator_tag;
  1979. using value_type = T;
  1980. using difference_type = ptrdiff_t;
  1981. using pointer = T*;
  1982. using reference = T&;
  1983. };
  1984. } // namespace detail
  1985. } // namespace nlohmann
  1986. // #include <nlohmann/detail/macro_scope.hpp>
  1987. // #include <nlohmann/detail/meta/cpp_future.hpp>
  1988. // #include <nlohmann/detail/meta/detected.hpp>
  1989. #include <type_traits>
  1990. // #include <nlohmann/detail/meta/void_t.hpp>
  1991. // http://en.cppreference.com/w/cpp/experimental/is_detected
  1992. namespace nlohmann
  1993. {
  1994. namespace detail
  1995. {
  1996. struct nonesuch
  1997. {
  1998. nonesuch() = delete;
  1999. ~nonesuch() = delete;
  2000. nonesuch(nonesuch const&) = delete;
  2001. nonesuch(nonesuch const&&) = delete;
  2002. void operator=(nonesuch const&) = delete;
  2003. void operator=(nonesuch&&) = delete;
  2004. };
  2005. template <class Default,
  2006. class AlwaysVoid,
  2007. template <class...> class Op,
  2008. class... Args>
  2009. struct detector
  2010. {
  2011. using value_t = std::false_type;
  2012. using type = Default;
  2013. };
  2014. template <class Default, template <class...> class Op, class... Args>
  2015. struct detector<Default, void_t<Op<Args...>>, Op, Args...>
  2016. {
  2017. using value_t = std::true_type;
  2018. using type = Op<Args...>;
  2019. };
  2020. template <template <class...> class Op, class... Args>
  2021. using is_detected = typename detector<nonesuch, void, Op, Args...>::value_t;
  2022. template <template <class...> class Op, class... Args>
  2023. using detected_t = typename detector<nonesuch, void, Op, Args...>::type;
  2024. template <class Default, template <class...> class Op, class... Args>
  2025. using detected_or = detector<Default, void, Op, Args...>;
  2026. template <class Default, template <class...> class Op, class... Args>
  2027. using detected_or_t = typename detected_or<Default, Op, Args...>::type;
  2028. template <class Expected, template <class...> class Op, class... Args>
  2029. using is_detected_exact = std::is_same<Expected, detected_t<Op, Args...>>;
  2030. template <class To, template <class...> class Op, class... Args>
  2031. using is_detected_convertible =
  2032. std::is_convertible<detected_t<Op, Args...>, To>;
  2033. } // namespace detail
  2034. } // namespace nlohmann
  2035. // #include <nlohmann/json_fwd.hpp>
  2036. #ifndef INCLUDE_NLOHMANN_JSON_FWD_HPP_
  2037. #define INCLUDE_NLOHMANN_JSON_FWD_HPP_
  2038. #include <cstdint> // int64_t, uint64_t
  2039. #include <map> // map
  2040. #include <memory> // allocator
  2041. #include <string> // string
  2042. #include <vector> // vector
  2043. /*!
  2044. @brief namespace for Niels Lohmann
  2045. @see https://github.com/nlohmann
  2046. @since version 1.0.0
  2047. */
  2048. namespace nlohmann
  2049. {
  2050. /*!
  2051. @brief default JSONSerializer template argument
  2052. This serializer ignores the template arguments and uses ADL
  2053. ([argument-dependent lookup](https://en.cppreference.com/w/cpp/language/adl))
  2054. for serialization.
  2055. */
  2056. template<typename T = void, typename SFINAE = void>
  2057. struct adl_serializer;
  2058. template<template<typename U, typename V, typename... Args> class ObjectType =
  2059. std::map,
  2060. template<typename U, typename... Args> class ArrayType = std::vector,
  2061. class StringType = std::string, class BooleanType = bool,
  2062. class NumberIntegerType = std::int64_t,
  2063. class NumberUnsignedType = std::uint64_t,
  2064. class NumberFloatType = double,
  2065. template<typename U> class AllocatorType = std::allocator,
  2066. template<typename T, typename SFINAE = void> class JSONSerializer =
  2067. adl_serializer>
  2068. class basic_json;
  2069. /*!
  2070. @brief JSON Pointer
  2071. A JSON pointer defines a string syntax for identifying a specific value
  2072. within a JSON document. It can be used with functions `at` and
  2073. `operator[]`. Furthermore, JSON pointers are the base for JSON patches.
  2074. @sa [RFC 6901](https://tools.ietf.org/html/rfc6901)
  2075. @since version 2.0.0
  2076. */
  2077. template<typename BasicJsonType>
  2078. class json_pointer;
  2079. /*!
  2080. @brief default JSON class
  2081. This type is the default specialization of the @ref basic_json class which
  2082. uses the standard template types.
  2083. @since version 1.0.0
  2084. */
  2085. using json = basic_json<>;
  2086. } // namespace nlohmann
  2087. #endif // INCLUDE_NLOHMANN_JSON_FWD_HPP_
  2088. namespace nlohmann
  2089. {
  2090. /*!
  2091. @brief detail namespace with internal helper functions
  2092. This namespace collects functions that should not be exposed,
  2093. implementations of some @ref basic_json methods, and meta-programming helpers.
  2094. @since version 2.1.0
  2095. */
  2096. namespace detail
  2097. {
  2098. /////////////
  2099. // helpers //
  2100. /////////////
  2101. // Note to maintainers:
  2102. //
  2103. // Every trait in this file expects a non CV-qualified type.
  2104. // The only exceptions are in the 'aliases for detected' section
  2105. // (i.e. those of the form: decltype(T::member_function(std::declval<T>())))
  2106. //
  2107. // In this case, T has to be properly CV-qualified to constraint the function arguments
  2108. // (e.g. to_json(BasicJsonType&, const T&))
  2109. template<typename> struct is_basic_json : std::false_type {};
  2110. NLOHMANN_BASIC_JSON_TPL_DECLARATION
  2111. struct is_basic_json<NLOHMANN_BASIC_JSON_TPL> : std::true_type {};
  2112. //////////////////////////
  2113. // aliases for detected //
  2114. //////////////////////////
  2115. template <typename T>
  2116. using mapped_type_t = typename T::mapped_type;
  2117. template <typename T>
  2118. using key_type_t = typename T::key_type;
  2119. template <typename T>
  2120. using value_type_t = typename T::value_type;
  2121. template <typename T>
  2122. using difference_type_t = typename T::difference_type;
  2123. template <typename T>
  2124. using pointer_t = typename T::pointer;
  2125. template <typename T>
  2126. using reference_t = typename T::reference;
  2127. template <typename T>
  2128. using iterator_category_t = typename T::iterator_category;
  2129. template <typename T>
  2130. using iterator_t = typename T::iterator;
  2131. template <typename T, typename... Args>
  2132. using to_json_function = decltype(T::to_json(std::declval<Args>()...));
  2133. template <typename T, typename... Args>
  2134. using from_json_function = decltype(T::from_json(std::declval<Args>()...));
  2135. template <typename T, typename U>
  2136. using get_template_function = decltype(std::declval<T>().template get<U>());
  2137. // trait checking if JSONSerializer<T>::from_json(json const&, udt&) exists
  2138. template <typename BasicJsonType, typename T, typename = void>
  2139. struct has_from_json : std::false_type {};
  2140. template <typename BasicJsonType, typename T>
  2141. struct has_from_json<BasicJsonType, T,
  2142. enable_if_t<not is_basic_json<T>::value>>
  2143. {
  2144. using serializer = typename BasicJsonType::template json_serializer<T, void>;
  2145. static constexpr bool value =
  2146. is_detected_exact<void, from_json_function, serializer,
  2147. const BasicJsonType&, T&>::value;
  2148. };
  2149. // This trait checks if JSONSerializer<T>::from_json(json const&) exists
  2150. // this overload is used for non-default-constructible user-defined-types
  2151. template <typename BasicJsonType, typename T, typename = void>
  2152. struct has_non_default_from_json : std::false_type {};
  2153. template<typename BasicJsonType, typename T>
  2154. struct has_non_default_from_json<BasicJsonType, T, enable_if_t<not is_basic_json<T>::value>>
  2155. {
  2156. using serializer = typename BasicJsonType::template json_serializer<T, void>;
  2157. static constexpr bool value =
  2158. is_detected_exact<T, from_json_function, serializer,
  2159. const BasicJsonType&>::value;
  2160. };
  2161. // This trait checks if BasicJsonType::json_serializer<T>::to_json exists
  2162. // Do not evaluate the trait when T is a basic_json type, to avoid template instantiation infinite recursion.
  2163. template <typename BasicJsonType, typename T, typename = void>
  2164. struct has_to_json : std::false_type {};
  2165. template <typename BasicJsonType, typename T>
  2166. struct has_to_json<BasicJsonType, T, enable_if_t<not is_basic_json<T>::value>>
  2167. {
  2168. using serializer = typename BasicJsonType::template json_serializer<T, void>;
  2169. static constexpr bool value =
  2170. is_detected_exact<void, to_json_function, serializer, BasicJsonType&,
  2171. T>::value;
  2172. };
  2173. ///////////////////
  2174. // is_ functions //
  2175. ///////////////////
  2176. template <typename T, typename = void>
  2177. struct is_iterator_traits : std::false_type {};
  2178. template <typename T>
  2179. struct is_iterator_traits<iterator_traits<T>>
  2180. {
  2181. private:
  2182. using traits = iterator_traits<T>;
  2183. public:
  2184. static constexpr auto value =
  2185. is_detected<value_type_t, traits>::value &&
  2186. is_detected<difference_type_t, traits>::value &&
  2187. is_detected<pointer_t, traits>::value &&
  2188. is_detected<iterator_category_t, traits>::value &&
  2189. is_detected<reference_t, traits>::value;
  2190. };
  2191. // source: https://stackoverflow.com/a/37193089/4116453
  2192. template <typename T, typename = void>
  2193. struct is_complete_type : std::false_type {};
  2194. template <typename T>
  2195. struct is_complete_type<T, decltype(void(sizeof(T)))> : std::true_type {};
  2196. template <typename BasicJsonType, typename CompatibleObjectType,
  2197. typename = void>
  2198. struct is_compatible_object_type_impl : std::false_type {};
  2199. template <typename BasicJsonType, typename CompatibleObjectType>
  2200. struct is_compatible_object_type_impl <
  2201. BasicJsonType, CompatibleObjectType,
  2202. enable_if_t<is_detected<mapped_type_t, CompatibleObjectType>::value and
  2203. is_detected<key_type_t, CompatibleObjectType>::value >>
  2204. {
  2205. using object_t = typename BasicJsonType::object_t;
  2206. // macOS's is_constructible does not play well with nonesuch...
  2207. static constexpr bool value =
  2208. std::is_constructible<typename object_t::key_type,
  2209. typename CompatibleObjectType::key_type>::value and
  2210. std::is_constructible<typename object_t::mapped_type,
  2211. typename CompatibleObjectType::mapped_type>::value;
  2212. };
  2213. template <typename BasicJsonType, typename CompatibleObjectType>
  2214. struct is_compatible_object_type
  2215. : is_compatible_object_type_impl<BasicJsonType, CompatibleObjectType> {};
  2216. template <typename BasicJsonType, typename ConstructibleObjectType,
  2217. typename = void>
  2218. struct is_constructible_object_type_impl : std::false_type {};
  2219. template <typename BasicJsonType, typename ConstructibleObjectType>
  2220. struct is_constructible_object_type_impl <
  2221. BasicJsonType, ConstructibleObjectType,
  2222. enable_if_t<is_detected<mapped_type_t, ConstructibleObjectType>::value and
  2223. is_detected<key_type_t, ConstructibleObjectType>::value >>
  2224. {
  2225. using object_t = typename BasicJsonType::object_t;
  2226. static constexpr bool value =
  2227. (std::is_default_constructible<ConstructibleObjectType>::value and
  2228. (std::is_move_assignable<ConstructibleObjectType>::value or
  2229. std::is_copy_assignable<ConstructibleObjectType>::value) and
  2230. (std::is_constructible<typename ConstructibleObjectType::key_type,
  2231. typename object_t::key_type>::value and
  2232. std::is_same <
  2233. typename object_t::mapped_type,
  2234. typename ConstructibleObjectType::mapped_type >::value)) or
  2235. (has_from_json<BasicJsonType,
  2236. typename ConstructibleObjectType::mapped_type>::value or
  2237. has_non_default_from_json <
  2238. BasicJsonType,
  2239. typename ConstructibleObjectType::mapped_type >::value);
  2240. };
  2241. template <typename BasicJsonType, typename ConstructibleObjectType>
  2242. struct is_constructible_object_type
  2243. : is_constructible_object_type_impl<BasicJsonType,
  2244. ConstructibleObjectType> {};
  2245. template <typename BasicJsonType, typename CompatibleStringType,
  2246. typename = void>
  2247. struct is_compatible_string_type_impl : std::false_type {};
  2248. template <typename BasicJsonType, typename CompatibleStringType>
  2249. struct is_compatible_string_type_impl <
  2250. BasicJsonType, CompatibleStringType,
  2251. enable_if_t<is_detected_exact<typename BasicJsonType::string_t::value_type,
  2252. value_type_t, CompatibleStringType>::value >>
  2253. {
  2254. static constexpr auto value =
  2255. std::is_constructible<typename BasicJsonType::string_t, CompatibleStringType>::value;
  2256. };
  2257. template <typename BasicJsonType, typename ConstructibleStringType>
  2258. struct is_compatible_string_type
  2259. : is_compatible_string_type_impl<BasicJsonType, ConstructibleStringType> {};
  2260. template <typename BasicJsonType, typename ConstructibleStringType,
  2261. typename = void>
  2262. struct is_constructible_string_type_impl : std::false_type {};
  2263. template <typename BasicJsonType, typename ConstructibleStringType>
  2264. struct is_constructible_string_type_impl <
  2265. BasicJsonType, ConstructibleStringType,
  2266. enable_if_t<is_detected_exact<typename BasicJsonType::string_t::value_type,
  2267. value_type_t, ConstructibleStringType>::value >>
  2268. {
  2269. static constexpr auto value =
  2270. std::is_constructible<ConstructibleStringType,
  2271. typename BasicJsonType::string_t>::value;
  2272. };
  2273. template <typename BasicJsonType, typename ConstructibleStringType>
  2274. struct is_constructible_string_type
  2275. : is_constructible_string_type_impl<BasicJsonType, ConstructibleStringType> {};
  2276. template <typename BasicJsonType, typename CompatibleArrayType, typename = void>
  2277. struct is_compatible_array_type_impl : std::false_type {};
  2278. template <typename BasicJsonType, typename CompatibleArrayType>
  2279. struct is_compatible_array_type_impl <
  2280. BasicJsonType, CompatibleArrayType,
  2281. enable_if_t<is_detected<value_type_t, CompatibleArrayType>::value and
  2282. is_detected<iterator_t, CompatibleArrayType>::value and
  2283. // This is needed because json_reverse_iterator has a ::iterator type...
  2284. // Therefore it is detected as a CompatibleArrayType.
  2285. // The real fix would be to have an Iterable concept.
  2286. not is_iterator_traits<
  2287. iterator_traits<CompatibleArrayType>>::value >>
  2288. {
  2289. static constexpr bool value =
  2290. std::is_constructible<BasicJsonType,
  2291. typename CompatibleArrayType::value_type>::value;
  2292. };
  2293. template <typename BasicJsonType, typename CompatibleArrayType>
  2294. struct is_compatible_array_type
  2295. : is_compatible_array_type_impl<BasicJsonType, CompatibleArrayType> {};
  2296. template <typename BasicJsonType, typename ConstructibleArrayType, typename = void>
  2297. struct is_constructible_array_type_impl : std::false_type {};
  2298. template <typename BasicJsonType, typename ConstructibleArrayType>
  2299. struct is_constructible_array_type_impl <
  2300. BasicJsonType, ConstructibleArrayType,
  2301. enable_if_t<std::is_same<ConstructibleArrayType,
  2302. typename BasicJsonType::value_type>::value >>
  2303. : std::true_type {};
  2304. template <typename BasicJsonType, typename ConstructibleArrayType>
  2305. struct is_constructible_array_type_impl <
  2306. BasicJsonType, ConstructibleArrayType,
  2307. enable_if_t<not std::is_same<ConstructibleArrayType,
  2308. typename BasicJsonType::value_type>::value and
  2309. std::is_default_constructible<ConstructibleArrayType>::value and
  2310. (std::is_move_assignable<ConstructibleArrayType>::value or
  2311. std::is_copy_assignable<ConstructibleArrayType>::value) and
  2312. is_detected<value_type_t, ConstructibleArrayType>::value and
  2313. is_detected<iterator_t, ConstructibleArrayType>::value and
  2314. is_complete_type<
  2315. detected_t<value_type_t, ConstructibleArrayType>>::value >>
  2316. {
  2317. static constexpr bool value =
  2318. // This is needed because json_reverse_iterator has a ::iterator type,
  2319. // furthermore, std::back_insert_iterator (and other iterators) have a
  2320. // base class `iterator`... Therefore it is detected as a
  2321. // ConstructibleArrayType. The real fix would be to have an Iterable
  2322. // concept.
  2323. not is_iterator_traits<iterator_traits<ConstructibleArrayType>>::value and
  2324. (std::is_same<typename ConstructibleArrayType::value_type,
  2325. typename BasicJsonType::array_t::value_type>::value or
  2326. has_from_json<BasicJsonType,
  2327. typename ConstructibleArrayType::value_type>::value or
  2328. has_non_default_from_json <
  2329. BasicJsonType, typename ConstructibleArrayType::value_type >::value);
  2330. };
  2331. template <typename BasicJsonType, typename ConstructibleArrayType>
  2332. struct is_constructible_array_type
  2333. : is_constructible_array_type_impl<BasicJsonType, ConstructibleArrayType> {};
  2334. template <typename RealIntegerType, typename CompatibleNumberIntegerType,
  2335. typename = void>
  2336. struct is_compatible_integer_type_impl : std::false_type {};
  2337. template <typename RealIntegerType, typename CompatibleNumberIntegerType>
  2338. struct is_compatible_integer_type_impl <
  2339. RealIntegerType, CompatibleNumberIntegerType,
  2340. enable_if_t<std::is_integral<RealIntegerType>::value and
  2341. std::is_integral<CompatibleNumberIntegerType>::value and
  2342. not std::is_same<bool, CompatibleNumberIntegerType>::value >>
  2343. {
  2344. // is there an assert somewhere on overflows?
  2345. using RealLimits = std::numeric_limits<RealIntegerType>;
  2346. using CompatibleLimits = std::numeric_limits<CompatibleNumberIntegerType>;
  2347. static constexpr auto value =
  2348. std::is_constructible<RealIntegerType,
  2349. CompatibleNumberIntegerType>::value and
  2350. CompatibleLimits::is_integer and
  2351. RealLimits::is_signed == CompatibleLimits::is_signed;
  2352. };
  2353. template <typename RealIntegerType, typename CompatibleNumberIntegerType>
  2354. struct is_compatible_integer_type
  2355. : is_compatible_integer_type_impl<RealIntegerType,
  2356. CompatibleNumberIntegerType> {};
  2357. template <typename BasicJsonType, typename CompatibleType, typename = void>
  2358. struct is_compatible_type_impl: std::false_type {};
  2359. template <typename BasicJsonType, typename CompatibleType>
  2360. struct is_compatible_type_impl <
  2361. BasicJsonType, CompatibleType,
  2362. enable_if_t<is_complete_type<CompatibleType>::value >>
  2363. {
  2364. static constexpr bool value =
  2365. has_to_json<BasicJsonType, CompatibleType>::value;
  2366. };
  2367. template <typename BasicJsonType, typename CompatibleType>
  2368. struct is_compatible_type
  2369. : is_compatible_type_impl<BasicJsonType, CompatibleType> {};
  2370. } // namespace detail
  2371. } // namespace nlohmann
  2372. // #include <nlohmann/detail/value_t.hpp>
  2373. #include <array> // array
  2374. #include <ciso646> // and
  2375. #include <cstddef> // size_t
  2376. #include <cstdint> // uint8_t
  2377. #include <string> // string
  2378. namespace nlohmann
  2379. {
  2380. namespace detail
  2381. {
  2382. ///////////////////////////
  2383. // JSON type enumeration //
  2384. ///////////////////////////
  2385. /*!
  2386. @brief the JSON type enumeration
  2387. This enumeration collects the different JSON types. It is internally used to
  2388. distinguish the stored values, and the functions @ref basic_json::is_null(),
  2389. @ref basic_json::is_object(), @ref basic_json::is_array(),
  2390. @ref basic_json::is_string(), @ref basic_json::is_boolean(),
  2391. @ref basic_json::is_number() (with @ref basic_json::is_number_integer(),
  2392. @ref basic_json::is_number_unsigned(), and @ref basic_json::is_number_float()),
  2393. @ref basic_json::is_discarded(), @ref basic_json::is_primitive(), and
  2394. @ref basic_json::is_structured() rely on it.
  2395. @note There are three enumeration entries (number_integer, number_unsigned, and
  2396. number_float), because the library distinguishes these three types for numbers:
  2397. @ref basic_json::number_unsigned_t is used for unsigned integers,
  2398. @ref basic_json::number_integer_t is used for signed integers, and
  2399. @ref basic_json::number_float_t is used for floating-point numbers or to
  2400. approximate integers which do not fit in the limits of their respective type.
  2401. @sa @ref basic_json::basic_json(const value_t value_type) -- create a JSON
  2402. value with the default value for a given type
  2403. @since version 1.0.0
  2404. */
  2405. enum class value_t : std::uint8_t
  2406. {
  2407. null, ///< null value
  2408. object, ///< object (unordered set of name/value pairs)
  2409. array, ///< array (ordered collection of values)
  2410. string, ///< string value
  2411. boolean, ///< boolean value
  2412. number_integer, ///< number value (signed integer)
  2413. number_unsigned, ///< number value (unsigned integer)
  2414. number_float, ///< number value (floating-point)
  2415. discarded ///< discarded by the the parser callback function
  2416. };
  2417. /*!
  2418. @brief comparison operator for JSON types
  2419. Returns an ordering that is similar to Python:
  2420. - order: null < boolean < number < object < array < string
  2421. - furthermore, each type is not smaller than itself
  2422. - discarded values are not comparable
  2423. @since version 1.0.0
  2424. */
  2425. inline bool operator<(const value_t lhs, const value_t rhs) noexcept
  2426. {
  2427. static constexpr std::array<std::uint8_t, 8> order = {{
  2428. 0 /* null */, 3 /* object */, 4 /* array */, 5 /* string */,
  2429. 1 /* boolean */, 2 /* integer */, 2 /* unsigned */, 2 /* float */
  2430. }
  2431. };
  2432. const auto l_index = static_cast<std::size_t>(lhs);
  2433. const auto r_index = static_cast<std::size_t>(rhs);
  2434. return l_index < order.size() and r_index < order.size() and order[l_index] < order[r_index];
  2435. }
  2436. } // namespace detail
  2437. } // namespace nlohmann
  2438. namespace nlohmann
  2439. {
  2440. namespace detail
  2441. {
  2442. template<typename BasicJsonType>
  2443. void from_json(const BasicJsonType& j, typename std::nullptr_t& n)
  2444. {
  2445. if (JSON_HEDLEY_UNLIKELY(not j.is_null()))
  2446. {
  2447. JSON_THROW(type_error::create(302, "type must be null, but is " + std::string(j.type_name())));
  2448. }
  2449. n = nullptr;
  2450. }
  2451. // overloads for basic_json template parameters
  2452. template<typename BasicJsonType, typename ArithmeticType,
  2453. enable_if_t<std::is_arithmetic<ArithmeticType>::value and
  2454. not std::is_same<ArithmeticType, typename BasicJsonType::boolean_t>::value,
  2455. int> = 0>
  2456. void get_arithmetic_value(const BasicJsonType& j, ArithmeticType& val)
  2457. {
  2458. switch (static_cast<value_t>(j))
  2459. {
  2460. case value_t::number_unsigned:
  2461. {
  2462. val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::number_unsigned_t*>());
  2463. break;
  2464. }
  2465. case value_t::number_integer:
  2466. {
  2467. val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::number_integer_t*>());
  2468. break;
  2469. }
  2470. case value_t::number_float:
  2471. {
  2472. val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::number_float_t*>());
  2473. break;
  2474. }
  2475. default:
  2476. JSON_THROW(type_error::create(302, "type must be number, but is " + std::string(j.type_name())));
  2477. }
  2478. }
  2479. template<typename BasicJsonType>
  2480. void from_json(const BasicJsonType& j, typename BasicJsonType::boolean_t& b)
  2481. {
  2482. if (JSON_HEDLEY_UNLIKELY(not j.is_boolean()))
  2483. {
  2484. JSON_THROW(type_error::create(302, "type must be boolean, but is " + std::string(j.type_name())));
  2485. }
  2486. b = *j.template get_ptr<const typename BasicJsonType::boolean_t*>();
  2487. }
  2488. template<typename BasicJsonType>
  2489. void from_json(const BasicJsonType& j, typename BasicJsonType::string_t& s)
  2490. {
  2491. if (JSON_HEDLEY_UNLIKELY(not j.is_string()))
  2492. {
  2493. JSON_THROW(type_error::create(302, "type must be string, but is " + std::string(j.type_name())));
  2494. }
  2495. s = *j.template get_ptr<const typename BasicJsonType::string_t*>();
  2496. }
  2497. template <
  2498. typename BasicJsonType, typename ConstructibleStringType,
  2499. enable_if_t <
  2500. is_constructible_string_type<BasicJsonType, ConstructibleStringType>::value and
  2501. not std::is_same<typename BasicJsonType::string_t,
  2502. ConstructibleStringType>::value,
  2503. int > = 0 >
  2504. void from_json(const BasicJsonType& j, ConstructibleStringType& s)
  2505. {
  2506. if (JSON_HEDLEY_UNLIKELY(not j.is_string()))
  2507. {
  2508. JSON_THROW(type_error::create(302, "type must be string, but is " + std::string(j.type_name())));
  2509. }
  2510. s = *j.template get_ptr<const typename BasicJsonType::string_t*>();
  2511. }
  2512. template<typename BasicJsonType>
  2513. void from_json(const BasicJsonType& j, typename BasicJsonType::number_float_t& val)
  2514. {
  2515. get_arithmetic_value(j, val);
  2516. }
  2517. template<typename BasicJsonType>
  2518. void from_json(const BasicJsonType& j, typename BasicJsonType::number_unsigned_t& val)
  2519. {
  2520. get_arithmetic_value(j, val);
  2521. }
  2522. template<typename BasicJsonType>
  2523. void from_json(const BasicJsonType& j, typename BasicJsonType::number_integer_t& val)
  2524. {
  2525. get_arithmetic_value(j, val);
  2526. }
  2527. template<typename BasicJsonType, typename EnumType,
  2528. enable_if_t<std::is_enum<EnumType>::value, int> = 0>
  2529. void from_json(const BasicJsonType& j, EnumType& e)
  2530. {
  2531. typename std::underlying_type<EnumType>::type val;
  2532. get_arithmetic_value(j, val);
  2533. e = static_cast<EnumType>(val);
  2534. }
  2535. // forward_list doesn't have an insert method
  2536. template<typename BasicJsonType, typename T, typename Allocator,
  2537. enable_if_t<std::is_convertible<BasicJsonType, T>::value, int> = 0>
  2538. void from_json(const BasicJsonType& j, std::forward_list<T, Allocator>& l)
  2539. {
  2540. if (JSON_HEDLEY_UNLIKELY(not j.is_array()))
  2541. {
  2542. JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(j.type_name())));
  2543. }
  2544. l.clear();
  2545. std::transform(j.rbegin(), j.rend(),
  2546. std::front_inserter(l), [](const BasicJsonType & i)
  2547. {
  2548. return i.template get<T>();
  2549. });
  2550. }
  2551. // valarray doesn't have an insert method
  2552. template<typename BasicJsonType, typename T,
  2553. enable_if_t<std::is_convertible<BasicJsonType, T>::value, int> = 0>
  2554. void from_json(const BasicJsonType& j, std::valarray<T>& l)
  2555. {
  2556. if (JSON_HEDLEY_UNLIKELY(not j.is_array()))
  2557. {
  2558. JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(j.type_name())));
  2559. }
  2560. l.resize(j.size());
  2561. std::copy(j.m_value.array->begin(), j.m_value.array->end(), std::begin(l));
  2562. }
  2563. template <typename BasicJsonType, typename T, std::size_t N>
  2564. auto from_json(const BasicJsonType& j, T (&arr)[N])
  2565. -> decltype(j.template get<T>(), void())
  2566. {
  2567. for (std::size_t i = 0; i < N; ++i)
  2568. {
  2569. arr[i] = j.at(i).template get<T>();
  2570. }
  2571. }
  2572. template<typename BasicJsonType>
  2573. void from_json_array_impl(const BasicJsonType& j, typename BasicJsonType::array_t& arr, priority_tag<3> /*unused*/)
  2574. {
  2575. arr = *j.template get_ptr<const typename BasicJsonType::array_t*>();
  2576. }
  2577. template <typename BasicJsonType, typename T, std::size_t N>
  2578. auto from_json_array_impl(const BasicJsonType& j, std::array<T, N>& arr,
  2579. priority_tag<2> /*unused*/)
  2580. -> decltype(j.template get<T>(), void())
  2581. {
  2582. for (std::size_t i = 0; i < N; ++i)
  2583. {
  2584. arr[i] = j.at(i).template get<T>();
  2585. }
  2586. }
  2587. template<typename BasicJsonType, typename ConstructibleArrayType>
  2588. auto from_json_array_impl(const BasicJsonType& j, ConstructibleArrayType& arr, priority_tag<1> /*unused*/)
  2589. -> decltype(
  2590. arr.reserve(std::declval<typename ConstructibleArrayType::size_type>()),
  2591. j.template get<typename ConstructibleArrayType::value_type>(),
  2592. void())
  2593. {
  2594. using std::end;
  2595. ConstructibleArrayType ret;
  2596. ret.reserve(j.size());
  2597. std::transform(j.begin(), j.end(),
  2598. std::inserter(ret, end(ret)), [](const BasicJsonType & i)
  2599. {
  2600. // get<BasicJsonType>() returns *this, this won't call a from_json
  2601. // method when value_type is BasicJsonType
  2602. return i.template get<typename ConstructibleArrayType::value_type>();
  2603. });
  2604. arr = std::move(ret);
  2605. }
  2606. template <typename BasicJsonType, typename ConstructibleArrayType>
  2607. void from_json_array_impl(const BasicJsonType& j, ConstructibleArrayType& arr,
  2608. priority_tag<0> /*unused*/)
  2609. {
  2610. using std::end;
  2611. ConstructibleArrayType ret;
  2612. std::transform(
  2613. j.begin(), j.end(), std::inserter(ret, end(ret)),
  2614. [](const BasicJsonType & i)
  2615. {
  2616. // get<BasicJsonType>() returns *this, this won't call a from_json
  2617. // method when value_type is BasicJsonType
  2618. return i.template get<typename ConstructibleArrayType::value_type>();
  2619. });
  2620. arr = std::move(ret);
  2621. }
  2622. template <typename BasicJsonType, typename ConstructibleArrayType,
  2623. enable_if_t <
  2624. is_constructible_array_type<BasicJsonType, ConstructibleArrayType>::value and
  2625. not is_constructible_object_type<BasicJsonType, ConstructibleArrayType>::value and
  2626. not is_constructible_string_type<BasicJsonType, ConstructibleArrayType>::value and
  2627. not is_basic_json<ConstructibleArrayType>::value,
  2628. int > = 0 >
  2629. auto from_json(const BasicJsonType& j, ConstructibleArrayType& arr)
  2630. -> decltype(from_json_array_impl(j, arr, priority_tag<3> {}),
  2631. j.template get<typename ConstructibleArrayType::value_type>(),
  2632. void())
  2633. {
  2634. if (JSON_HEDLEY_UNLIKELY(not j.is_array()))
  2635. {
  2636. JSON_THROW(type_error::create(302, "type must be array, but is " +
  2637. std::string(j.type_name())));
  2638. }
  2639. from_json_array_impl(j, arr, priority_tag<3> {});
  2640. }
  2641. template<typename BasicJsonType, typename ConstructibleObjectType,
  2642. enable_if_t<is_constructible_object_type<BasicJsonType, ConstructibleObjectType>::value, int> = 0>
  2643. void from_json(const BasicJsonType& j, ConstructibleObjectType& obj)
  2644. {
  2645. if (JSON_HEDLEY_UNLIKELY(not j.is_object()))
  2646. {
  2647. JSON_THROW(type_error::create(302, "type must be object, but is " + std::string(j.type_name())));
  2648. }
  2649. ConstructibleObjectType ret;
  2650. auto inner_object = j.template get_ptr<const typename BasicJsonType::object_t*>();
  2651. using value_type = typename ConstructibleObjectType::value_type;
  2652. std::transform(
  2653. inner_object->begin(), inner_object->end(),
  2654. std::inserter(ret, ret.begin()),
  2655. [](typename BasicJsonType::object_t::value_type const & p)
  2656. {
  2657. return value_type(p.first, p.second.template get<typename ConstructibleObjectType::mapped_type>());
  2658. });
  2659. obj = std::move(ret);
  2660. }
  2661. // overload for arithmetic types, not chosen for basic_json template arguments
  2662. // (BooleanType, etc..); note: Is it really necessary to provide explicit
  2663. // overloads for boolean_t etc. in case of a custom BooleanType which is not
  2664. // an arithmetic type?
  2665. template<typename BasicJsonType, typename ArithmeticType,
  2666. enable_if_t <
  2667. std::is_arithmetic<ArithmeticType>::value and
  2668. not std::is_same<ArithmeticType, typename BasicJsonType::number_unsigned_t>::value and
  2669. not std::is_same<ArithmeticType, typename BasicJsonType::number_integer_t>::value and
  2670. not std::is_same<ArithmeticType, typename BasicJsonType::number_float_t>::value and
  2671. not std::is_same<ArithmeticType, typename BasicJsonType::boolean_t>::value,
  2672. int> = 0>
  2673. void from_json(const BasicJsonType& j, ArithmeticType& val)
  2674. {
  2675. switch (static_cast<value_t>(j))
  2676. {
  2677. case value_t::number_unsigned:
  2678. {
  2679. val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::number_unsigned_t*>());
  2680. break;
  2681. }
  2682. case value_t::number_integer:
  2683. {
  2684. val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::number_integer_t*>());
  2685. break;
  2686. }
  2687. case value_t::number_float:
  2688. {
  2689. val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::number_float_t*>());
  2690. break;
  2691. }
  2692. case value_t::boolean:
  2693. {
  2694. val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::boolean_t*>());
  2695. break;
  2696. }
  2697. default:
  2698. JSON_THROW(type_error::create(302, "type must be number, but is " + std::string(j.type_name())));
  2699. }
  2700. }
  2701. template<typename BasicJsonType, typename A1, typename A2>
  2702. void from_json(const BasicJsonType& j, std::pair<A1, A2>& p)
  2703. {
  2704. p = {j.at(0).template get<A1>(), j.at(1).template get<A2>()};
  2705. }
  2706. template<typename BasicJsonType, typename Tuple, std::size_t... Idx>
  2707. void from_json_tuple_impl(const BasicJsonType& j, Tuple& t, index_sequence<Idx...> /*unused*/)
  2708. {
  2709. t = std::make_tuple(j.at(Idx).template get<typename std::tuple_element<Idx, Tuple>::type>()...);
  2710. }
  2711. template<typename BasicJsonType, typename... Args>
  2712. void from_json(const BasicJsonType& j, std::tuple<Args...>& t)
  2713. {
  2714. from_json_tuple_impl(j, t, index_sequence_for<Args...> {});
  2715. }
  2716. template <typename BasicJsonType, typename Key, typename Value, typename Compare, typename Allocator,
  2717. typename = enable_if_t<not std::is_constructible<
  2718. typename BasicJsonType::string_t, Key>::value>>
  2719. void from_json(const BasicJsonType& j, std::map<Key, Value, Compare, Allocator>& m)
  2720. {
  2721. if (JSON_HEDLEY_UNLIKELY(not j.is_array()))
  2722. {
  2723. JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(j.type_name())));
  2724. }
  2725. m.clear();
  2726. for (const auto& p : j)
  2727. {
  2728. if (JSON_HEDLEY_UNLIKELY(not p.is_array()))
  2729. {
  2730. JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(p.type_name())));
  2731. }
  2732. m.emplace(p.at(0).template get<Key>(), p.at(1).template get<Value>());
  2733. }
  2734. }
  2735. template <typename BasicJsonType, typename Key, typename Value, typename Hash, typename KeyEqual, typename Allocator,
  2736. typename = enable_if_t<not std::is_constructible<
  2737. typename BasicJsonType::string_t, Key>::value>>
  2738. void from_json(const BasicJsonType& j, std::unordered_map<Key, Value, Hash, KeyEqual, Allocator>& m)
  2739. {
  2740. if (JSON_HEDLEY_UNLIKELY(not j.is_array()))
  2741. {
  2742. JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(j.type_name())));
  2743. }
  2744. m.clear();
  2745. for (const auto& p : j)
  2746. {
  2747. if (JSON_HEDLEY_UNLIKELY(not p.is_array()))
  2748. {
  2749. JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(p.type_name())));
  2750. }
  2751. m.emplace(p.at(0).template get<Key>(), p.at(1).template get<Value>());
  2752. }
  2753. }
  2754. struct from_json_fn
  2755. {
  2756. template<typename BasicJsonType, typename T>
  2757. auto operator()(const BasicJsonType& j, T& val) const
  2758. noexcept(noexcept(from_json(j, val)))
  2759. -> decltype(from_json(j, val), void())
  2760. {
  2761. return from_json(j, val);
  2762. }
  2763. };
  2764. } // namespace detail
  2765. /// namespace to hold default `from_json` function
  2766. /// to see why this is required:
  2767. /// http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2015/n4381.html
  2768. namespace
  2769. {
  2770. constexpr const auto& from_json = detail::static_const<detail::from_json_fn>::value;
  2771. } // namespace
  2772. } // namespace nlohmann
  2773. // #include <nlohmann/detail/conversions/to_json.hpp>
  2774. #include <algorithm> // copy
  2775. #include <ciso646> // or, and, not
  2776. #include <iterator> // begin, end
  2777. #include <string> // string
  2778. #include <tuple> // tuple, get
  2779. #include <type_traits> // is_same, is_constructible, is_floating_point, is_enum, underlying_type
  2780. #include <utility> // move, forward, declval, pair
  2781. #include <valarray> // valarray
  2782. #include <vector> // vector
  2783. // #include <nlohmann/detail/iterators/iteration_proxy.hpp>
  2784. #include <cstddef> // size_t
  2785. #include <iterator> // input_iterator_tag
  2786. #include <string> // string, to_string
  2787. #include <tuple> // tuple_size, get, tuple_element
  2788. // #include <nlohmann/detail/meta/type_traits.hpp>
  2789. // #include <nlohmann/detail/value_t.hpp>
  2790. namespace nlohmann
  2791. {
  2792. namespace detail
  2793. {
  2794. template <typename IteratorType> class iteration_proxy_value
  2795. {
  2796. public:
  2797. using difference_type = std::ptrdiff_t;
  2798. using value_type = iteration_proxy_value;
  2799. using pointer = value_type * ;
  2800. using reference = value_type & ;
  2801. using iterator_category = std::input_iterator_tag;
  2802. private:
  2803. /// the iterator
  2804. IteratorType anchor;
  2805. /// an index for arrays (used to create key names)
  2806. std::size_t array_index = 0;
  2807. /// last stringified array index
  2808. mutable std::size_t array_index_last = 0;
  2809. /// a string representation of the array index
  2810. mutable std::string array_index_str = "0";
  2811. /// an empty string (to return a reference for primitive values)
  2812. const std::string empty_str = "";
  2813. public:
  2814. explicit iteration_proxy_value(IteratorType it) noexcept : anchor(it) {}
  2815. /// dereference operator (needed for range-based for)
  2816. iteration_proxy_value& operator*()
  2817. {
  2818. return *this;
  2819. }
  2820. /// increment operator (needed for range-based for)
  2821. iteration_proxy_value& operator++()
  2822. {
  2823. ++anchor;
  2824. ++array_index;
  2825. return *this;
  2826. }
  2827. /// equality operator (needed for InputIterator)
  2828. bool operator==(const iteration_proxy_value& o) const
  2829. {
  2830. return anchor == o.anchor;
  2831. }
  2832. /// inequality operator (needed for range-based for)
  2833. bool operator!=(const iteration_proxy_value& o) const
  2834. {
  2835. return anchor != o.anchor;
  2836. }
  2837. /// return key of the iterator
  2838. const std::string& key() const
  2839. {
  2840. assert(anchor.m_object != nullptr);
  2841. switch (anchor.m_object->type())
  2842. {
  2843. // use integer array index as key
  2844. case value_t::array:
  2845. {
  2846. if (array_index != array_index_last)
  2847. {
  2848. array_index_str = std::to_string(array_index);
  2849. array_index_last = array_index;
  2850. }
  2851. return array_index_str;
  2852. }
  2853. // use key from the object
  2854. case value_t::object:
  2855. return anchor.key();
  2856. // use an empty key for all primitive types
  2857. default:
  2858. return empty_str;
  2859. }
  2860. }
  2861. /// return value of the iterator
  2862. typename IteratorType::reference value() const
  2863. {
  2864. return anchor.value();
  2865. }
  2866. };
  2867. /// proxy class for the items() function
  2868. template<typename IteratorType> class iteration_proxy
  2869. {
  2870. private:
  2871. /// the container to iterate
  2872. typename IteratorType::reference container;
  2873. public:
  2874. /// construct iteration proxy from a container
  2875. explicit iteration_proxy(typename IteratorType::reference cont) noexcept
  2876. : container(cont) {}
  2877. /// return iterator begin (needed for range-based for)
  2878. iteration_proxy_value<IteratorType> begin() noexcept
  2879. {
  2880. return iteration_proxy_value<IteratorType>(container.begin());
  2881. }
  2882. /// return iterator end (needed for range-based for)
  2883. iteration_proxy_value<IteratorType> end() noexcept
  2884. {
  2885. return iteration_proxy_value<IteratorType>(container.end());
  2886. }
  2887. };
  2888. // Structured Bindings Support
  2889. // For further reference see https://blog.tartanllama.xyz/structured-bindings/
  2890. // And see https://github.com/nlohmann/json/pull/1391
  2891. template <std::size_t N, typename IteratorType, enable_if_t<N == 0, int> = 0>
  2892. auto get(const nlohmann::detail::iteration_proxy_value<IteratorType>& i) -> decltype(i.key())
  2893. {
  2894. return i.key();
  2895. }
  2896. // Structured Bindings Support
  2897. // For further reference see https://blog.tartanllama.xyz/structured-bindings/
  2898. // And see https://github.com/nlohmann/json/pull/1391
  2899. template <std::size_t N, typename IteratorType, enable_if_t<N == 1, int> = 0>
  2900. auto get(const nlohmann::detail::iteration_proxy_value<IteratorType>& i) -> decltype(i.value())
  2901. {
  2902. return i.value();
  2903. }
  2904. } // namespace detail
  2905. } // namespace nlohmann
  2906. // The Addition to the STD Namespace is required to add
  2907. // Structured Bindings Support to the iteration_proxy_value class
  2908. // For further reference see https://blog.tartanllama.xyz/structured-bindings/
  2909. // And see https://github.com/nlohmann/json/pull/1391
  2910. namespace std
  2911. {
  2912. #if defined(__clang__)
  2913. // Fix: https://github.com/nlohmann/json/issues/1401
  2914. #pragma clang diagnostic push
  2915. #pragma clang diagnostic ignored "-Wmismatched-tags"
  2916. #endif
  2917. template <typename IteratorType>
  2918. class tuple_size<::nlohmann::detail::iteration_proxy_value<IteratorType>>
  2919. : public std::integral_constant<std::size_t, 2> {};
  2920. template <std::size_t N, typename IteratorType>
  2921. class tuple_element<N, ::nlohmann::detail::iteration_proxy_value<IteratorType >>
  2922. {
  2923. public:
  2924. using type = decltype(
  2925. get<N>(std::declval <
  2926. ::nlohmann::detail::iteration_proxy_value<IteratorType >> ()));
  2927. };
  2928. #if defined(__clang__)
  2929. #pragma clang diagnostic pop
  2930. #endif
  2931. } // namespace std
  2932. // #include <nlohmann/detail/meta/cpp_future.hpp>
  2933. // #include <nlohmann/detail/meta/type_traits.hpp>
  2934. // #include <nlohmann/detail/value_t.hpp>
  2935. namespace nlohmann
  2936. {
  2937. namespace detail
  2938. {
  2939. //////////////////
  2940. // constructors //
  2941. //////////////////
  2942. template<value_t> struct external_constructor;
  2943. template<>
  2944. struct external_constructor<value_t::boolean>
  2945. {
  2946. template<typename BasicJsonType>
  2947. static void construct(BasicJsonType& j, typename BasicJsonType::boolean_t b) noexcept
  2948. {
  2949. j.m_type = value_t::boolean;
  2950. j.m_value = b;
  2951. j.assert_invariant();
  2952. }
  2953. };
  2954. template<>
  2955. struct external_constructor<value_t::string>
  2956. {
  2957. template<typename BasicJsonType>
  2958. static void construct(BasicJsonType& j, const typename BasicJsonType::string_t& s)
  2959. {
  2960. j.m_type = value_t::string;
  2961. j.m_value = s;
  2962. j.assert_invariant();
  2963. }
  2964. template<typename BasicJsonType>
  2965. static void construct(BasicJsonType& j, typename BasicJsonType::string_t&& s)
  2966. {
  2967. j.m_type = value_t::string;
  2968. j.m_value = std::move(s);
  2969. j.assert_invariant();
  2970. }
  2971. template<typename BasicJsonType, typename CompatibleStringType,
  2972. enable_if_t<not std::is_same<CompatibleStringType, typename BasicJsonType::string_t>::value,
  2973. int> = 0>
  2974. static void construct(BasicJsonType& j, const CompatibleStringType& str)
  2975. {
  2976. j.m_type = value_t::string;
  2977. j.m_value.string = j.template create<typename BasicJsonType::string_t>(str);
  2978. j.assert_invariant();
  2979. }
  2980. };
  2981. template<>
  2982. struct external_constructor<value_t::number_float>
  2983. {
  2984. template<typename BasicJsonType>
  2985. static void construct(BasicJsonType& j, typename BasicJsonType::number_float_t val) noexcept
  2986. {
  2987. j.m_type = value_t::number_float;
  2988. j.m_value = val;
  2989. j.assert_invariant();
  2990. }
  2991. };
  2992. template<>
  2993. struct external_constructor<value_t::number_unsigned>
  2994. {
  2995. template<typename BasicJsonType>
  2996. static void construct(BasicJsonType& j, typename BasicJsonType::number_unsigned_t val) noexcept
  2997. {
  2998. j.m_type = value_t::number_unsigned;
  2999. j.m_value = val;
  3000. j.assert_invariant();
  3001. }
  3002. };
  3003. template<>
  3004. struct external_constructor<value_t::number_integer>
  3005. {
  3006. template<typename BasicJsonType>
  3007. static void construct(BasicJsonType& j, typename BasicJsonType::number_integer_t val) noexcept
  3008. {
  3009. j.m_type = value_t::number_integer;
  3010. j.m_value = val;
  3011. j.assert_invariant();
  3012. }
  3013. };
  3014. template<>
  3015. struct external_constructor<value_t::array>
  3016. {
  3017. template<typename BasicJsonType>
  3018. static void construct(BasicJsonType& j, const typename BasicJsonType::array_t& arr)
  3019. {
  3020. j.m_type = value_t::array;
  3021. j.m_value = arr;
  3022. j.assert_invariant();
  3023. }
  3024. template<typename BasicJsonType>
  3025. static void construct(BasicJsonType& j, typename BasicJsonType::array_t&& arr)
  3026. {
  3027. j.m_type = value_t::array;
  3028. j.m_value = std::move(arr);
  3029. j.assert_invariant();
  3030. }
  3031. template<typename BasicJsonType, typename CompatibleArrayType,
  3032. enable_if_t<not std::is_same<CompatibleArrayType, typename BasicJsonType::array_t>::value,
  3033. int> = 0>
  3034. static void construct(BasicJsonType& j, const CompatibleArrayType& arr)
  3035. {
  3036. using std::begin;
  3037. using std::end;
  3038. j.m_type = value_t::array;
  3039. j.m_value.array = j.template create<typename BasicJsonType::array_t>(begin(arr), end(arr));
  3040. j.assert_invariant();
  3041. }
  3042. template<typename BasicJsonType>
  3043. static void construct(BasicJsonType& j, const std::vector<bool>& arr)
  3044. {
  3045. j.m_type = value_t::array;
  3046. j.m_value = value_t::array;
  3047. j.m_value.array->reserve(arr.size());
  3048. for (const bool x : arr)
  3049. {
  3050. j.m_value.array->push_back(x);
  3051. }
  3052. j.assert_invariant();
  3053. }
  3054. template<typename BasicJsonType, typename T,
  3055. enable_if_t<std::is_convertible<T, BasicJsonType>::value, int> = 0>
  3056. static void construct(BasicJsonType& j, const std::valarray<T>& arr)
  3057. {
  3058. j.m_type = value_t::array;
  3059. j.m_value = value_t::array;
  3060. j.m_value.array->resize(arr.size());
  3061. std::copy(std::begin(arr), std::end(arr), j.m_value.array->begin());
  3062. j.assert_invariant();
  3063. }
  3064. };
  3065. template<>
  3066. struct external_constructor<value_t::object>
  3067. {
  3068. template<typename BasicJsonType>
  3069. static void construct(BasicJsonType& j, const typename BasicJsonType::object_t& obj)
  3070. {
  3071. j.m_type = value_t::object;
  3072. j.m_value = obj;
  3073. j.assert_invariant();
  3074. }
  3075. template<typename BasicJsonType>
  3076. static void construct(BasicJsonType& j, typename BasicJsonType::object_t&& obj)
  3077. {
  3078. j.m_type = value_t::object;
  3079. j.m_value = std::move(obj);
  3080. j.assert_invariant();
  3081. }
  3082. template<typename BasicJsonType, typename CompatibleObjectType,
  3083. enable_if_t<not std::is_same<CompatibleObjectType, typename BasicJsonType::object_t>::value, int> = 0>
  3084. static void construct(BasicJsonType& j, const CompatibleObjectType& obj)
  3085. {
  3086. using std::begin;
  3087. using std::end;
  3088. j.m_type = value_t::object;
  3089. j.m_value.object = j.template create<typename BasicJsonType::object_t>(begin(obj), end(obj));
  3090. j.assert_invariant();
  3091. }
  3092. };
  3093. /////////////
  3094. // to_json //
  3095. /////////////
  3096. template<typename BasicJsonType, typename T,
  3097. enable_if_t<std::is_same<T, typename BasicJsonType::boolean_t>::value, int> = 0>
  3098. void to_json(BasicJsonType& j, T b) noexcept
  3099. {
  3100. external_constructor<value_t::boolean>::construct(j, b);
  3101. }
  3102. template<typename BasicJsonType, typename CompatibleString,
  3103. enable_if_t<std::is_constructible<typename BasicJsonType::string_t, CompatibleString>::value, int> = 0>
  3104. void to_json(BasicJsonType& j, const CompatibleString& s)
  3105. {
  3106. external_constructor<value_t::string>::construct(j, s);
  3107. }
  3108. template<typename BasicJsonType>
  3109. void to_json(BasicJsonType& j, typename BasicJsonType::string_t&& s)
  3110. {
  3111. external_constructor<value_t::string>::construct(j, std::move(s));
  3112. }
  3113. template<typename BasicJsonType, typename FloatType,
  3114. enable_if_t<std::is_floating_point<FloatType>::value, int> = 0>
  3115. void to_json(BasicJsonType& j, FloatType val) noexcept
  3116. {
  3117. external_constructor<value_t::number_float>::construct(j, static_cast<typename BasicJsonType::number_float_t>(val));
  3118. }
  3119. template<typename BasicJsonType, typename CompatibleNumberUnsignedType,
  3120. enable_if_t<is_compatible_integer_type<typename BasicJsonType::number_unsigned_t, CompatibleNumberUnsignedType>::value, int> = 0>
  3121. void to_json(BasicJsonType& j, CompatibleNumberUnsignedType val) noexcept
  3122. {
  3123. external_constructor<value_t::number_unsigned>::construct(j, static_cast<typename BasicJsonType::number_unsigned_t>(val));
  3124. }
  3125. template<typename BasicJsonType, typename CompatibleNumberIntegerType,
  3126. enable_if_t<is_compatible_integer_type<typename BasicJsonType::number_integer_t, CompatibleNumberIntegerType>::value, int> = 0>
  3127. void to_json(BasicJsonType& j, CompatibleNumberIntegerType val) noexcept
  3128. {
  3129. external_constructor<value_t::number_integer>::construct(j, static_cast<typename BasicJsonType::number_integer_t>(val));
  3130. }
  3131. template<typename BasicJsonType, typename EnumType,
  3132. enable_if_t<std::is_enum<EnumType>::value, int> = 0>
  3133. void to_json(BasicJsonType& j, EnumType e) noexcept
  3134. {
  3135. using underlying_type = typename std::underlying_type<EnumType>::type;
  3136. external_constructor<value_t::number_integer>::construct(j, static_cast<underlying_type>(e));
  3137. }
  3138. template<typename BasicJsonType>
  3139. void to_json(BasicJsonType& j, const std::vector<bool>& e)
  3140. {
  3141. external_constructor<value_t::array>::construct(j, e);
  3142. }
  3143. template <typename BasicJsonType, typename CompatibleArrayType,
  3144. enable_if_t<is_compatible_array_type<BasicJsonType,
  3145. CompatibleArrayType>::value and
  3146. not is_compatible_object_type<
  3147. BasicJsonType, CompatibleArrayType>::value and
  3148. not is_compatible_string_type<BasicJsonType, CompatibleArrayType>::value and
  3149. not is_basic_json<CompatibleArrayType>::value,
  3150. int> = 0>
  3151. void to_json(BasicJsonType& j, const CompatibleArrayType& arr)
  3152. {
  3153. external_constructor<value_t::array>::construct(j, arr);
  3154. }
  3155. template<typename BasicJsonType, typename T,
  3156. enable_if_t<std::is_convertible<T, BasicJsonType>::value, int> = 0>
  3157. void to_json(BasicJsonType& j, const std::valarray<T>& arr)
  3158. {
  3159. external_constructor<value_t::array>::construct(j, std::move(arr));
  3160. }
  3161. template<typename BasicJsonType>
  3162. void to_json(BasicJsonType& j, typename BasicJsonType::array_t&& arr)
  3163. {
  3164. external_constructor<value_t::array>::construct(j, std::move(arr));
  3165. }
  3166. template<typename BasicJsonType, typename CompatibleObjectType,
  3167. enable_if_t<is_compatible_object_type<BasicJsonType, CompatibleObjectType>::value and not is_basic_json<CompatibleObjectType>::value, int> = 0>
  3168. void to_json(BasicJsonType& j, const CompatibleObjectType& obj)
  3169. {
  3170. external_constructor<value_t::object>::construct(j, obj);
  3171. }
  3172. template<typename BasicJsonType>
  3173. void to_json(BasicJsonType& j, typename BasicJsonType::object_t&& obj)
  3174. {
  3175. external_constructor<value_t::object>::construct(j, std::move(obj));
  3176. }
  3177. template <
  3178. typename BasicJsonType, typename T, std::size_t N,
  3179. enable_if_t<not std::is_constructible<typename BasicJsonType::string_t,
  3180. const T(&)[N]>::value,
  3181. int> = 0 >
  3182. void to_json(BasicJsonType& j, const T(&arr)[N])
  3183. {
  3184. external_constructor<value_t::array>::construct(j, arr);
  3185. }
  3186. template<typename BasicJsonType, typename... Args>
  3187. void to_json(BasicJsonType& j, const std::pair<Args...>& p)
  3188. {
  3189. j = { p.first, p.second };
  3190. }
  3191. // for https://github.com/nlohmann/json/pull/1134
  3192. template < typename BasicJsonType, typename T,
  3193. enable_if_t<std::is_same<T, iteration_proxy_value<typename BasicJsonType::iterator>>::value, int> = 0>
  3194. void to_json(BasicJsonType& j, const T& b)
  3195. {
  3196. j = { {b.key(), b.value()} };
  3197. }
  3198. template<typename BasicJsonType, typename Tuple, std::size_t... Idx>
  3199. void to_json_tuple_impl(BasicJsonType& j, const Tuple& t, index_sequence<Idx...> /*unused*/)
  3200. {
  3201. j = { std::get<Idx>(t)... };
  3202. }
  3203. template<typename BasicJsonType, typename... Args>
  3204. void to_json(BasicJsonType& j, const std::tuple<Args...>& t)
  3205. {
  3206. to_json_tuple_impl(j, t, index_sequence_for<Args...> {});
  3207. }
  3208. struct to_json_fn
  3209. {
  3210. template<typename BasicJsonType, typename T>
  3211. auto operator()(BasicJsonType& j, T&& val) const noexcept(noexcept(to_json(j, std::forward<T>(val))))
  3212. -> decltype(to_json(j, std::forward<T>(val)), void())
  3213. {
  3214. return to_json(j, std::forward<T>(val));
  3215. }
  3216. };
  3217. } // namespace detail
  3218. /// namespace to hold default `to_json` function
  3219. namespace
  3220. {
  3221. constexpr const auto& to_json = detail::static_const<detail::to_json_fn>::value;
  3222. } // namespace
  3223. } // namespace nlohmann
  3224. namespace nlohmann
  3225. {
  3226. template<typename, typename>
  3227. struct adl_serializer
  3228. {
  3229. /*!
  3230. @brief convert a JSON value to any value type
  3231. This function is usually called by the `get()` function of the
  3232. @ref basic_json class (either explicit or via conversion operators).
  3233. @param[in] j JSON value to read from
  3234. @param[in,out] val value to write to
  3235. */
  3236. template<typename BasicJsonType, typename ValueType>
  3237. static auto from_json(BasicJsonType&& j, ValueType& val) noexcept(
  3238. noexcept(::nlohmann::from_json(std::forward<BasicJsonType>(j), val)))
  3239. -> decltype(::nlohmann::from_json(std::forward<BasicJsonType>(j), val), void())
  3240. {
  3241. ::nlohmann::from_json(std::forward<BasicJsonType>(j), val);
  3242. }
  3243. /*!
  3244. @brief convert any value type to a JSON value
  3245. This function is usually called by the constructors of the @ref basic_json
  3246. class.
  3247. @param[in,out] j JSON value to write to
  3248. @param[in] val value to read from
  3249. */
  3250. template <typename BasicJsonType, typename ValueType>
  3251. static auto to_json(BasicJsonType& j, ValueType&& val) noexcept(
  3252. noexcept(::nlohmann::to_json(j, std::forward<ValueType>(val))))
  3253. -> decltype(::nlohmann::to_json(j, std::forward<ValueType>(val)), void())
  3254. {
  3255. ::nlohmann::to_json(j, std::forward<ValueType>(val));
  3256. }
  3257. };
  3258. } // namespace nlohmann
  3259. // #include <nlohmann/detail/conversions/from_json.hpp>
  3260. // #include <nlohmann/detail/conversions/to_json.hpp>
  3261. // #include <nlohmann/detail/exceptions.hpp>
  3262. // #include <nlohmann/detail/input/binary_reader.hpp>
  3263. #include <algorithm> // generate_n
  3264. #include <array> // array
  3265. #include <cassert> // assert
  3266. #include <cmath> // ldexp
  3267. #include <cstddef> // size_t
  3268. #include <cstdint> // uint8_t, uint16_t, uint32_t, uint64_t
  3269. #include <cstdio> // snprintf
  3270. #include <cstring> // memcpy
  3271. #include <iterator> // back_inserter
  3272. #include <limits> // numeric_limits
  3273. #include <string> // char_traits, string
  3274. #include <utility> // make_pair, move
  3275. // #include <nlohmann/detail/exceptions.hpp>
  3276. // #include <nlohmann/detail/input/input_adapters.hpp>
  3277. #include <array> // array
  3278. #include <cassert> // assert
  3279. #include <cstddef> // size_t
  3280. #include <cstdio> //FILE *
  3281. #include <cstring> // strlen
  3282. #include <istream> // istream
  3283. #include <iterator> // begin, end, iterator_traits, random_access_iterator_tag, distance, next
  3284. #include <memory> // shared_ptr, make_shared, addressof
  3285. #include <numeric> // accumulate
  3286. #include <string> // string, char_traits
  3287. #include <type_traits> // enable_if, is_base_of, is_pointer, is_integral, remove_pointer
  3288. #include <utility> // pair, declval
  3289. // #include <nlohmann/detail/iterators/iterator_traits.hpp>
  3290. // #include <nlohmann/detail/macro_scope.hpp>
  3291. namespace nlohmann
  3292. {
  3293. namespace detail
  3294. {
  3295. /// the supported input formats
  3296. enum class input_format_t { json, cbor, msgpack, ubjson, bson };
  3297. ////////////////////
  3298. // input adapters //
  3299. ////////////////////
  3300. /*!
  3301. @brief abstract input adapter interface
  3302. Produces a stream of std::char_traits<char>::int_type characters from a
  3303. std::istream, a buffer, or some other input type. Accepts the return of
  3304. exactly one non-EOF character for future input. The int_type characters
  3305. returned consist of all valid char values as positive values (typically
  3306. unsigned char), plus an EOF value outside that range, specified by the value
  3307. of the function std::char_traits<char>::eof(). This value is typically -1, but
  3308. could be any arbitrary value which is not a valid char value.
  3309. */
  3310. struct input_adapter_protocol
  3311. {
  3312. /// get a character [0,255] or std::char_traits<char>::eof().
  3313. virtual std::char_traits<char>::int_type get_character() = 0;
  3314. virtual ~input_adapter_protocol() = default;
  3315. };
  3316. /// a type to simplify interfaces
  3317. using input_adapter_t = std::shared_ptr<input_adapter_protocol>;
  3318. /*!
  3319. Input adapter for stdio file access. This adapter read only 1 byte and do not use any
  3320. buffer. This adapter is a very low level adapter.
  3321. */
  3322. class file_input_adapter : public input_adapter_protocol
  3323. {
  3324. public:
  3325. JSON_HEDLEY_NON_NULL(2)
  3326. explicit file_input_adapter(std::FILE* f) noexcept
  3327. : m_file(f)
  3328. {}
  3329. // make class move-only
  3330. file_input_adapter(const file_input_adapter&) = delete;
  3331. file_input_adapter(file_input_adapter&&) = default;
  3332. file_input_adapter& operator=(const file_input_adapter&) = delete;
  3333. file_input_adapter& operator=(file_input_adapter&&) = default;
  3334. ~file_input_adapter() override = default;
  3335. std::char_traits<char>::int_type get_character() noexcept override
  3336. {
  3337. return std::fgetc(m_file);
  3338. }
  3339. private:
  3340. /// the file pointer to read from
  3341. std::FILE* m_file;
  3342. };
  3343. /*!
  3344. Input adapter for a (caching) istream. Ignores a UFT Byte Order Mark at
  3345. beginning of input. Does not support changing the underlying std::streambuf
  3346. in mid-input. Maintains underlying std::istream and std::streambuf to support
  3347. subsequent use of standard std::istream operations to process any input
  3348. characters following those used in parsing the JSON input. Clears the
  3349. std::istream flags; any input errors (e.g., EOF) will be detected by the first
  3350. subsequent call for input from the std::istream.
  3351. */
  3352. class input_stream_adapter : public input_adapter_protocol
  3353. {
  3354. public:
  3355. ~input_stream_adapter() override
  3356. {
  3357. // clear stream flags; we use underlying streambuf I/O, do not
  3358. // maintain ifstream flags, except eof
  3359. is.clear(is.rdstate() & std::ios::eofbit);
  3360. }
  3361. explicit input_stream_adapter(std::istream& i)
  3362. : is(i), sb(*i.rdbuf())
  3363. {}
  3364. // delete because of pointer members
  3365. input_stream_adapter(const input_stream_adapter&) = delete;
  3366. input_stream_adapter& operator=(input_stream_adapter&) = delete;
  3367. input_stream_adapter(input_stream_adapter&&) = delete;
  3368. input_stream_adapter& operator=(input_stream_adapter&&) = delete;
  3369. // std::istream/std::streambuf use std::char_traits<char>::to_int_type, to
  3370. // ensure that std::char_traits<char>::eof() and the character 0xFF do not
  3371. // end up as the same value, eg. 0xFFFFFFFF.
  3372. std::char_traits<char>::int_type get_character() override
  3373. {
  3374. auto res = sb.sbumpc();
  3375. // set eof manually, as we don't use the istream interface.
  3376. if (res == EOF)
  3377. {
  3378. is.clear(is.rdstate() | std::ios::eofbit);
  3379. }
  3380. return res;
  3381. }
  3382. private:
  3383. /// the associated input stream
  3384. std::istream& is;
  3385. std::streambuf& sb;
  3386. };
  3387. /// input adapter for buffer input
  3388. class input_buffer_adapter : public input_adapter_protocol
  3389. {
  3390. public:
  3391. JSON_HEDLEY_NON_NULL(2)
  3392. input_buffer_adapter(const char* b, const std::size_t l) noexcept
  3393. : cursor(b), limit(b + l)
  3394. {}
  3395. // delete because of pointer members
  3396. input_buffer_adapter(const input_buffer_adapter&) = delete;
  3397. input_buffer_adapter& operator=(input_buffer_adapter&) = delete;
  3398. input_buffer_adapter(input_buffer_adapter&&) = delete;
  3399. input_buffer_adapter& operator=(input_buffer_adapter&&) = delete;
  3400. ~input_buffer_adapter() override = default;
  3401. std::char_traits<char>::int_type get_character() noexcept override
  3402. {
  3403. if (JSON_HEDLEY_LIKELY(cursor < limit))
  3404. {
  3405. return std::char_traits<char>::to_int_type(*(cursor++));
  3406. }
  3407. return std::char_traits<char>::eof();
  3408. }
  3409. private:
  3410. /// pointer to the current character
  3411. const char* cursor;
  3412. /// pointer past the last character
  3413. const char* const limit;
  3414. };
  3415. template<typename WideStringType, size_t T>
  3416. struct wide_string_input_helper
  3417. {
  3418. // UTF-32
  3419. static void fill_buffer(const WideStringType& str,
  3420. size_t& current_wchar,
  3421. std::array<std::char_traits<char>::int_type, 4>& utf8_bytes,
  3422. size_t& utf8_bytes_index,
  3423. size_t& utf8_bytes_filled)
  3424. {
  3425. utf8_bytes_index = 0;
  3426. if (current_wchar == str.size())
  3427. {
  3428. utf8_bytes[0] = std::char_traits<char>::eof();
  3429. utf8_bytes_filled = 1;
  3430. }
  3431. else
  3432. {
  3433. // get the current character
  3434. const auto wc = static_cast<unsigned int>(str[current_wchar++]);
  3435. // UTF-32 to UTF-8 encoding
  3436. if (wc < 0x80)
  3437. {
  3438. utf8_bytes[0] = static_cast<std::char_traits<char>::int_type>(wc);
  3439. utf8_bytes_filled = 1;
  3440. }
  3441. else if (wc <= 0x7FF)
  3442. {
  3443. utf8_bytes[0] = static_cast<std::char_traits<char>::int_type>(0xC0u | ((wc >> 6u) & 0x1Fu));
  3444. utf8_bytes[1] = static_cast<std::char_traits<char>::int_type>(0x80u | (wc & 0x3Fu));
  3445. utf8_bytes_filled = 2;
  3446. }
  3447. else if (wc <= 0xFFFF)
  3448. {
  3449. utf8_bytes[0] = static_cast<std::char_traits<char>::int_type>(0xE0u | ((wc >> 12u) & 0x0Fu));
  3450. utf8_bytes[1] = static_cast<std::char_traits<char>::int_type>(0x80u | ((wc >> 6u) & 0x3Fu));
  3451. utf8_bytes[2] = static_cast<std::char_traits<char>::int_type>(0x80u | (wc & 0x3Fu));
  3452. utf8_bytes_filled = 3;
  3453. }
  3454. else if (wc <= 0x10FFFF)
  3455. {
  3456. utf8_bytes[0] = static_cast<std::char_traits<char>::int_type>(0xF0u | ((wc >> 18u) & 0x07u));
  3457. utf8_bytes[1] = static_cast<std::char_traits<char>::int_type>(0x80u | ((wc >> 12u) & 0x3Fu));
  3458. utf8_bytes[2] = static_cast<std::char_traits<char>::int_type>(0x80u | ((wc >> 6u) & 0x3Fu));
  3459. utf8_bytes[3] = static_cast<std::char_traits<char>::int_type>(0x80u | (wc & 0x3Fu));
  3460. utf8_bytes_filled = 4;
  3461. }
  3462. else
  3463. {
  3464. // unknown character
  3465. utf8_bytes[0] = static_cast<std::char_traits<char>::int_type>(wc);
  3466. utf8_bytes_filled = 1;
  3467. }
  3468. }
  3469. }
  3470. };
  3471. template<typename WideStringType>
  3472. struct wide_string_input_helper<WideStringType, 2>
  3473. {
  3474. // UTF-16
  3475. static void fill_buffer(const WideStringType& str,
  3476. size_t& current_wchar,
  3477. std::array<std::char_traits<char>::int_type, 4>& utf8_bytes,
  3478. size_t& utf8_bytes_index,
  3479. size_t& utf8_bytes_filled)
  3480. {
  3481. utf8_bytes_index = 0;
  3482. if (current_wchar == str.size())
  3483. {
  3484. utf8_bytes[0] = std::char_traits<char>::eof();
  3485. utf8_bytes_filled = 1;
  3486. }
  3487. else
  3488. {
  3489. // get the current character
  3490. const auto wc = static_cast<unsigned int>(str[current_wchar++]);
  3491. // UTF-16 to UTF-8 encoding
  3492. if (wc < 0x80)
  3493. {
  3494. utf8_bytes[0] = static_cast<std::char_traits<char>::int_type>(wc);
  3495. utf8_bytes_filled = 1;
  3496. }
  3497. else if (wc <= 0x7FF)
  3498. {
  3499. utf8_bytes[0] = static_cast<std::char_traits<char>::int_type>(0xC0u | ((wc >> 6u)));
  3500. utf8_bytes[1] = static_cast<std::char_traits<char>::int_type>(0x80u | (wc & 0x3Fu));
  3501. utf8_bytes_filled = 2;
  3502. }
  3503. else if (0xD800 > wc or wc >= 0xE000)
  3504. {
  3505. utf8_bytes[0] = static_cast<std::char_traits<char>::int_type>(0xE0u | ((wc >> 12u)));
  3506. utf8_bytes[1] = static_cast<std::char_traits<char>::int_type>(0x80u | ((wc >> 6u) & 0x3Fu));
  3507. utf8_bytes[2] = static_cast<std::char_traits<char>::int_type>(0x80u | (wc & 0x3Fu));
  3508. utf8_bytes_filled = 3;
  3509. }
  3510. else
  3511. {
  3512. if (current_wchar < str.size())
  3513. {
  3514. const auto wc2 = static_cast<unsigned int>(str[current_wchar++]);
  3515. const auto charcode = 0x10000u + (((wc & 0x3FFu) << 10u) | (wc2 & 0x3FFu));
  3516. utf8_bytes[0] = static_cast<std::char_traits<char>::int_type>(0xF0u | (charcode >> 18u));
  3517. utf8_bytes[1] = static_cast<std::char_traits<char>::int_type>(0x80u | ((charcode >> 12u) & 0x3Fu));
  3518. utf8_bytes[2] = static_cast<std::char_traits<char>::int_type>(0x80u | ((charcode >> 6u) & 0x3Fu));
  3519. utf8_bytes[3] = static_cast<std::char_traits<char>::int_type>(0x80u | (charcode & 0x3Fu));
  3520. utf8_bytes_filled = 4;
  3521. }
  3522. else
  3523. {
  3524. // unknown character
  3525. ++current_wchar;
  3526. utf8_bytes[0] = static_cast<std::char_traits<char>::int_type>(wc);
  3527. utf8_bytes_filled = 1;
  3528. }
  3529. }
  3530. }
  3531. }
  3532. };
  3533. template<typename WideStringType>
  3534. class wide_string_input_adapter : public input_adapter_protocol
  3535. {
  3536. public:
  3537. explicit wide_string_input_adapter(const WideStringType& w) noexcept
  3538. : str(w)
  3539. {}
  3540. std::char_traits<char>::int_type get_character() noexcept override
  3541. {
  3542. // check if buffer needs to be filled
  3543. if (utf8_bytes_index == utf8_bytes_filled)
  3544. {
  3545. fill_buffer<sizeof(typename WideStringType::value_type)>();
  3546. assert(utf8_bytes_filled > 0);
  3547. assert(utf8_bytes_index == 0);
  3548. }
  3549. // use buffer
  3550. assert(utf8_bytes_filled > 0);
  3551. assert(utf8_bytes_index < utf8_bytes_filled);
  3552. return utf8_bytes[utf8_bytes_index++];
  3553. }
  3554. private:
  3555. template<size_t T>
  3556. void fill_buffer()
  3557. {
  3558. wide_string_input_helper<WideStringType, T>::fill_buffer(str, current_wchar, utf8_bytes, utf8_bytes_index, utf8_bytes_filled);
  3559. }
  3560. /// the wstring to process
  3561. const WideStringType& str;
  3562. /// index of the current wchar in str
  3563. std::size_t current_wchar = 0;
  3564. /// a buffer for UTF-8 bytes
  3565. std::array<std::char_traits<char>::int_type, 4> utf8_bytes = {{0, 0, 0, 0}};
  3566. /// index to the utf8_codes array for the next valid byte
  3567. std::size_t utf8_bytes_index = 0;
  3568. /// number of valid bytes in the utf8_codes array
  3569. std::size_t utf8_bytes_filled = 0;
  3570. };
  3571. class input_adapter
  3572. {
  3573. public:
  3574. // native support
  3575. JSON_HEDLEY_NON_NULL(2)
  3576. input_adapter(std::FILE* file)
  3577. : ia(std::make_shared<file_input_adapter>(file)) {}
  3578. /// input adapter for input stream
  3579. input_adapter(std::istream& i)
  3580. : ia(std::make_shared<input_stream_adapter>(i)) {}
  3581. /// input adapter for input stream
  3582. input_adapter(std::istream&& i)
  3583. : ia(std::make_shared<input_stream_adapter>(i)) {}
  3584. input_adapter(const std::wstring& ws)
  3585. : ia(std::make_shared<wide_string_input_adapter<std::wstring>>(ws)) {}
  3586. input_adapter(const std::u16string& ws)
  3587. : ia(std::make_shared<wide_string_input_adapter<std::u16string>>(ws)) {}
  3588. input_adapter(const std::u32string& ws)
  3589. : ia(std::make_shared<wide_string_input_adapter<std::u32string>>(ws)) {}
  3590. /// input adapter for buffer
  3591. template<typename CharT,
  3592. typename std::enable_if<
  3593. std::is_pointer<CharT>::value and
  3594. std::is_integral<typename std::remove_pointer<CharT>::type>::value and
  3595. sizeof(typename std::remove_pointer<CharT>::type) == 1,
  3596. int>::type = 0>
  3597. input_adapter(CharT b, std::size_t l)
  3598. : ia(std::make_shared<input_buffer_adapter>(reinterpret_cast<const char*>(b), l)) {}
  3599. // derived support
  3600. /// input adapter for string literal
  3601. template<typename CharT,
  3602. typename std::enable_if<
  3603. std::is_pointer<CharT>::value and
  3604. std::is_integral<typename std::remove_pointer<CharT>::type>::value and
  3605. sizeof(typename std::remove_pointer<CharT>::type) == 1,
  3606. int>::type = 0>
  3607. input_adapter(CharT b)
  3608. : input_adapter(reinterpret_cast<const char*>(b),
  3609. std::strlen(reinterpret_cast<const char*>(b))) {}
  3610. /// input adapter for iterator range with contiguous storage
  3611. template<class IteratorType,
  3612. typename std::enable_if<
  3613. std::is_same<typename iterator_traits<IteratorType>::iterator_category, std::random_access_iterator_tag>::value,
  3614. int>::type = 0>
  3615. input_adapter(IteratorType first, IteratorType last)
  3616. {
  3617. #ifndef NDEBUG
  3618. // assertion to check that the iterator range is indeed contiguous,
  3619. // see http://stackoverflow.com/a/35008842/266378 for more discussion
  3620. const auto is_contiguous = std::accumulate(
  3621. first, last, std::pair<bool, int>(true, 0),
  3622. [&first](std::pair<bool, int> res, decltype(*first) val)
  3623. {
  3624. res.first &= (val == *(std::next(std::addressof(*first), res.second++)));
  3625. return res;
  3626. }).first;
  3627. assert(is_contiguous);
  3628. #endif
  3629. // assertion to check that each element is 1 byte long
  3630. static_assert(
  3631. sizeof(typename iterator_traits<IteratorType>::value_type) == 1,
  3632. "each element in the iterator range must have the size of 1 byte");
  3633. const auto len = static_cast<size_t>(std::distance(first, last));
  3634. if (JSON_HEDLEY_LIKELY(len > 0))
  3635. {
  3636. // there is at least one element: use the address of first
  3637. ia = std::make_shared<input_buffer_adapter>(reinterpret_cast<const char*>(&(*first)), len);
  3638. }
  3639. else
  3640. {
  3641. // the address of first cannot be used: use nullptr
  3642. ia = std::make_shared<input_buffer_adapter>(nullptr, len);
  3643. }
  3644. }
  3645. /// input adapter for array
  3646. template<class T, std::size_t N>
  3647. input_adapter(T (&array)[N])
  3648. : input_adapter(std::begin(array), std::end(array)) {}
  3649. /// input adapter for contiguous container
  3650. template<class ContiguousContainer, typename
  3651. std::enable_if<not std::is_pointer<ContiguousContainer>::value and
  3652. std::is_base_of<std::random_access_iterator_tag, typename iterator_traits<decltype(std::begin(std::declval<ContiguousContainer const>()))>::iterator_category>::value,
  3653. int>::type = 0>
  3654. input_adapter(const ContiguousContainer& c)
  3655. : input_adapter(std::begin(c), std::end(c)) {}
  3656. operator input_adapter_t()
  3657. {
  3658. return ia;
  3659. }
  3660. private:
  3661. /// the actual adapter
  3662. input_adapter_t ia = nullptr;
  3663. };
  3664. } // namespace detail
  3665. } // namespace nlohmann
  3666. // #include <nlohmann/detail/input/json_sax.hpp>
  3667. #include <cassert> // assert
  3668. #include <cstddef>
  3669. #include <string> // string
  3670. #include <utility> // move
  3671. #include <vector> // vector
  3672. // #include <nlohmann/detail/exceptions.hpp>
  3673. // #include <nlohmann/detail/macro_scope.hpp>
  3674. namespace nlohmann
  3675. {
  3676. /*!
  3677. @brief SAX interface
  3678. This class describes the SAX interface used by @ref nlohmann::json::sax_parse.
  3679. Each function is called in different situations while the input is parsed. The
  3680. boolean return value informs the parser whether to continue processing the
  3681. input.
  3682. */
  3683. template<typename BasicJsonType>
  3684. struct json_sax
  3685. {
  3686. /// type for (signed) integers
  3687. using number_integer_t = typename BasicJsonType::number_integer_t;
  3688. /// type for unsigned integers
  3689. using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
  3690. /// type for floating-point numbers
  3691. using number_float_t = typename BasicJsonType::number_float_t;
  3692. /// type for strings
  3693. using string_t = typename BasicJsonType::string_t;
  3694. /*!
  3695. @brief a null value was read
  3696. @return whether parsing should proceed
  3697. */
  3698. virtual bool null() = 0;
  3699. /*!
  3700. @brief a boolean value was read
  3701. @param[in] val boolean value
  3702. @return whether parsing should proceed
  3703. */
  3704. virtual bool boolean(bool val) = 0;
  3705. /*!
  3706. @brief an integer number was read
  3707. @param[in] val integer value
  3708. @return whether parsing should proceed
  3709. */
  3710. virtual bool number_integer(number_integer_t val) = 0;
  3711. /*!
  3712. @brief an unsigned integer number was read
  3713. @param[in] val unsigned integer value
  3714. @return whether parsing should proceed
  3715. */
  3716. virtual bool number_unsigned(number_unsigned_t val) = 0;
  3717. /*!
  3718. @brief an floating-point number was read
  3719. @param[in] val floating-point value
  3720. @param[in] s raw token value
  3721. @return whether parsing should proceed
  3722. */
  3723. virtual bool number_float(number_float_t val, const string_t& s) = 0;
  3724. /*!
  3725. @brief a string was read
  3726. @param[in] val string value
  3727. @return whether parsing should proceed
  3728. @note It is safe to move the passed string.
  3729. */
  3730. virtual bool string(string_t& val) = 0;
  3731. /*!
  3732. @brief the beginning of an object was read
  3733. @param[in] elements number of object elements or -1 if unknown
  3734. @return whether parsing should proceed
  3735. @note binary formats may report the number of elements
  3736. */
  3737. virtual bool start_object(std::size_t elements) = 0;
  3738. /*!
  3739. @brief an object key was read
  3740. @param[in] val object key
  3741. @return whether parsing should proceed
  3742. @note It is safe to move the passed string.
  3743. */
  3744. virtual bool key(string_t& val) = 0;
  3745. /*!
  3746. @brief the end of an object was read
  3747. @return whether parsing should proceed
  3748. */
  3749. virtual bool end_object() = 0;
  3750. /*!
  3751. @brief the beginning of an array was read
  3752. @param[in] elements number of array elements or -1 if unknown
  3753. @return whether parsing should proceed
  3754. @note binary formats may report the number of elements
  3755. */
  3756. virtual bool start_array(std::size_t elements) = 0;
  3757. /*!
  3758. @brief the end of an array was read
  3759. @return whether parsing should proceed
  3760. */
  3761. virtual bool end_array() = 0;
  3762. /*!
  3763. @brief a parse error occurred
  3764. @param[in] position the position in the input where the error occurs
  3765. @param[in] last_token the last read token
  3766. @param[in] ex an exception object describing the error
  3767. @return whether parsing should proceed (must return false)
  3768. */
  3769. virtual bool parse_error(std::size_t position,
  3770. const std::string& last_token,
  3771. const detail::exception& ex) = 0;
  3772. virtual ~json_sax() = default;
  3773. };
  3774. namespace detail
  3775. {
  3776. /*!
  3777. @brief SAX implementation to create a JSON value from SAX events
  3778. This class implements the @ref json_sax interface and processes the SAX events
  3779. to create a JSON value which makes it basically a DOM parser. The structure or
  3780. hierarchy of the JSON value is managed by the stack `ref_stack` which contains
  3781. a pointer to the respective array or object for each recursion depth.
  3782. After successful parsing, the value that is passed by reference to the
  3783. constructor contains the parsed value.
  3784. @tparam BasicJsonType the JSON type
  3785. */
  3786. template<typename BasicJsonType>
  3787. class json_sax_dom_parser
  3788. {
  3789. public:
  3790. using number_integer_t = typename BasicJsonType::number_integer_t;
  3791. using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
  3792. using number_float_t = typename BasicJsonType::number_float_t;
  3793. using string_t = typename BasicJsonType::string_t;
  3794. /*!
  3795. @param[in, out] r reference to a JSON value that is manipulated while
  3796. parsing
  3797. @param[in] allow_exceptions_ whether parse errors yield exceptions
  3798. */
  3799. explicit json_sax_dom_parser(BasicJsonType& r, const bool allow_exceptions_ = true)
  3800. : root(r), allow_exceptions(allow_exceptions_)
  3801. {}
  3802. // make class move-only
  3803. json_sax_dom_parser(const json_sax_dom_parser&) = delete;
  3804. json_sax_dom_parser(json_sax_dom_parser&&) = default;
  3805. json_sax_dom_parser& operator=(const json_sax_dom_parser&) = delete;
  3806. json_sax_dom_parser& operator=(json_sax_dom_parser&&) = default;
  3807. ~json_sax_dom_parser() = default;
  3808. bool null()
  3809. {
  3810. handle_value(nullptr);
  3811. return true;
  3812. }
  3813. bool boolean(bool val)
  3814. {
  3815. handle_value(val);
  3816. return true;
  3817. }
  3818. bool number_integer(number_integer_t val)
  3819. {
  3820. handle_value(val);
  3821. return true;
  3822. }
  3823. bool number_unsigned(number_unsigned_t val)
  3824. {
  3825. handle_value(val);
  3826. return true;
  3827. }
  3828. bool number_float(number_float_t val, const string_t& /*unused*/)
  3829. {
  3830. handle_value(val);
  3831. return true;
  3832. }
  3833. bool string(string_t& val)
  3834. {
  3835. handle_value(val);
  3836. return true;
  3837. }
  3838. bool start_object(std::size_t len)
  3839. {
  3840. ref_stack.push_back(handle_value(BasicJsonType::value_t::object));
  3841. if (JSON_HEDLEY_UNLIKELY(len != std::size_t(-1) and len > ref_stack.back()->max_size()))
  3842. {
  3843. JSON_THROW(out_of_range::create(408,
  3844. "excessive object size: " + std::to_string(len)));
  3845. }
  3846. return true;
  3847. }
  3848. bool key(string_t& val)
  3849. {
  3850. // add null at given key and store the reference for later
  3851. object_element = &(ref_stack.back()->m_value.object->operator[](val));
  3852. return true;
  3853. }
  3854. bool end_object()
  3855. {
  3856. ref_stack.pop_back();
  3857. return true;
  3858. }
  3859. bool start_array(std::size_t len)
  3860. {
  3861. ref_stack.push_back(handle_value(BasicJsonType::value_t::array));
  3862. if (JSON_HEDLEY_UNLIKELY(len != std::size_t(-1) and len > ref_stack.back()->max_size()))
  3863. {
  3864. JSON_THROW(out_of_range::create(408,
  3865. "excessive array size: " + std::to_string(len)));
  3866. }
  3867. return true;
  3868. }
  3869. bool end_array()
  3870. {
  3871. ref_stack.pop_back();
  3872. return true;
  3873. }
  3874. bool parse_error(std::size_t /*unused*/, const std::string& /*unused*/,
  3875. const detail::exception& ex)
  3876. {
  3877. errored = true;
  3878. if (allow_exceptions)
  3879. {
  3880. // determine the proper exception type from the id
  3881. switch ((ex.id / 100) % 100)
  3882. {
  3883. case 1:
  3884. JSON_THROW(*static_cast<const detail::parse_error*>(&ex));
  3885. case 4:
  3886. JSON_THROW(*static_cast<const detail::out_of_range*>(&ex));
  3887. // LCOV_EXCL_START
  3888. case 2:
  3889. JSON_THROW(*static_cast<const detail::invalid_iterator*>(&ex));
  3890. case 3:
  3891. JSON_THROW(*static_cast<const detail::type_error*>(&ex));
  3892. case 5:
  3893. JSON_THROW(*static_cast<const detail::other_error*>(&ex));
  3894. default:
  3895. assert(false);
  3896. // LCOV_EXCL_STOP
  3897. }
  3898. }
  3899. return false;
  3900. }
  3901. constexpr bool is_errored() const
  3902. {
  3903. return errored;
  3904. }
  3905. private:
  3906. /*!
  3907. @invariant If the ref stack is empty, then the passed value will be the new
  3908. root.
  3909. @invariant If the ref stack contains a value, then it is an array or an
  3910. object to which we can add elements
  3911. */
  3912. template<typename Value>
  3913. JSON_HEDLEY_RETURNS_NON_NULL
  3914. BasicJsonType* handle_value(Value&& v)
  3915. {
  3916. if (ref_stack.empty())
  3917. {
  3918. root = BasicJsonType(std::forward<Value>(v));
  3919. return &root;
  3920. }
  3921. assert(ref_stack.back()->is_array() or ref_stack.back()->is_object());
  3922. if (ref_stack.back()->is_array())
  3923. {
  3924. ref_stack.back()->m_value.array->emplace_back(std::forward<Value>(v));
  3925. return &(ref_stack.back()->m_value.array->back());
  3926. }
  3927. assert(ref_stack.back()->is_object());
  3928. assert(object_element);
  3929. *object_element = BasicJsonType(std::forward<Value>(v));
  3930. return object_element;
  3931. }
  3932. /// the parsed JSON value
  3933. BasicJsonType& root;
  3934. /// stack to model hierarchy of values
  3935. std::vector<BasicJsonType*> ref_stack {};
  3936. /// helper to hold the reference for the next object element
  3937. BasicJsonType* object_element = nullptr;
  3938. /// whether a syntax error occurred
  3939. bool errored = false;
  3940. /// whether to throw exceptions in case of errors
  3941. const bool allow_exceptions = true;
  3942. };
  3943. template<typename BasicJsonType>
  3944. class json_sax_dom_callback_parser
  3945. {
  3946. public:
  3947. using number_integer_t = typename BasicJsonType::number_integer_t;
  3948. using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
  3949. using number_float_t = typename BasicJsonType::number_float_t;
  3950. using string_t = typename BasicJsonType::string_t;
  3951. using parser_callback_t = typename BasicJsonType::parser_callback_t;
  3952. using parse_event_t = typename BasicJsonType::parse_event_t;
  3953. json_sax_dom_callback_parser(BasicJsonType& r,
  3954. const parser_callback_t cb,
  3955. const bool allow_exceptions_ = true)
  3956. : root(r), callback(cb), allow_exceptions(allow_exceptions_)
  3957. {
  3958. keep_stack.push_back(true);
  3959. }
  3960. // make class move-only
  3961. json_sax_dom_callback_parser(const json_sax_dom_callback_parser&) = delete;
  3962. json_sax_dom_callback_parser(json_sax_dom_callback_parser&&) = default;
  3963. json_sax_dom_callback_parser& operator=(const json_sax_dom_callback_parser&) = delete;
  3964. json_sax_dom_callback_parser& operator=(json_sax_dom_callback_parser&&) = default;
  3965. ~json_sax_dom_callback_parser() = default;
  3966. bool null()
  3967. {
  3968. handle_value(nullptr);
  3969. return true;
  3970. }
  3971. bool boolean(bool val)
  3972. {
  3973. handle_value(val);
  3974. return true;
  3975. }
  3976. bool number_integer(number_integer_t val)
  3977. {
  3978. handle_value(val);
  3979. return true;
  3980. }
  3981. bool number_unsigned(number_unsigned_t val)
  3982. {
  3983. handle_value(val);
  3984. return true;
  3985. }
  3986. bool number_float(number_float_t val, const string_t& /*unused*/)
  3987. {
  3988. handle_value(val);
  3989. return true;
  3990. }
  3991. bool string(string_t& val)
  3992. {
  3993. handle_value(val);
  3994. return true;
  3995. }
  3996. bool start_object(std::size_t len)
  3997. {
  3998. // check callback for object start
  3999. const bool keep = callback(static_cast<int>(ref_stack.size()), parse_event_t::object_start, discarded);
  4000. keep_stack.push_back(keep);
  4001. auto val = handle_value(BasicJsonType::value_t::object, true);
  4002. ref_stack.push_back(val.second);
  4003. // check object limit
  4004. if (ref_stack.back() and JSON_HEDLEY_UNLIKELY(len != std::size_t(-1) and len > ref_stack.back()->max_size()))
  4005. {
  4006. JSON_THROW(out_of_range::create(408, "excessive object size: " + std::to_string(len)));
  4007. }
  4008. return true;
  4009. }
  4010. bool key(string_t& val)
  4011. {
  4012. BasicJsonType k = BasicJsonType(val);
  4013. // check callback for key
  4014. const bool keep = callback(static_cast<int>(ref_stack.size()), parse_event_t::key, k);
  4015. key_keep_stack.push_back(keep);
  4016. // add discarded value at given key and store the reference for later
  4017. if (keep and ref_stack.back())
  4018. {
  4019. object_element = &(ref_stack.back()->m_value.object->operator[](val) = discarded);
  4020. }
  4021. return true;
  4022. }
  4023. bool end_object()
  4024. {
  4025. if (ref_stack.back() and not callback(static_cast<int>(ref_stack.size()) - 1, parse_event_t::object_end, *ref_stack.back()))
  4026. {
  4027. // discard object
  4028. *ref_stack.back() = discarded;
  4029. }
  4030. assert(not ref_stack.empty());
  4031. assert(not keep_stack.empty());
  4032. ref_stack.pop_back();
  4033. keep_stack.pop_back();
  4034. if (not ref_stack.empty() and ref_stack.back() and ref_stack.back()->is_object())
  4035. {
  4036. // remove discarded value
  4037. for (auto it = ref_stack.back()->begin(); it != ref_stack.back()->end(); ++it)
  4038. {
  4039. if (it->is_discarded())
  4040. {
  4041. ref_stack.back()->erase(it);
  4042. break;
  4043. }
  4044. }
  4045. }
  4046. return true;
  4047. }
  4048. bool start_array(std::size_t len)
  4049. {
  4050. const bool keep = callback(static_cast<int>(ref_stack.size()), parse_event_t::array_start, discarded);
  4051. keep_stack.push_back(keep);
  4052. auto val = handle_value(BasicJsonType::value_t::array, true);
  4053. ref_stack.push_back(val.second);
  4054. // check array limit
  4055. if (ref_stack.back() and JSON_HEDLEY_UNLIKELY(len != std::size_t(-1) and len > ref_stack.back()->max_size()))
  4056. {
  4057. JSON_THROW(out_of_range::create(408, "excessive array size: " + std::to_string(len)));
  4058. }
  4059. return true;
  4060. }
  4061. bool end_array()
  4062. {
  4063. bool keep = true;
  4064. if (ref_stack.back())
  4065. {
  4066. keep = callback(static_cast<int>(ref_stack.size()) - 1, parse_event_t::array_end, *ref_stack.back());
  4067. if (not keep)
  4068. {
  4069. // discard array
  4070. *ref_stack.back() = discarded;
  4071. }
  4072. }
  4073. assert(not ref_stack.empty());
  4074. assert(not keep_stack.empty());
  4075. ref_stack.pop_back();
  4076. keep_stack.pop_back();
  4077. // remove discarded value
  4078. if (not keep and not ref_stack.empty() and ref_stack.back()->is_array())
  4079. {
  4080. ref_stack.back()->m_value.array->pop_back();
  4081. }
  4082. return true;
  4083. }
  4084. bool parse_error(std::size_t /*unused*/, const std::string& /*unused*/,
  4085. const detail::exception& ex)
  4086. {
  4087. errored = true;
  4088. if (allow_exceptions)
  4089. {
  4090. // determine the proper exception type from the id
  4091. switch ((ex.id / 100) % 100)
  4092. {
  4093. case 1:
  4094. JSON_THROW(*static_cast<const detail::parse_error*>(&ex));
  4095. case 4:
  4096. JSON_THROW(*static_cast<const detail::out_of_range*>(&ex));
  4097. // LCOV_EXCL_START
  4098. case 2:
  4099. JSON_THROW(*static_cast<const detail::invalid_iterator*>(&ex));
  4100. case 3:
  4101. JSON_THROW(*static_cast<const detail::type_error*>(&ex));
  4102. case 5:
  4103. JSON_THROW(*static_cast<const detail::other_error*>(&ex));
  4104. default:
  4105. assert(false);
  4106. // LCOV_EXCL_STOP
  4107. }
  4108. }
  4109. return false;
  4110. }
  4111. constexpr bool is_errored() const
  4112. {
  4113. return errored;
  4114. }
  4115. private:
  4116. /*!
  4117. @param[in] v value to add to the JSON value we build during parsing
  4118. @param[in] skip_callback whether we should skip calling the callback
  4119. function; this is required after start_array() and
  4120. start_object() SAX events, because otherwise we would call the
  4121. callback function with an empty array or object, respectively.
  4122. @invariant If the ref stack is empty, then the passed value will be the new
  4123. root.
  4124. @invariant If the ref stack contains a value, then it is an array or an
  4125. object to which we can add elements
  4126. @return pair of boolean (whether value should be kept) and pointer (to the
  4127. passed value in the ref_stack hierarchy; nullptr if not kept)
  4128. */
  4129. template<typename Value>
  4130. std::pair<bool, BasicJsonType*> handle_value(Value&& v, const bool skip_callback = false)
  4131. {
  4132. assert(not keep_stack.empty());
  4133. // do not handle this value if we know it would be added to a discarded
  4134. // container
  4135. if (not keep_stack.back())
  4136. {
  4137. return {false, nullptr};
  4138. }
  4139. // create value
  4140. auto value = BasicJsonType(std::forward<Value>(v));
  4141. // check callback
  4142. const bool keep = skip_callback or callback(static_cast<int>(ref_stack.size()), parse_event_t::value, value);
  4143. // do not handle this value if we just learnt it shall be discarded
  4144. if (not keep)
  4145. {
  4146. return {false, nullptr};
  4147. }
  4148. if (ref_stack.empty())
  4149. {
  4150. root = std::move(value);
  4151. return {true, &root};
  4152. }
  4153. // skip this value if we already decided to skip the parent
  4154. // (https://github.com/nlohmann/json/issues/971#issuecomment-413678360)
  4155. if (not ref_stack.back())
  4156. {
  4157. return {false, nullptr};
  4158. }
  4159. // we now only expect arrays and objects
  4160. assert(ref_stack.back()->is_array() or ref_stack.back()->is_object());
  4161. // array
  4162. if (ref_stack.back()->is_array())
  4163. {
  4164. ref_stack.back()->m_value.array->push_back(std::move(value));
  4165. return {true, &(ref_stack.back()->m_value.array->back())};
  4166. }
  4167. // object
  4168. assert(ref_stack.back()->is_object());
  4169. // check if we should store an element for the current key
  4170. assert(not key_keep_stack.empty());
  4171. const bool store_element = key_keep_stack.back();
  4172. key_keep_stack.pop_back();
  4173. if (not store_element)
  4174. {
  4175. return {false, nullptr};
  4176. }
  4177. assert(object_element);
  4178. *object_element = std::move(value);
  4179. return {true, object_element};
  4180. }
  4181. /// the parsed JSON value
  4182. BasicJsonType& root;
  4183. /// stack to model hierarchy of values
  4184. std::vector<BasicJsonType*> ref_stack {};
  4185. /// stack to manage which values to keep
  4186. std::vector<bool> keep_stack {};
  4187. /// stack to manage which object keys to keep
  4188. std::vector<bool> key_keep_stack {};
  4189. /// helper to hold the reference for the next object element
  4190. BasicJsonType* object_element = nullptr;
  4191. /// whether a syntax error occurred
  4192. bool errored = false;
  4193. /// callback function
  4194. const parser_callback_t callback = nullptr;
  4195. /// whether to throw exceptions in case of errors
  4196. const bool allow_exceptions = true;
  4197. /// a discarded value for the callback
  4198. BasicJsonType discarded = BasicJsonType::value_t::discarded;
  4199. };
  4200. template<typename BasicJsonType>
  4201. class json_sax_acceptor
  4202. {
  4203. public:
  4204. using number_integer_t = typename BasicJsonType::number_integer_t;
  4205. using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
  4206. using number_float_t = typename BasicJsonType::number_float_t;
  4207. using string_t = typename BasicJsonType::string_t;
  4208. bool null()
  4209. {
  4210. return true;
  4211. }
  4212. bool boolean(bool /*unused*/)
  4213. {
  4214. return true;
  4215. }
  4216. bool number_integer(number_integer_t /*unused*/)
  4217. {
  4218. return true;
  4219. }
  4220. bool number_unsigned(number_unsigned_t /*unused*/)
  4221. {
  4222. return true;
  4223. }
  4224. bool number_float(number_float_t /*unused*/, const string_t& /*unused*/)
  4225. {
  4226. return true;
  4227. }
  4228. bool string(string_t& /*unused*/)
  4229. {
  4230. return true;
  4231. }
  4232. bool start_object(std::size_t /*unused*/ = std::size_t(-1))
  4233. {
  4234. return true;
  4235. }
  4236. bool key(string_t& /*unused*/)
  4237. {
  4238. return true;
  4239. }
  4240. bool end_object()
  4241. {
  4242. return true;
  4243. }
  4244. bool start_array(std::size_t /*unused*/ = std::size_t(-1))
  4245. {
  4246. return true;
  4247. }
  4248. bool end_array()
  4249. {
  4250. return true;
  4251. }
  4252. bool parse_error(std::size_t /*unused*/, const std::string& /*unused*/, const detail::exception& /*unused*/)
  4253. {
  4254. return false;
  4255. }
  4256. };
  4257. } // namespace detail
  4258. } // namespace nlohmann
  4259. // #include <nlohmann/detail/macro_scope.hpp>
  4260. // #include <nlohmann/detail/meta/is_sax.hpp>
  4261. #include <cstdint> // size_t
  4262. #include <utility> // declval
  4263. #include <string> // string
  4264. // #include <nlohmann/detail/meta/detected.hpp>
  4265. // #include <nlohmann/detail/meta/type_traits.hpp>
  4266. namespace nlohmann
  4267. {
  4268. namespace detail
  4269. {
  4270. template <typename T>
  4271. using null_function_t = decltype(std::declval<T&>().null());
  4272. template <typename T>
  4273. using boolean_function_t =
  4274. decltype(std::declval<T&>().boolean(std::declval<bool>()));
  4275. template <typename T, typename Integer>
  4276. using number_integer_function_t =
  4277. decltype(std::declval<T&>().number_integer(std::declval<Integer>()));
  4278. template <typename T, typename Unsigned>
  4279. using number_unsigned_function_t =
  4280. decltype(std::declval<T&>().number_unsigned(std::declval<Unsigned>()));
  4281. template <typename T, typename Float, typename String>
  4282. using number_float_function_t = decltype(std::declval<T&>().number_float(
  4283. std::declval<Float>(), std::declval<const String&>()));
  4284. template <typename T, typename String>
  4285. using string_function_t =
  4286. decltype(std::declval<T&>().string(std::declval<String&>()));
  4287. template <typename T>
  4288. using start_object_function_t =
  4289. decltype(std::declval<T&>().start_object(std::declval<std::size_t>()));
  4290. template <typename T, typename String>
  4291. using key_function_t =
  4292. decltype(std::declval<T&>().key(std::declval<String&>()));
  4293. template <typename T>
  4294. using end_object_function_t = decltype(std::declval<T&>().end_object());
  4295. template <typename T>
  4296. using start_array_function_t =
  4297. decltype(std::declval<T&>().start_array(std::declval<std::size_t>()));
  4298. template <typename T>
  4299. using end_array_function_t = decltype(std::declval<T&>().end_array());
  4300. template <typename T, typename Exception>
  4301. using parse_error_function_t = decltype(std::declval<T&>().parse_error(
  4302. std::declval<std::size_t>(), std::declval<const std::string&>(),
  4303. std::declval<const Exception&>()));
  4304. template <typename SAX, typename BasicJsonType>
  4305. struct is_sax
  4306. {
  4307. private:
  4308. static_assert(is_basic_json<BasicJsonType>::value,
  4309. "BasicJsonType must be of type basic_json<...>");
  4310. using number_integer_t = typename BasicJsonType::number_integer_t;
  4311. using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
  4312. using number_float_t = typename BasicJsonType::number_float_t;
  4313. using string_t = typename BasicJsonType::string_t;
  4314. using exception_t = typename BasicJsonType::exception;
  4315. public:
  4316. static constexpr bool value =
  4317. is_detected_exact<bool, null_function_t, SAX>::value &&
  4318. is_detected_exact<bool, boolean_function_t, SAX>::value &&
  4319. is_detected_exact<bool, number_integer_function_t, SAX,
  4320. number_integer_t>::value &&
  4321. is_detected_exact<bool, number_unsigned_function_t, SAX,
  4322. number_unsigned_t>::value &&
  4323. is_detected_exact<bool, number_float_function_t, SAX, number_float_t,
  4324. string_t>::value &&
  4325. is_detected_exact<bool, string_function_t, SAX, string_t>::value &&
  4326. is_detected_exact<bool, start_object_function_t, SAX>::value &&
  4327. is_detected_exact<bool, key_function_t, SAX, string_t>::value &&
  4328. is_detected_exact<bool, end_object_function_t, SAX>::value &&
  4329. is_detected_exact<bool, start_array_function_t, SAX>::value &&
  4330. is_detected_exact<bool, end_array_function_t, SAX>::value &&
  4331. is_detected_exact<bool, parse_error_function_t, SAX, exception_t>::value;
  4332. };
  4333. template <typename SAX, typename BasicJsonType>
  4334. struct is_sax_static_asserts
  4335. {
  4336. private:
  4337. static_assert(is_basic_json<BasicJsonType>::value,
  4338. "BasicJsonType must be of type basic_json<...>");
  4339. using number_integer_t = typename BasicJsonType::number_integer_t;
  4340. using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
  4341. using number_float_t = typename BasicJsonType::number_float_t;
  4342. using string_t = typename BasicJsonType::string_t;
  4343. using exception_t = typename BasicJsonType::exception;
  4344. public:
  4345. static_assert(is_detected_exact<bool, null_function_t, SAX>::value,
  4346. "Missing/invalid function: bool null()");
  4347. static_assert(is_detected_exact<bool, boolean_function_t, SAX>::value,
  4348. "Missing/invalid function: bool boolean(bool)");
  4349. static_assert(is_detected_exact<bool, boolean_function_t, SAX>::value,
  4350. "Missing/invalid function: bool boolean(bool)");
  4351. static_assert(
  4352. is_detected_exact<bool, number_integer_function_t, SAX,
  4353. number_integer_t>::value,
  4354. "Missing/invalid function: bool number_integer(number_integer_t)");
  4355. static_assert(
  4356. is_detected_exact<bool, number_unsigned_function_t, SAX,
  4357. number_unsigned_t>::value,
  4358. "Missing/invalid function: bool number_unsigned(number_unsigned_t)");
  4359. static_assert(is_detected_exact<bool, number_float_function_t, SAX,
  4360. number_float_t, string_t>::value,
  4361. "Missing/invalid function: bool number_float(number_float_t, const string_t&)");
  4362. static_assert(
  4363. is_detected_exact<bool, string_function_t, SAX, string_t>::value,
  4364. "Missing/invalid function: bool string(string_t&)");
  4365. static_assert(is_detected_exact<bool, start_object_function_t, SAX>::value,
  4366. "Missing/invalid function: bool start_object(std::size_t)");
  4367. static_assert(is_detected_exact<bool, key_function_t, SAX, string_t>::value,
  4368. "Missing/invalid function: bool key(string_t&)");
  4369. static_assert(is_detected_exact<bool, end_object_function_t, SAX>::value,
  4370. "Missing/invalid function: bool end_object()");
  4371. static_assert(is_detected_exact<bool, start_array_function_t, SAX>::value,
  4372. "Missing/invalid function: bool start_array(std::size_t)");
  4373. static_assert(is_detected_exact<bool, end_array_function_t, SAX>::value,
  4374. "Missing/invalid function: bool end_array()");
  4375. static_assert(
  4376. is_detected_exact<bool, parse_error_function_t, SAX, exception_t>::value,
  4377. "Missing/invalid function: bool parse_error(std::size_t, const "
  4378. "std::string&, const exception&)");
  4379. };
  4380. } // namespace detail
  4381. } // namespace nlohmann
  4382. // #include <nlohmann/detail/value_t.hpp>
  4383. namespace nlohmann
  4384. {
  4385. namespace detail
  4386. {
  4387. ///////////////////
  4388. // binary reader //
  4389. ///////////////////
  4390. /*!
  4391. @brief deserialization of CBOR, MessagePack, and UBJSON values
  4392. */
  4393. template<typename BasicJsonType, typename SAX = json_sax_dom_parser<BasicJsonType>>
  4394. class binary_reader
  4395. {
  4396. using number_integer_t = typename BasicJsonType::number_integer_t;
  4397. using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
  4398. using number_float_t = typename BasicJsonType::number_float_t;
  4399. using string_t = typename BasicJsonType::string_t;
  4400. using json_sax_t = SAX;
  4401. public:
  4402. /*!
  4403. @brief create a binary reader
  4404. @param[in] adapter input adapter to read from
  4405. */
  4406. explicit binary_reader(input_adapter_t adapter) : ia(std::move(adapter))
  4407. {
  4408. (void)detail::is_sax_static_asserts<SAX, BasicJsonType> {};
  4409. assert(ia);
  4410. }
  4411. // make class move-only
  4412. binary_reader(const binary_reader&) = delete;
  4413. binary_reader(binary_reader&&) = default;
  4414. binary_reader& operator=(const binary_reader&) = delete;
  4415. binary_reader& operator=(binary_reader&&) = default;
  4416. ~binary_reader() = default;
  4417. /*!
  4418. @param[in] format the binary format to parse
  4419. @param[in] sax_ a SAX event processor
  4420. @param[in] strict whether to expect the input to be consumed completed
  4421. @return
  4422. */
  4423. JSON_HEDLEY_NON_NULL(3)
  4424. bool sax_parse(const input_format_t format,
  4425. json_sax_t* sax_,
  4426. const bool strict = true)
  4427. {
  4428. sax = sax_;
  4429. bool result = false;
  4430. switch (format)
  4431. {
  4432. case input_format_t::bson:
  4433. result = parse_bson_internal();
  4434. break;
  4435. case input_format_t::cbor:
  4436. result = parse_cbor_internal();
  4437. break;
  4438. case input_format_t::msgpack:
  4439. result = parse_msgpack_internal();
  4440. break;
  4441. case input_format_t::ubjson:
  4442. result = parse_ubjson_internal();
  4443. break;
  4444. default: // LCOV_EXCL_LINE
  4445. assert(false); // LCOV_EXCL_LINE
  4446. }
  4447. // strict mode: next byte must be EOF
  4448. if (result and strict)
  4449. {
  4450. if (format == input_format_t::ubjson)
  4451. {
  4452. get_ignore_noop();
  4453. }
  4454. else
  4455. {
  4456. get();
  4457. }
  4458. if (JSON_HEDLEY_UNLIKELY(current != std::char_traits<char>::eof()))
  4459. {
  4460. return sax->parse_error(chars_read, get_token_string(),
  4461. parse_error::create(110, chars_read, exception_message(format, "expected end of input; last byte: 0x" + get_token_string(), "value")));
  4462. }
  4463. }
  4464. return result;
  4465. }
  4466. /*!
  4467. @brief determine system byte order
  4468. @return true if and only if system's byte order is little endian
  4469. @note from http://stackoverflow.com/a/1001328/266378
  4470. */
  4471. static constexpr bool little_endianess(int num = 1) noexcept
  4472. {
  4473. return *reinterpret_cast<char*>(&num) == 1;
  4474. }
  4475. private:
  4476. //////////
  4477. // BSON //
  4478. //////////
  4479. /*!
  4480. @brief Reads in a BSON-object and passes it to the SAX-parser.
  4481. @return whether a valid BSON-value was passed to the SAX parser
  4482. */
  4483. bool parse_bson_internal()
  4484. {
  4485. std::int32_t document_size;
  4486. get_number<std::int32_t, true>(input_format_t::bson, document_size);
  4487. if (JSON_HEDLEY_UNLIKELY(not sax->start_object(std::size_t(-1))))
  4488. {
  4489. return false;
  4490. }
  4491. if (JSON_HEDLEY_UNLIKELY(not parse_bson_element_list(/*is_array*/false)))
  4492. {
  4493. return false;
  4494. }
  4495. return sax->end_object();
  4496. }
  4497. /*!
  4498. @brief Parses a C-style string from the BSON input.
  4499. @param[in, out] result A reference to the string variable where the read
  4500. string is to be stored.
  4501. @return `true` if the \x00-byte indicating the end of the string was
  4502. encountered before the EOF; false` indicates an unexpected EOF.
  4503. */
  4504. bool get_bson_cstr(string_t& result)
  4505. {
  4506. auto out = std::back_inserter(result);
  4507. while (true)
  4508. {
  4509. get();
  4510. if (JSON_HEDLEY_UNLIKELY(not unexpect_eof(input_format_t::bson, "cstring")))
  4511. {
  4512. return false;
  4513. }
  4514. if (current == 0x00)
  4515. {
  4516. return true;
  4517. }
  4518. *out++ = static_cast<char>(current);
  4519. }
  4520. return true;
  4521. }
  4522. /*!
  4523. @brief Parses a zero-terminated string of length @a len from the BSON
  4524. input.
  4525. @param[in] len The length (including the zero-byte at the end) of the
  4526. string to be read.
  4527. @param[in, out] result A reference to the string variable where the read
  4528. string is to be stored.
  4529. @tparam NumberType The type of the length @a len
  4530. @pre len >= 1
  4531. @return `true` if the string was successfully parsed
  4532. */
  4533. template<typename NumberType>
  4534. bool get_bson_string(const NumberType len, string_t& result)
  4535. {
  4536. if (JSON_HEDLEY_UNLIKELY(len < 1))
  4537. {
  4538. auto last_token = get_token_string();
  4539. 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")));
  4540. }
  4541. return get_string(input_format_t::bson, len - static_cast<NumberType>(1), result) and get() != std::char_traits<char>::eof();
  4542. }
  4543. /*!
  4544. @brief Read a BSON document element of the given @a element_type.
  4545. @param[in] element_type The BSON element type, c.f. http://bsonspec.org/spec.html
  4546. @param[in] element_type_parse_position The position in the input stream,
  4547. where the `element_type` was read.
  4548. @warning Not all BSON element types are supported yet. An unsupported
  4549. @a element_type will give rise to a parse_error.114:
  4550. Unsupported BSON record type 0x...
  4551. @return whether a valid BSON-object/array was passed to the SAX parser
  4552. */
  4553. bool parse_bson_element_internal(const int element_type,
  4554. const std::size_t element_type_parse_position)
  4555. {
  4556. switch (element_type)
  4557. {
  4558. case 0x01: // double
  4559. {
  4560. double number;
  4561. return get_number<double, true>(input_format_t::bson, number) and sax->number_float(static_cast<number_float_t>(number), "");
  4562. }
  4563. case 0x02: // string
  4564. {
  4565. std::int32_t len;
  4566. string_t value;
  4567. return get_number<std::int32_t, true>(input_format_t::bson, len) and get_bson_string(len, value) and sax->string(value);
  4568. }
  4569. case 0x03: // object
  4570. {
  4571. return parse_bson_internal();
  4572. }
  4573. case 0x04: // array
  4574. {
  4575. return parse_bson_array();
  4576. }
  4577. case 0x08: // boolean
  4578. {
  4579. return sax->boolean(get() != 0);
  4580. }
  4581. case 0x0A: // null
  4582. {
  4583. return sax->null();
  4584. }
  4585. case 0x10: // int32
  4586. {
  4587. std::int32_t value;
  4588. return get_number<std::int32_t, true>(input_format_t::bson, value) and sax->number_integer(value);
  4589. }
  4590. case 0x12: // int64
  4591. {
  4592. std::int64_t value;
  4593. return get_number<std::int64_t, true>(input_format_t::bson, value) and sax->number_integer(value);
  4594. }
  4595. default: // anything else not supported (yet)
  4596. {
  4597. std::array<char, 3> cr{{}};
  4598. (std::snprintf)(cr.data(), cr.size(), "%.2hhX", static_cast<unsigned char>(element_type));
  4599. 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())));
  4600. }
  4601. }
  4602. }
  4603. /*!
  4604. @brief Read a BSON element list (as specified in the BSON-spec)
  4605. The same binary layout is used for objects and arrays, hence it must be
  4606. indicated with the argument @a is_array which one is expected
  4607. (true --> array, false --> object).
  4608. @param[in] is_array Determines if the element list being read is to be
  4609. treated as an object (@a is_array == false), or as an
  4610. array (@a is_array == true).
  4611. @return whether a valid BSON-object/array was passed to the SAX parser
  4612. */
  4613. bool parse_bson_element_list(const bool is_array)
  4614. {
  4615. string_t key;
  4616. while (int element_type = get())
  4617. {
  4618. if (JSON_HEDLEY_UNLIKELY(not unexpect_eof(input_format_t::bson, "element list")))
  4619. {
  4620. return false;
  4621. }
  4622. const std::size_t element_type_parse_position = chars_read;
  4623. if (JSON_HEDLEY_UNLIKELY(not get_bson_cstr(key)))
  4624. {
  4625. return false;
  4626. }
  4627. if (not is_array and not sax->key(key))
  4628. {
  4629. return false;
  4630. }
  4631. if (JSON_HEDLEY_UNLIKELY(not parse_bson_element_internal(element_type, element_type_parse_position)))
  4632. {
  4633. return false;
  4634. }
  4635. // get_bson_cstr only appends
  4636. key.clear();
  4637. }
  4638. return true;
  4639. }
  4640. /*!
  4641. @brief Reads an array from the BSON input and passes it to the SAX-parser.
  4642. @return whether a valid BSON-array was passed to the SAX parser
  4643. */
  4644. bool parse_bson_array()
  4645. {
  4646. std::int32_t document_size;
  4647. get_number<std::int32_t, true>(input_format_t::bson, document_size);
  4648. if (JSON_HEDLEY_UNLIKELY(not sax->start_array(std::size_t(-1))))
  4649. {
  4650. return false;
  4651. }
  4652. if (JSON_HEDLEY_UNLIKELY(not parse_bson_element_list(/*is_array*/true)))
  4653. {
  4654. return false;
  4655. }
  4656. return sax->end_array();
  4657. }
  4658. //////////
  4659. // CBOR //
  4660. //////////
  4661. /*!
  4662. @param[in] get_char whether a new character should be retrieved from the
  4663. input (true, default) or whether the last read
  4664. character should be considered instead
  4665. @return whether a valid CBOR value was passed to the SAX parser
  4666. */
  4667. bool parse_cbor_internal(const bool get_char = true)
  4668. {
  4669. switch (get_char ? get() : current)
  4670. {
  4671. // EOF
  4672. case std::char_traits<char>::eof():
  4673. return unexpect_eof(input_format_t::cbor, "value");
  4674. // Integer 0x00..0x17 (0..23)
  4675. case 0x00:
  4676. case 0x01:
  4677. case 0x02:
  4678. case 0x03:
  4679. case 0x04:
  4680. case 0x05:
  4681. case 0x06:
  4682. case 0x07:
  4683. case 0x08:
  4684. case 0x09:
  4685. case 0x0A:
  4686. case 0x0B:
  4687. case 0x0C:
  4688. case 0x0D:
  4689. case 0x0E:
  4690. case 0x0F:
  4691. case 0x10:
  4692. case 0x11:
  4693. case 0x12:
  4694. case 0x13:
  4695. case 0x14:
  4696. case 0x15:
  4697. case 0x16:
  4698. case 0x17:
  4699. return sax->number_unsigned(static_cast<number_unsigned_t>(current));
  4700. case 0x18: // Unsigned integer (one-byte uint8_t follows)
  4701. {
  4702. std::uint8_t number;
  4703. return get_number(input_format_t::cbor, number) and sax->number_unsigned(number);
  4704. }
  4705. case 0x19: // Unsigned integer (two-byte uint16_t follows)
  4706. {
  4707. std::uint16_t number;
  4708. return get_number(input_format_t::cbor, number) and sax->number_unsigned(number);
  4709. }
  4710. case 0x1A: // Unsigned integer (four-byte uint32_t follows)
  4711. {
  4712. std::uint32_t number;
  4713. return get_number(input_format_t::cbor, number) and sax->number_unsigned(number);
  4714. }
  4715. case 0x1B: // Unsigned integer (eight-byte uint64_t follows)
  4716. {
  4717. std::uint64_t number;
  4718. return get_number(input_format_t::cbor, number) and sax->number_unsigned(number);
  4719. }
  4720. // Negative integer -1-0x00..-1-0x17 (-1..-24)
  4721. case 0x20:
  4722. case 0x21:
  4723. case 0x22:
  4724. case 0x23:
  4725. case 0x24:
  4726. case 0x25:
  4727. case 0x26:
  4728. case 0x27:
  4729. case 0x28:
  4730. case 0x29:
  4731. case 0x2A:
  4732. case 0x2B:
  4733. case 0x2C:
  4734. case 0x2D:
  4735. case 0x2E:
  4736. case 0x2F:
  4737. case 0x30:
  4738. case 0x31:
  4739. case 0x32:
  4740. case 0x33:
  4741. case 0x34:
  4742. case 0x35:
  4743. case 0x36:
  4744. case 0x37:
  4745. return sax->number_integer(static_cast<std::int8_t>(0x20 - 1 - current));
  4746. case 0x38: // Negative integer (one-byte uint8_t follows)
  4747. {
  4748. std::uint8_t number;
  4749. return get_number(input_format_t::cbor, number) and sax->number_integer(static_cast<number_integer_t>(-1) - number);
  4750. }
  4751. case 0x39: // Negative integer -1-n (two-byte uint16_t follows)
  4752. {
  4753. std::uint16_t number;
  4754. return get_number(input_format_t::cbor, number) and sax->number_integer(static_cast<number_integer_t>(-1) - number);
  4755. }
  4756. case 0x3A: // Negative integer -1-n (four-byte uint32_t follows)
  4757. {
  4758. std::uint32_t number;
  4759. return get_number(input_format_t::cbor, number) and sax->number_integer(static_cast<number_integer_t>(-1) - number);
  4760. }
  4761. case 0x3B: // Negative integer -1-n (eight-byte uint64_t follows)
  4762. {
  4763. std::uint64_t number;
  4764. return get_number(input_format_t::cbor, number) and sax->number_integer(static_cast<number_integer_t>(-1)
  4765. - static_cast<number_integer_t>(number));
  4766. }
  4767. // UTF-8 string (0x00..0x17 bytes follow)
  4768. case 0x60:
  4769. case 0x61:
  4770. case 0x62:
  4771. case 0x63:
  4772. case 0x64:
  4773. case 0x65:
  4774. case 0x66:
  4775. case 0x67:
  4776. case 0x68:
  4777. case 0x69:
  4778. case 0x6A:
  4779. case 0x6B:
  4780. case 0x6C:
  4781. case 0x6D:
  4782. case 0x6E:
  4783. case 0x6F:
  4784. case 0x70:
  4785. case 0x71:
  4786. case 0x72:
  4787. case 0x73:
  4788. case 0x74:
  4789. case 0x75:
  4790. case 0x76:
  4791. case 0x77:
  4792. case 0x78: // UTF-8 string (one-byte uint8_t for n follows)
  4793. case 0x79: // UTF-8 string (two-byte uint16_t for n follow)
  4794. case 0x7A: // UTF-8 string (four-byte uint32_t for n follow)
  4795. case 0x7B: // UTF-8 string (eight-byte uint64_t for n follow)
  4796. case 0x7F: // UTF-8 string (indefinite length)
  4797. {
  4798. string_t s;
  4799. return get_cbor_string(s) and sax->string(s);
  4800. }
  4801. // array (0x00..0x17 data items follow)
  4802. case 0x80:
  4803. case 0x81:
  4804. case 0x82:
  4805. case 0x83:
  4806. case 0x84:
  4807. case 0x85:
  4808. case 0x86:
  4809. case 0x87:
  4810. case 0x88:
  4811. case 0x89:
  4812. case 0x8A:
  4813. case 0x8B:
  4814. case 0x8C:
  4815. case 0x8D:
  4816. case 0x8E:
  4817. case 0x8F:
  4818. case 0x90:
  4819. case 0x91:
  4820. case 0x92:
  4821. case 0x93:
  4822. case 0x94:
  4823. case 0x95:
  4824. case 0x96:
  4825. case 0x97:
  4826. return get_cbor_array(static_cast<std::size_t>(static_cast<unsigned int>(current) & 0x1Fu));
  4827. case 0x98: // array (one-byte uint8_t for n follows)
  4828. {
  4829. std::uint8_t len;
  4830. return get_number(input_format_t::cbor, len) and get_cbor_array(static_cast<std::size_t>(len));
  4831. }
  4832. case 0x99: // array (two-byte uint16_t for n follow)
  4833. {
  4834. std::uint16_t len;
  4835. return get_number(input_format_t::cbor, len) and get_cbor_array(static_cast<std::size_t>(len));
  4836. }
  4837. case 0x9A: // array (four-byte uint32_t for n follow)
  4838. {
  4839. std::uint32_t len;
  4840. return get_number(input_format_t::cbor, len) and get_cbor_array(static_cast<std::size_t>(len));
  4841. }
  4842. case 0x9B: // array (eight-byte uint64_t for n follow)
  4843. {
  4844. std::uint64_t len;
  4845. return get_number(input_format_t::cbor, len) and get_cbor_array(static_cast<std::size_t>(len));
  4846. }
  4847. case 0x9F: // array (indefinite length)
  4848. return get_cbor_array(std::size_t(-1));
  4849. // map (0x00..0x17 pairs of data items follow)
  4850. case 0xA0:
  4851. case 0xA1:
  4852. case 0xA2:
  4853. case 0xA3:
  4854. case 0xA4:
  4855. case 0xA5:
  4856. case 0xA6:
  4857. case 0xA7:
  4858. case 0xA8:
  4859. case 0xA9:
  4860. case 0xAA:
  4861. case 0xAB:
  4862. case 0xAC:
  4863. case 0xAD:
  4864. case 0xAE:
  4865. case 0xAF:
  4866. case 0xB0:
  4867. case 0xB1:
  4868. case 0xB2:
  4869. case 0xB3:
  4870. case 0xB4:
  4871. case 0xB5:
  4872. case 0xB6:
  4873. case 0xB7:
  4874. return get_cbor_object(static_cast<std::size_t>(static_cast<unsigned int>(current) & 0x1Fu));
  4875. case 0xB8: // map (one-byte uint8_t for n follows)
  4876. {
  4877. std::uint8_t len;
  4878. return get_number(input_format_t::cbor, len) and get_cbor_object(static_cast<std::size_t>(len));
  4879. }
  4880. case 0xB9: // map (two-byte uint16_t for n follow)
  4881. {
  4882. std::uint16_t len;
  4883. return get_number(input_format_t::cbor, len) and get_cbor_object(static_cast<std::size_t>(len));
  4884. }
  4885. case 0xBA: // map (four-byte uint32_t for n follow)
  4886. {
  4887. std::uint32_t len;
  4888. return get_number(input_format_t::cbor, len) and get_cbor_object(static_cast<std::size_t>(len));
  4889. }
  4890. case 0xBB: // map (eight-byte uint64_t for n follow)
  4891. {
  4892. std::uint64_t len;
  4893. return get_number(input_format_t::cbor, len) and get_cbor_object(static_cast<std::size_t>(len));
  4894. }
  4895. case 0xBF: // map (indefinite length)
  4896. return get_cbor_object(std::size_t(-1));
  4897. case 0xF4: // false
  4898. return sax->boolean(false);
  4899. case 0xF5: // true
  4900. return sax->boolean(true);
  4901. case 0xF6: // null
  4902. return sax->null();
  4903. case 0xF9: // Half-Precision Float (two-byte IEEE 754)
  4904. {
  4905. const int byte1_raw = get();
  4906. if (JSON_HEDLEY_UNLIKELY(not unexpect_eof(input_format_t::cbor, "number")))
  4907. {
  4908. return false;
  4909. }
  4910. const int byte2_raw = get();
  4911. if (JSON_HEDLEY_UNLIKELY(not unexpect_eof(input_format_t::cbor, "number")))
  4912. {
  4913. return false;
  4914. }
  4915. const auto byte1 = static_cast<unsigned char>(byte1_raw);
  4916. const auto byte2 = static_cast<unsigned char>(byte2_raw);
  4917. // code from RFC 7049, Appendix D, Figure 3:
  4918. // As half-precision floating-point numbers were only added
  4919. // to IEEE 754 in 2008, today's programming platforms often
  4920. // still only have limited support for them. It is very
  4921. // easy to include at least decoding support for them even
  4922. // without such support. An example of a small decoder for
  4923. // half-precision floating-point numbers in the C language
  4924. // is shown in Fig. 3.
  4925. const auto half = static_cast<unsigned int>((byte1 << 8u) + byte2);
  4926. const double val = [&half]
  4927. {
  4928. const int exp = (half >> 10u) & 0x1Fu;
  4929. const unsigned int mant = half & 0x3FFu;
  4930. assert(0 <= exp and exp <= 32);
  4931. assert(0 <= mant and mant <= 1024);
  4932. switch (exp)
  4933. {
  4934. case 0:
  4935. return std::ldexp(mant, -24);
  4936. case 31:
  4937. return (mant == 0)
  4938. ? std::numeric_limits<double>::infinity()
  4939. : std::numeric_limits<double>::quiet_NaN();
  4940. default:
  4941. return std::ldexp(mant + 1024, exp - 25);
  4942. }
  4943. }();
  4944. return sax->number_float((half & 0x8000u) != 0
  4945. ? static_cast<number_float_t>(-val)
  4946. : static_cast<number_float_t>(val), "");
  4947. }
  4948. case 0xFA: // Single-Precision Float (four-byte IEEE 754)
  4949. {
  4950. float number;
  4951. return get_number(input_format_t::cbor, number) and sax->number_float(static_cast<number_float_t>(number), "");
  4952. }
  4953. case 0xFB: // Double-Precision Float (eight-byte IEEE 754)
  4954. {
  4955. double number;
  4956. return get_number(input_format_t::cbor, number) and sax->number_float(static_cast<number_float_t>(number), "");
  4957. }
  4958. default: // anything else (0xFF is handled inside the other types)
  4959. {
  4960. auto last_token = get_token_string();
  4961. 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")));
  4962. }
  4963. }
  4964. }
  4965. /*!
  4966. @brief reads a CBOR string
  4967. This function first reads starting bytes to determine the expected
  4968. string length and then copies this number of bytes into a string.
  4969. Additionally, CBOR's strings with indefinite lengths are supported.
  4970. @param[out] result created string
  4971. @return whether string creation completed
  4972. */
  4973. bool get_cbor_string(string_t& result)
  4974. {
  4975. if (JSON_HEDLEY_UNLIKELY(not unexpect_eof(input_format_t::cbor, "string")))
  4976. {
  4977. return false;
  4978. }
  4979. switch (current)
  4980. {
  4981. // UTF-8 string (0x00..0x17 bytes follow)
  4982. case 0x60:
  4983. case 0x61:
  4984. case 0x62:
  4985. case 0x63:
  4986. case 0x64:
  4987. case 0x65:
  4988. case 0x66:
  4989. case 0x67:
  4990. case 0x68:
  4991. case 0x69:
  4992. case 0x6A:
  4993. case 0x6B:
  4994. case 0x6C:
  4995. case 0x6D:
  4996. case 0x6E:
  4997. case 0x6F:
  4998. case 0x70:
  4999. case 0x71:
  5000. case 0x72:
  5001. case 0x73:
  5002. case 0x74:
  5003. case 0x75:
  5004. case 0x76:
  5005. case 0x77:
  5006. {
  5007. return get_string(input_format_t::cbor, static_cast<unsigned int>(current) & 0x1Fu, result);
  5008. }
  5009. case 0x78: // UTF-8 string (one-byte uint8_t for n follows)
  5010. {
  5011. std::uint8_t len;
  5012. return get_number(input_format_t::cbor, len) and get_string(input_format_t::cbor, len, result);
  5013. }
  5014. case 0x79: // UTF-8 string (two-byte uint16_t for n follow)
  5015. {
  5016. std::uint16_t len;
  5017. return get_number(input_format_t::cbor, len) and get_string(input_format_t::cbor, len, result);
  5018. }
  5019. case 0x7A: // UTF-8 string (four-byte uint32_t for n follow)
  5020. {
  5021. std::uint32_t len;
  5022. return get_number(input_format_t::cbor, len) and get_string(input_format_t::cbor, len, result);
  5023. }
  5024. case 0x7B: // UTF-8 string (eight-byte uint64_t for n follow)
  5025. {
  5026. std::uint64_t len;
  5027. return get_number(input_format_t::cbor, len) and get_string(input_format_t::cbor, len, result);
  5028. }
  5029. case 0x7F: // UTF-8 string (indefinite length)
  5030. {
  5031. while (get() != 0xFF)
  5032. {
  5033. string_t chunk;
  5034. if (not get_cbor_string(chunk))
  5035. {
  5036. return false;
  5037. }
  5038. result.append(chunk);
  5039. }
  5040. return true;
  5041. }
  5042. default:
  5043. {
  5044. auto last_token = get_token_string();
  5045. 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")));
  5046. }
  5047. }
  5048. }
  5049. /*!
  5050. @param[in] len the length of the array or std::size_t(-1) for an
  5051. array of indefinite size
  5052. @return whether array creation completed
  5053. */
  5054. bool get_cbor_array(const std::size_t len)
  5055. {
  5056. if (JSON_HEDLEY_UNLIKELY(not sax->start_array(len)))
  5057. {
  5058. return false;
  5059. }
  5060. if (len != std::size_t(-1))
  5061. {
  5062. for (std::size_t i = 0; i < len; ++i)
  5063. {
  5064. if (JSON_HEDLEY_UNLIKELY(not parse_cbor_internal()))
  5065. {
  5066. return false;
  5067. }
  5068. }
  5069. }
  5070. else
  5071. {
  5072. while (get() != 0xFF)
  5073. {
  5074. if (JSON_HEDLEY_UNLIKELY(not parse_cbor_internal(false)))
  5075. {
  5076. return false;
  5077. }
  5078. }
  5079. }
  5080. return sax->end_array();
  5081. }
  5082. /*!
  5083. @param[in] len the length of the object or std::size_t(-1) for an
  5084. object of indefinite size
  5085. @return whether object creation completed
  5086. */
  5087. bool get_cbor_object(const std::size_t len)
  5088. {
  5089. if (JSON_HEDLEY_UNLIKELY(not sax->start_object(len)))
  5090. {
  5091. return false;
  5092. }
  5093. string_t key;
  5094. if (len != std::size_t(-1))
  5095. {
  5096. for (std::size_t i = 0; i < len; ++i)
  5097. {
  5098. get();
  5099. if (JSON_HEDLEY_UNLIKELY(not get_cbor_string(key) or not sax->key(key)))
  5100. {
  5101. return false;
  5102. }
  5103. if (JSON_HEDLEY_UNLIKELY(not parse_cbor_internal()))
  5104. {
  5105. return false;
  5106. }
  5107. key.clear();
  5108. }
  5109. }
  5110. else
  5111. {
  5112. while (get() != 0xFF)
  5113. {
  5114. if (JSON_HEDLEY_UNLIKELY(not get_cbor_string(key) or not sax->key(key)))
  5115. {
  5116. return false;
  5117. }
  5118. if (JSON_HEDLEY_UNLIKELY(not parse_cbor_internal()))
  5119. {
  5120. return false;
  5121. }
  5122. key.clear();
  5123. }
  5124. }
  5125. return sax->end_object();
  5126. }
  5127. /////////////
  5128. // MsgPack //
  5129. /////////////
  5130. /*!
  5131. @return whether a valid MessagePack value was passed to the SAX parser
  5132. */
  5133. bool parse_msgpack_internal()
  5134. {
  5135. switch (get())
  5136. {
  5137. // EOF
  5138. case std::char_traits<char>::eof():
  5139. return unexpect_eof(input_format_t::msgpack, "value");
  5140. // positive fixint
  5141. case 0x00:
  5142. case 0x01:
  5143. case 0x02:
  5144. case 0x03:
  5145. case 0x04:
  5146. case 0x05:
  5147. case 0x06:
  5148. case 0x07:
  5149. case 0x08:
  5150. case 0x09:
  5151. case 0x0A:
  5152. case 0x0B:
  5153. case 0x0C:
  5154. case 0x0D:
  5155. case 0x0E:
  5156. case 0x0F:
  5157. case 0x10:
  5158. case 0x11:
  5159. case 0x12:
  5160. case 0x13:
  5161. case 0x14:
  5162. case 0x15:
  5163. case 0x16:
  5164. case 0x17:
  5165. case 0x18:
  5166. case 0x19:
  5167. case 0x1A:
  5168. case 0x1B:
  5169. case 0x1C:
  5170. case 0x1D:
  5171. case 0x1E:
  5172. case 0x1F:
  5173. case 0x20:
  5174. case 0x21:
  5175. case 0x22:
  5176. case 0x23:
  5177. case 0x24:
  5178. case 0x25:
  5179. case 0x26:
  5180. case 0x27:
  5181. case 0x28:
  5182. case 0x29:
  5183. case 0x2A:
  5184. case 0x2B:
  5185. case 0x2C:
  5186. case 0x2D:
  5187. case 0x2E:
  5188. case 0x2F:
  5189. case 0x30:
  5190. case 0x31:
  5191. case 0x32:
  5192. case 0x33:
  5193. case 0x34:
  5194. case 0x35:
  5195. case 0x36:
  5196. case 0x37:
  5197. case 0x38:
  5198. case 0x39:
  5199. case 0x3A:
  5200. case 0x3B:
  5201. case 0x3C:
  5202. case 0x3D:
  5203. case 0x3E:
  5204. case 0x3F:
  5205. case 0x40:
  5206. case 0x41:
  5207. case 0x42:
  5208. case 0x43:
  5209. case 0x44:
  5210. case 0x45:
  5211. case 0x46:
  5212. case 0x47:
  5213. case 0x48:
  5214. case 0x49:
  5215. case 0x4A:
  5216. case 0x4B:
  5217. case 0x4C:
  5218. case 0x4D:
  5219. case 0x4E:
  5220. case 0x4F:
  5221. case 0x50:
  5222. case 0x51:
  5223. case 0x52:
  5224. case 0x53:
  5225. case 0x54:
  5226. case 0x55:
  5227. case 0x56:
  5228. case 0x57:
  5229. case 0x58:
  5230. case 0x59:
  5231. case 0x5A:
  5232. case 0x5B:
  5233. case 0x5C:
  5234. case 0x5D:
  5235. case 0x5E:
  5236. case 0x5F:
  5237. case 0x60:
  5238. case 0x61:
  5239. case 0x62:
  5240. case 0x63:
  5241. case 0x64:
  5242. case 0x65:
  5243. case 0x66:
  5244. case 0x67:
  5245. case 0x68:
  5246. case 0x69:
  5247. case 0x6A:
  5248. case 0x6B:
  5249. case 0x6C:
  5250. case 0x6D:
  5251. case 0x6E:
  5252. case 0x6F:
  5253. case 0x70:
  5254. case 0x71:
  5255. case 0x72:
  5256. case 0x73:
  5257. case 0x74:
  5258. case 0x75:
  5259. case 0x76:
  5260. case 0x77:
  5261. case 0x78:
  5262. case 0x79:
  5263. case 0x7A:
  5264. case 0x7B:
  5265. case 0x7C:
  5266. case 0x7D:
  5267. case 0x7E:
  5268. case 0x7F:
  5269. return sax->number_unsigned(static_cast<number_unsigned_t>(current));
  5270. // fixmap
  5271. case 0x80:
  5272. case 0x81:
  5273. case 0x82:
  5274. case 0x83:
  5275. case 0x84:
  5276. case 0x85:
  5277. case 0x86:
  5278. case 0x87:
  5279. case 0x88:
  5280. case 0x89:
  5281. case 0x8A:
  5282. case 0x8B:
  5283. case 0x8C:
  5284. case 0x8D:
  5285. case 0x8E:
  5286. case 0x8F:
  5287. return get_msgpack_object(static_cast<std::size_t>(static_cast<unsigned int>(current) & 0x0Fu));
  5288. // fixarray
  5289. case 0x90:
  5290. case 0x91:
  5291. case 0x92:
  5292. case 0x93:
  5293. case 0x94:
  5294. case 0x95:
  5295. case 0x96:
  5296. case 0x97:
  5297. case 0x98:
  5298. case 0x99:
  5299. case 0x9A:
  5300. case 0x9B:
  5301. case 0x9C:
  5302. case 0x9D:
  5303. case 0x9E:
  5304. case 0x9F:
  5305. return get_msgpack_array(static_cast<std::size_t>(static_cast<unsigned int>(current) & 0x0Fu));
  5306. // fixstr
  5307. case 0xA0:
  5308. case 0xA1:
  5309. case 0xA2:
  5310. case 0xA3:
  5311. case 0xA4:
  5312. case 0xA5:
  5313. case 0xA6:
  5314. case 0xA7:
  5315. case 0xA8:
  5316. case 0xA9:
  5317. case 0xAA:
  5318. case 0xAB:
  5319. case 0xAC:
  5320. case 0xAD:
  5321. case 0xAE:
  5322. case 0xAF:
  5323. case 0xB0:
  5324. case 0xB1:
  5325. case 0xB2:
  5326. case 0xB3:
  5327. case 0xB4:
  5328. case 0xB5:
  5329. case 0xB6:
  5330. case 0xB7:
  5331. case 0xB8:
  5332. case 0xB9:
  5333. case 0xBA:
  5334. case 0xBB:
  5335. case 0xBC:
  5336. case 0xBD:
  5337. case 0xBE:
  5338. case 0xBF:
  5339. case 0xD9: // str 8
  5340. case 0xDA: // str 16
  5341. case 0xDB: // str 32
  5342. {
  5343. string_t s;
  5344. return get_msgpack_string(s) and sax->string(s);
  5345. }
  5346. case 0xC0: // nil
  5347. return sax->null();
  5348. case 0xC2: // false
  5349. return sax->boolean(false);
  5350. case 0xC3: // true
  5351. return sax->boolean(true);
  5352. case 0xCA: // float 32
  5353. {
  5354. float number;
  5355. return get_number(input_format_t::msgpack, number) and sax->number_float(static_cast<number_float_t>(number), "");
  5356. }
  5357. case 0xCB: // float 64
  5358. {
  5359. double number;
  5360. return get_number(input_format_t::msgpack, number) and sax->number_float(static_cast<number_float_t>(number), "");
  5361. }
  5362. case 0xCC: // uint 8
  5363. {
  5364. std::uint8_t number;
  5365. return get_number(input_format_t::msgpack, number) and sax->number_unsigned(number);
  5366. }
  5367. case 0xCD: // uint 16
  5368. {
  5369. std::uint16_t number;
  5370. return get_number(input_format_t::msgpack, number) and sax->number_unsigned(number);
  5371. }
  5372. case 0xCE: // uint 32
  5373. {
  5374. std::uint32_t number;
  5375. return get_number(input_format_t::msgpack, number) and sax->number_unsigned(number);
  5376. }
  5377. case 0xCF: // uint 64
  5378. {
  5379. std::uint64_t number;
  5380. return get_number(input_format_t::msgpack, number) and sax->number_unsigned(number);
  5381. }
  5382. case 0xD0: // int 8
  5383. {
  5384. std::int8_t number;
  5385. return get_number(input_format_t::msgpack, number) and sax->number_integer(number);
  5386. }
  5387. case 0xD1: // int 16
  5388. {
  5389. std::int16_t number;
  5390. return get_number(input_format_t::msgpack, number) and sax->number_integer(number);
  5391. }
  5392. case 0xD2: // int 32
  5393. {
  5394. std::int32_t number;
  5395. return get_number(input_format_t::msgpack, number) and sax->number_integer(number);
  5396. }
  5397. case 0xD3: // int 64
  5398. {
  5399. std::int64_t number;
  5400. return get_number(input_format_t::msgpack, number) and sax->number_integer(number);
  5401. }
  5402. case 0xDC: // array 16
  5403. {
  5404. std::uint16_t len;
  5405. return get_number(input_format_t::msgpack, len) and get_msgpack_array(static_cast<std::size_t>(len));
  5406. }
  5407. case 0xDD: // array 32
  5408. {
  5409. std::uint32_t len;
  5410. return get_number(input_format_t::msgpack, len) and get_msgpack_array(static_cast<std::size_t>(len));
  5411. }
  5412. case 0xDE: // map 16
  5413. {
  5414. std::uint16_t len;
  5415. return get_number(input_format_t::msgpack, len) and get_msgpack_object(static_cast<std::size_t>(len));
  5416. }
  5417. case 0xDF: // map 32
  5418. {
  5419. std::uint32_t len;
  5420. return get_number(input_format_t::msgpack, len) and get_msgpack_object(static_cast<std::size_t>(len));
  5421. }
  5422. // negative fixint
  5423. case 0xE0:
  5424. case 0xE1:
  5425. case 0xE2:
  5426. case 0xE3:
  5427. case 0xE4:
  5428. case 0xE5:
  5429. case 0xE6:
  5430. case 0xE7:
  5431. case 0xE8:
  5432. case 0xE9:
  5433. case 0xEA:
  5434. case 0xEB:
  5435. case 0xEC:
  5436. case 0xED:
  5437. case 0xEE:
  5438. case 0xEF:
  5439. case 0xF0:
  5440. case 0xF1:
  5441. case 0xF2:
  5442. case 0xF3:
  5443. case 0xF4:
  5444. case 0xF5:
  5445. case 0xF6:
  5446. case 0xF7:
  5447. case 0xF8:
  5448. case 0xF9:
  5449. case 0xFA:
  5450. case 0xFB:
  5451. case 0xFC:
  5452. case 0xFD:
  5453. case 0xFE:
  5454. case 0xFF:
  5455. return sax->number_integer(static_cast<std::int8_t>(current));
  5456. default: // anything else
  5457. {
  5458. auto last_token = get_token_string();
  5459. 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")));
  5460. }
  5461. }
  5462. }
  5463. /*!
  5464. @brief reads a MessagePack string
  5465. This function first reads starting bytes to determine the expected
  5466. string length and then copies this number of bytes into a string.
  5467. @param[out] result created string
  5468. @return whether string creation completed
  5469. */
  5470. bool get_msgpack_string(string_t& result)
  5471. {
  5472. if (JSON_HEDLEY_UNLIKELY(not unexpect_eof(input_format_t::msgpack, "string")))
  5473. {
  5474. return false;
  5475. }
  5476. switch (current)
  5477. {
  5478. // fixstr
  5479. case 0xA0:
  5480. case 0xA1:
  5481. case 0xA2:
  5482. case 0xA3:
  5483. case 0xA4:
  5484. case 0xA5:
  5485. case 0xA6:
  5486. case 0xA7:
  5487. case 0xA8:
  5488. case 0xA9:
  5489. case 0xAA:
  5490. case 0xAB:
  5491. case 0xAC:
  5492. case 0xAD:
  5493. case 0xAE:
  5494. case 0xAF:
  5495. case 0xB0:
  5496. case 0xB1:
  5497. case 0xB2:
  5498. case 0xB3:
  5499. case 0xB4:
  5500. case 0xB5:
  5501. case 0xB6:
  5502. case 0xB7:
  5503. case 0xB8:
  5504. case 0xB9:
  5505. case 0xBA:
  5506. case 0xBB:
  5507. case 0xBC:
  5508. case 0xBD:
  5509. case 0xBE:
  5510. case 0xBF:
  5511. {
  5512. return get_string(input_format_t::msgpack, static_cast<unsigned int>(current) & 0x1Fu, result);
  5513. }
  5514. case 0xD9: // str 8
  5515. {
  5516. std::uint8_t len;
  5517. return get_number(input_format_t::msgpack, len) and get_string(input_format_t::msgpack, len, result);
  5518. }
  5519. case 0xDA: // str 16
  5520. {
  5521. std::uint16_t len;
  5522. return get_number(input_format_t::msgpack, len) and get_string(input_format_t::msgpack, len, result);
  5523. }
  5524. case 0xDB: // str 32
  5525. {
  5526. std::uint32_t len;
  5527. return get_number(input_format_t::msgpack, len) and get_string(input_format_t::msgpack, len, result);
  5528. }
  5529. default:
  5530. {
  5531. auto last_token = get_token_string();
  5532. 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")));
  5533. }
  5534. }
  5535. }
  5536. /*!
  5537. @param[in] len the length of the array
  5538. @return whether array creation completed
  5539. */
  5540. bool get_msgpack_array(const std::size_t len)
  5541. {
  5542. if (JSON_HEDLEY_UNLIKELY(not sax->start_array(len)))
  5543. {
  5544. return false;
  5545. }
  5546. for (std::size_t i = 0; i < len; ++i)
  5547. {
  5548. if (JSON_HEDLEY_UNLIKELY(not parse_msgpack_internal()))
  5549. {
  5550. return false;
  5551. }
  5552. }
  5553. return sax->end_array();
  5554. }
  5555. /*!
  5556. @param[in] len the length of the object
  5557. @return whether object creation completed
  5558. */
  5559. bool get_msgpack_object(const std::size_t len)
  5560. {
  5561. if (JSON_HEDLEY_UNLIKELY(not sax->start_object(len)))
  5562. {
  5563. return false;
  5564. }
  5565. string_t key;
  5566. for (std::size_t i = 0; i < len; ++i)
  5567. {
  5568. get();
  5569. if (JSON_HEDLEY_UNLIKELY(not get_msgpack_string(key) or not sax->key(key)))
  5570. {
  5571. return false;
  5572. }
  5573. if (JSON_HEDLEY_UNLIKELY(not parse_msgpack_internal()))
  5574. {
  5575. return false;
  5576. }
  5577. key.clear();
  5578. }
  5579. return sax->end_object();
  5580. }
  5581. ////////////
  5582. // UBJSON //
  5583. ////////////
  5584. /*!
  5585. @param[in] get_char whether a new character should be retrieved from the
  5586. input (true, default) or whether the last read
  5587. character should be considered instead
  5588. @return whether a valid UBJSON value was passed to the SAX parser
  5589. */
  5590. bool parse_ubjson_internal(const bool get_char = true)
  5591. {
  5592. return get_ubjson_value(get_char ? get_ignore_noop() : current);
  5593. }
  5594. /*!
  5595. @brief reads a UBJSON string
  5596. This function is either called after reading the 'S' byte explicitly
  5597. indicating a string, or in case of an object key where the 'S' byte can be
  5598. left out.
  5599. @param[out] result created string
  5600. @param[in] get_char whether a new character should be retrieved from the
  5601. input (true, default) or whether the last read
  5602. character should be considered instead
  5603. @return whether string creation completed
  5604. */
  5605. bool get_ubjson_string(string_t& result, const bool get_char = true)
  5606. {
  5607. if (get_char)
  5608. {
  5609. get(); // TODO(niels): may we ignore N here?
  5610. }
  5611. if (JSON_HEDLEY_UNLIKELY(not unexpect_eof(input_format_t::ubjson, "value")))
  5612. {
  5613. return false;
  5614. }
  5615. switch (current)
  5616. {
  5617. case 'U':
  5618. {
  5619. std::uint8_t len;
  5620. return get_number(input_format_t::ubjson, len) and get_string(input_format_t::ubjson, len, result);
  5621. }
  5622. case 'i':
  5623. {
  5624. std::int8_t len;
  5625. return get_number(input_format_t::ubjson, len) and get_string(input_format_t::ubjson, len, result);
  5626. }
  5627. case 'I':
  5628. {
  5629. std::int16_t len;
  5630. return get_number(input_format_t::ubjson, len) and get_string(input_format_t::ubjson, len, result);
  5631. }
  5632. case 'l':
  5633. {
  5634. std::int32_t len;
  5635. return get_number(input_format_t::ubjson, len) and get_string(input_format_t::ubjson, len, result);
  5636. }
  5637. case 'L':
  5638. {
  5639. std::int64_t len;
  5640. return get_number(input_format_t::ubjson, len) and get_string(input_format_t::ubjson, len, result);
  5641. }
  5642. default:
  5643. auto last_token = get_token_string();
  5644. 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")));
  5645. }
  5646. }
  5647. /*!
  5648. @param[out] result determined size
  5649. @return whether size determination completed
  5650. */
  5651. bool get_ubjson_size_value(std::size_t& result)
  5652. {
  5653. switch (get_ignore_noop())
  5654. {
  5655. case 'U':
  5656. {
  5657. std::uint8_t number;
  5658. if (JSON_HEDLEY_UNLIKELY(not get_number(input_format_t::ubjson, number)))
  5659. {
  5660. return false;
  5661. }
  5662. result = static_cast<std::size_t>(number);
  5663. return true;
  5664. }
  5665. case 'i':
  5666. {
  5667. std::int8_t number;
  5668. if (JSON_HEDLEY_UNLIKELY(not get_number(input_format_t::ubjson, number)))
  5669. {
  5670. return false;
  5671. }
  5672. result = static_cast<std::size_t>(number);
  5673. return true;
  5674. }
  5675. case 'I':
  5676. {
  5677. std::int16_t number;
  5678. if (JSON_HEDLEY_UNLIKELY(not get_number(input_format_t::ubjson, number)))
  5679. {
  5680. return false;
  5681. }
  5682. result = static_cast<std::size_t>(number);
  5683. return true;
  5684. }
  5685. case 'l':
  5686. {
  5687. std::int32_t number;
  5688. if (JSON_HEDLEY_UNLIKELY(not get_number(input_format_t::ubjson, number)))
  5689. {
  5690. return false;
  5691. }
  5692. result = static_cast<std::size_t>(number);
  5693. return true;
  5694. }
  5695. case 'L':
  5696. {
  5697. std::int64_t number;
  5698. if (JSON_HEDLEY_UNLIKELY(not get_number(input_format_t::ubjson, number)))
  5699. {
  5700. return false;
  5701. }
  5702. result = static_cast<std::size_t>(number);
  5703. return true;
  5704. }
  5705. default:
  5706. {
  5707. auto last_token = get_token_string();
  5708. 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")));
  5709. }
  5710. }
  5711. }
  5712. /*!
  5713. @brief determine the type and size for a container
  5714. In the optimized UBJSON format, a type and a size can be provided to allow
  5715. for a more compact representation.
  5716. @param[out] result pair of the size and the type
  5717. @return whether pair creation completed
  5718. */
  5719. bool get_ubjson_size_type(std::pair<std::size_t, int>& result)
  5720. {
  5721. result.first = string_t::npos; // size
  5722. result.second = 0; // type
  5723. get_ignore_noop();
  5724. if (current == '$')
  5725. {
  5726. result.second = get(); // must not ignore 'N', because 'N' maybe the type
  5727. if (JSON_HEDLEY_UNLIKELY(not unexpect_eof(input_format_t::ubjson, "type")))
  5728. {
  5729. return false;
  5730. }
  5731. get_ignore_noop();
  5732. if (JSON_HEDLEY_UNLIKELY(current != '#'))
  5733. {
  5734. if (JSON_HEDLEY_UNLIKELY(not unexpect_eof(input_format_t::ubjson, "value")))
  5735. {
  5736. return false;
  5737. }
  5738. auto last_token = get_token_string();
  5739. 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")));
  5740. }
  5741. return get_ubjson_size_value(result.first);
  5742. }
  5743. if (current == '#')
  5744. {
  5745. return get_ubjson_size_value(result.first);
  5746. }
  5747. return true;
  5748. }
  5749. /*!
  5750. @param prefix the previously read or set type prefix
  5751. @return whether value creation completed
  5752. */
  5753. bool get_ubjson_value(const int prefix)
  5754. {
  5755. switch (prefix)
  5756. {
  5757. case std::char_traits<char>::eof(): // EOF
  5758. return unexpect_eof(input_format_t::ubjson, "value");
  5759. case 'T': // true
  5760. return sax->boolean(true);
  5761. case 'F': // false
  5762. return sax->boolean(false);
  5763. case 'Z': // null
  5764. return sax->null();
  5765. case 'U':
  5766. {
  5767. std::uint8_t number;
  5768. return get_number(input_format_t::ubjson, number) and sax->number_unsigned(number);
  5769. }
  5770. case 'i':
  5771. {
  5772. std::int8_t number;
  5773. return get_number(input_format_t::ubjson, number) and sax->number_integer(number);
  5774. }
  5775. case 'I':
  5776. {
  5777. std::int16_t number;
  5778. return get_number(input_format_t::ubjson, number) and sax->number_integer(number);
  5779. }
  5780. case 'l':
  5781. {
  5782. std::int32_t number;
  5783. return get_number(input_format_t::ubjson, number) and sax->number_integer(number);
  5784. }
  5785. case 'L':
  5786. {
  5787. std::int64_t number;
  5788. return get_number(input_format_t::ubjson, number) and sax->number_integer(number);
  5789. }
  5790. case 'd':
  5791. {
  5792. float number;
  5793. return get_number(input_format_t::ubjson, number) and sax->number_float(static_cast<number_float_t>(number), "");
  5794. }
  5795. case 'D':
  5796. {
  5797. double number;
  5798. return get_number(input_format_t::ubjson, number) and sax->number_float(static_cast<number_float_t>(number), "");
  5799. }
  5800. case 'C': // char
  5801. {
  5802. get();
  5803. if (JSON_HEDLEY_UNLIKELY(not unexpect_eof(input_format_t::ubjson, "char")))
  5804. {
  5805. return false;
  5806. }
  5807. if (JSON_HEDLEY_UNLIKELY(current > 127))
  5808. {
  5809. auto last_token = get_token_string();
  5810. 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")));
  5811. }
  5812. string_t s(1, static_cast<char>(current));
  5813. return sax->string(s);
  5814. }
  5815. case 'S': // string
  5816. {
  5817. string_t s;
  5818. return get_ubjson_string(s) and sax->string(s);
  5819. }
  5820. case '[': // array
  5821. return get_ubjson_array();
  5822. case '{': // object
  5823. return get_ubjson_object();
  5824. default: // anything else
  5825. {
  5826. auto last_token = get_token_string();
  5827. 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")));
  5828. }
  5829. }
  5830. }
  5831. /*!
  5832. @return whether array creation completed
  5833. */
  5834. bool get_ubjson_array()
  5835. {
  5836. std::pair<std::size_t, int> size_and_type;
  5837. if (JSON_HEDLEY_UNLIKELY(not get_ubjson_size_type(size_and_type)))
  5838. {
  5839. return false;
  5840. }
  5841. if (size_and_type.first != string_t::npos)
  5842. {
  5843. if (JSON_HEDLEY_UNLIKELY(not sax->start_array(size_and_type.first)))
  5844. {
  5845. return false;
  5846. }
  5847. if (size_and_type.second != 0)
  5848. {
  5849. if (size_and_type.second != 'N')
  5850. {
  5851. for (std::size_t i = 0; i < size_and_type.first; ++i)
  5852. {
  5853. if (JSON_HEDLEY_UNLIKELY(not get_ubjson_value(size_and_type.second)))
  5854. {
  5855. return false;
  5856. }
  5857. }
  5858. }
  5859. }
  5860. else
  5861. {
  5862. for (std::size_t i = 0; i < size_and_type.first; ++i)
  5863. {
  5864. if (JSON_HEDLEY_UNLIKELY(not parse_ubjson_internal()))
  5865. {
  5866. return false;
  5867. }
  5868. }
  5869. }
  5870. }
  5871. else
  5872. {
  5873. if (JSON_HEDLEY_UNLIKELY(not sax->start_array(std::size_t(-1))))
  5874. {
  5875. return false;
  5876. }
  5877. while (current != ']')
  5878. {
  5879. if (JSON_HEDLEY_UNLIKELY(not parse_ubjson_internal(false)))
  5880. {
  5881. return false;
  5882. }
  5883. get_ignore_noop();
  5884. }
  5885. }
  5886. return sax->end_array();
  5887. }
  5888. /*!
  5889. @return whether object creation completed
  5890. */
  5891. bool get_ubjson_object()
  5892. {
  5893. std::pair<std::size_t, int> size_and_type;
  5894. if (JSON_HEDLEY_UNLIKELY(not get_ubjson_size_type(size_and_type)))
  5895. {
  5896. return false;
  5897. }
  5898. string_t key;
  5899. if (size_and_type.first != string_t::npos)
  5900. {
  5901. if (JSON_HEDLEY_UNLIKELY(not sax->start_object(size_and_type.first)))
  5902. {
  5903. return false;
  5904. }
  5905. if (size_and_type.second != 0)
  5906. {
  5907. for (std::size_t i = 0; i < size_and_type.first; ++i)
  5908. {
  5909. if (JSON_HEDLEY_UNLIKELY(not get_ubjson_string(key) or not sax->key(key)))
  5910. {
  5911. return false;
  5912. }
  5913. if (JSON_HEDLEY_UNLIKELY(not get_ubjson_value(size_and_type.second)))
  5914. {
  5915. return false;
  5916. }
  5917. key.clear();
  5918. }
  5919. }
  5920. else
  5921. {
  5922. for (std::size_t i = 0; i < size_and_type.first; ++i)
  5923. {
  5924. if (JSON_HEDLEY_UNLIKELY(not get_ubjson_string(key) or not sax->key(key)))
  5925. {
  5926. return false;
  5927. }
  5928. if (JSON_HEDLEY_UNLIKELY(not parse_ubjson_internal()))
  5929. {
  5930. return false;
  5931. }
  5932. key.clear();
  5933. }
  5934. }
  5935. }
  5936. else
  5937. {
  5938. if (JSON_HEDLEY_UNLIKELY(not sax->start_object(std::size_t(-1))))
  5939. {
  5940. return false;
  5941. }
  5942. while (current != '}')
  5943. {
  5944. if (JSON_HEDLEY_UNLIKELY(not get_ubjson_string(key, false) or not sax->key(key)))
  5945. {
  5946. return false;
  5947. }
  5948. if (JSON_HEDLEY_UNLIKELY(not parse_ubjson_internal()))
  5949. {
  5950. return false;
  5951. }
  5952. get_ignore_noop();
  5953. key.clear();
  5954. }
  5955. }
  5956. return sax->end_object();
  5957. }
  5958. ///////////////////////
  5959. // Utility functions //
  5960. ///////////////////////
  5961. /*!
  5962. @brief get next character from the input
  5963. This function provides the interface to the used input adapter. It does
  5964. not throw in case the input reached EOF, but returns a -'ve valued
  5965. `std::char_traits<char>::eof()` in that case.
  5966. @return character read from the input
  5967. */
  5968. int get()
  5969. {
  5970. ++chars_read;
  5971. return current = ia->get_character();
  5972. }
  5973. /*!
  5974. @return character read from the input after ignoring all 'N' entries
  5975. */
  5976. int get_ignore_noop()
  5977. {
  5978. do
  5979. {
  5980. get();
  5981. }
  5982. while (current == 'N');
  5983. return current;
  5984. }
  5985. /*
  5986. @brief read a number from the input
  5987. @tparam NumberType the type of the number
  5988. @param[in] format the current format (for diagnostics)
  5989. @param[out] result number of type @a NumberType
  5990. @return whether conversion completed
  5991. @note This function needs to respect the system's endianess, because
  5992. bytes in CBOR, MessagePack, and UBJSON are stored in network order
  5993. (big endian) and therefore need reordering on little endian systems.
  5994. */
  5995. template<typename NumberType, bool InputIsLittleEndian = false>
  5996. bool get_number(const input_format_t format, NumberType& result)
  5997. {
  5998. // step 1: read input into array with system's byte order
  5999. std::array<std::uint8_t, sizeof(NumberType)> vec;
  6000. for (std::size_t i = 0; i < sizeof(NumberType); ++i)
  6001. {
  6002. get();
  6003. if (JSON_HEDLEY_UNLIKELY(not unexpect_eof(format, "number")))
  6004. {
  6005. return false;
  6006. }
  6007. // reverse byte order prior to conversion if necessary
  6008. if (is_little_endian != InputIsLittleEndian)
  6009. {
  6010. vec[sizeof(NumberType) - i - 1] = static_cast<std::uint8_t>(current);
  6011. }
  6012. else
  6013. {
  6014. vec[i] = static_cast<std::uint8_t>(current); // LCOV_EXCL_LINE
  6015. }
  6016. }
  6017. // step 2: convert array into number of type T and return
  6018. std::memcpy(&result, vec.data(), sizeof(NumberType));
  6019. return true;
  6020. }
  6021. /*!
  6022. @brief create a string by reading characters from the input
  6023. @tparam NumberType the type of the number
  6024. @param[in] format the current format (for diagnostics)
  6025. @param[in] len number of characters to read
  6026. @param[out] result string created by reading @a len bytes
  6027. @return whether string creation completed
  6028. @note We can not reserve @a len bytes for the result, because @a len
  6029. may be too large. Usually, @ref unexpect_eof() detects the end of
  6030. the input before we run out of string memory.
  6031. */
  6032. template<typename NumberType>
  6033. bool get_string(const input_format_t format,
  6034. const NumberType len,
  6035. string_t& result)
  6036. {
  6037. bool success = true;
  6038. std::generate_n(std::back_inserter(result), len, [this, &success, &format]()
  6039. {
  6040. get();
  6041. if (JSON_HEDLEY_UNLIKELY(not unexpect_eof(format, "string")))
  6042. {
  6043. success = false;
  6044. }
  6045. return static_cast<char>(current);
  6046. });
  6047. return success;
  6048. }
  6049. /*!
  6050. @param[in] format the current format (for diagnostics)
  6051. @param[in] context further context information (for diagnostics)
  6052. @return whether the last read character is not EOF
  6053. */
  6054. JSON_HEDLEY_NON_NULL(3)
  6055. bool unexpect_eof(const input_format_t format, const char* context) const
  6056. {
  6057. if (JSON_HEDLEY_UNLIKELY(current == std::char_traits<char>::eof()))
  6058. {
  6059. return sax->parse_error(chars_read, "<end of file>",
  6060. parse_error::create(110, chars_read, exception_message(format, "unexpected end of input", context)));
  6061. }
  6062. return true;
  6063. }
  6064. /*!
  6065. @return a string representation of the last read byte
  6066. */
  6067. std::string get_token_string() const
  6068. {
  6069. std::array<char, 3> cr{{}};
  6070. (std::snprintf)(cr.data(), cr.size(), "%.2hhX", static_cast<unsigned char>(current));
  6071. return std::string{cr.data()};
  6072. }
  6073. /*!
  6074. @param[in] format the current format
  6075. @param[in] detail a detailed error message
  6076. @param[in] context further contect information
  6077. @return a message string to use in the parse_error exceptions
  6078. */
  6079. std::string exception_message(const input_format_t format,
  6080. const std::string& detail,
  6081. const std::string& context) const
  6082. {
  6083. std::string error_msg = "syntax error while parsing ";
  6084. switch (format)
  6085. {
  6086. case input_format_t::cbor:
  6087. error_msg += "CBOR";
  6088. break;
  6089. case input_format_t::msgpack:
  6090. error_msg += "MessagePack";
  6091. break;
  6092. case input_format_t::ubjson:
  6093. error_msg += "UBJSON";
  6094. break;
  6095. case input_format_t::bson:
  6096. error_msg += "BSON";
  6097. break;
  6098. default: // LCOV_EXCL_LINE
  6099. assert(false); // LCOV_EXCL_LINE
  6100. }
  6101. return error_msg + " " + context + ": " + detail;
  6102. }
  6103. private:
  6104. /// input adapter
  6105. input_adapter_t ia = nullptr;
  6106. /// the current character
  6107. int current = std::char_traits<char>::eof();
  6108. /// the number of characters read
  6109. std::size_t chars_read = 0;
  6110. /// whether we can assume little endianess
  6111. const bool is_little_endian = little_endianess();
  6112. /// the SAX parser
  6113. json_sax_t* sax = nullptr;
  6114. };
  6115. } // namespace detail
  6116. } // namespace nlohmann
  6117. // #include <nlohmann/detail/input/input_adapters.hpp>
  6118. // #include <nlohmann/detail/input/lexer.hpp>
  6119. #include <array> // array
  6120. #include <clocale> // localeconv
  6121. #include <cstddef> // size_t
  6122. #include <cstdio> // snprintf
  6123. #include <cstdlib> // strtof, strtod, strtold, strtoll, strtoull
  6124. #include <initializer_list> // initializer_list
  6125. #include <string> // char_traits, string
  6126. #include <utility> // move
  6127. #include <vector> // vector
  6128. // #include <nlohmann/detail/input/input_adapters.hpp>
  6129. // #include <nlohmann/detail/input/position_t.hpp>
  6130. // #include <nlohmann/detail/macro_scope.hpp>
  6131. namespace nlohmann
  6132. {
  6133. namespace detail
  6134. {
  6135. ///////////
  6136. // lexer //
  6137. ///////////
  6138. /*!
  6139. @brief lexical analysis
  6140. This class organizes the lexical analysis during JSON deserialization.
  6141. */
  6142. template<typename BasicJsonType>
  6143. class lexer
  6144. {
  6145. using number_integer_t = typename BasicJsonType::number_integer_t;
  6146. using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
  6147. using number_float_t = typename BasicJsonType::number_float_t;
  6148. using string_t = typename BasicJsonType::string_t;
  6149. public:
  6150. /// token types for the parser
  6151. enum class token_type
  6152. {
  6153. uninitialized, ///< indicating the scanner is uninitialized
  6154. literal_true, ///< the `true` literal
  6155. literal_false, ///< the `false` literal
  6156. literal_null, ///< the `null` literal
  6157. value_string, ///< a string -- use get_string() for actual value
  6158. value_unsigned, ///< an unsigned integer -- use get_number_unsigned() for actual value
  6159. value_integer, ///< a signed integer -- use get_number_integer() for actual value
  6160. value_float, ///< an floating point number -- use get_number_float() for actual value
  6161. begin_array, ///< the character for array begin `[`
  6162. begin_object, ///< the character for object begin `{`
  6163. end_array, ///< the character for array end `]`
  6164. end_object, ///< the character for object end `}`
  6165. name_separator, ///< the name separator `:`
  6166. value_separator, ///< the value separator `,`
  6167. parse_error, ///< indicating a parse error
  6168. end_of_input, ///< indicating the end of the input buffer
  6169. literal_or_value ///< a literal or the begin of a value (only for diagnostics)
  6170. };
  6171. /// return name of values of type token_type (only used for errors)
  6172. JSON_HEDLEY_RETURNS_NON_NULL
  6173. JSON_HEDLEY_CONST
  6174. static const char* token_type_name(const token_type t) noexcept
  6175. {
  6176. switch (t)
  6177. {
  6178. case token_type::uninitialized:
  6179. return "<uninitialized>";
  6180. case token_type::literal_true:
  6181. return "true literal";
  6182. case token_type::literal_false:
  6183. return "false literal";
  6184. case token_type::literal_null:
  6185. return "null literal";
  6186. case token_type::value_string:
  6187. return "string literal";
  6188. case lexer::token_type::value_unsigned:
  6189. case lexer::token_type::value_integer:
  6190. case lexer::token_type::value_float:
  6191. return "number literal";
  6192. case token_type::begin_array:
  6193. return "'['";
  6194. case token_type::begin_object:
  6195. return "'{'";
  6196. case token_type::end_array:
  6197. return "']'";
  6198. case token_type::end_object:
  6199. return "'}'";
  6200. case token_type::name_separator:
  6201. return "':'";
  6202. case token_type::value_separator:
  6203. return "','";
  6204. case token_type::parse_error:
  6205. return "<parse error>";
  6206. case token_type::end_of_input:
  6207. return "end of input";
  6208. case token_type::literal_or_value:
  6209. return "'[', '{', or a literal";
  6210. // LCOV_EXCL_START
  6211. default: // catch non-enum values
  6212. return "unknown token";
  6213. // LCOV_EXCL_STOP
  6214. }
  6215. }
  6216. explicit lexer(detail::input_adapter_t&& adapter)
  6217. : ia(std::move(adapter)), decimal_point_char(get_decimal_point()) {}
  6218. // delete because of pointer members
  6219. lexer(const lexer&) = delete;
  6220. lexer(lexer&&) = delete;
  6221. lexer& operator=(lexer&) = delete;
  6222. lexer& operator=(lexer&&) = delete;
  6223. ~lexer() = default;
  6224. private:
  6225. /////////////////////
  6226. // locales
  6227. /////////////////////
  6228. /// return the locale-dependent decimal point
  6229. JSON_HEDLEY_PURE
  6230. static char get_decimal_point() noexcept
  6231. {
  6232. const auto loc = localeconv();
  6233. assert(loc != nullptr);
  6234. return (loc->decimal_point == nullptr) ? '.' : *(loc->decimal_point);
  6235. }
  6236. /////////////////////
  6237. // scan functions
  6238. /////////////////////
  6239. /*!
  6240. @brief get codepoint from 4 hex characters following `\u`
  6241. For input "\u c1 c2 c3 c4" the codepoint is:
  6242. (c1 * 0x1000) + (c2 * 0x0100) + (c3 * 0x0010) + c4
  6243. = (c1 << 12) + (c2 << 8) + (c3 << 4) + (c4 << 0)
  6244. Furthermore, the possible characters '0'..'9', 'A'..'F', and 'a'..'f'
  6245. must be converted to the integers 0x0..0x9, 0xA..0xF, 0xA..0xF, resp. The
  6246. conversion is done by subtracting the offset (0x30, 0x37, and 0x57)
  6247. between the ASCII value of the character and the desired integer value.
  6248. @return codepoint (0x0000..0xFFFF) or -1 in case of an error (e.g. EOF or
  6249. non-hex character)
  6250. */
  6251. int get_codepoint()
  6252. {
  6253. // this function only makes sense after reading `\u`
  6254. assert(current == 'u');
  6255. int codepoint = 0;
  6256. const auto factors = { 12u, 8u, 4u, 0u };
  6257. for (const auto factor : factors)
  6258. {
  6259. get();
  6260. if (current >= '0' and current <= '9')
  6261. {
  6262. codepoint += static_cast<int>((static_cast<unsigned int>(current) - 0x30u) << factor);
  6263. }
  6264. else if (current >= 'A' and current <= 'F')
  6265. {
  6266. codepoint += static_cast<int>((static_cast<unsigned int>(current) - 0x37u) << factor);
  6267. }
  6268. else if (current >= 'a' and current <= 'f')
  6269. {
  6270. codepoint += static_cast<int>((static_cast<unsigned int>(current) - 0x57u) << factor);
  6271. }
  6272. else
  6273. {
  6274. return -1;
  6275. }
  6276. }
  6277. assert(0x0000 <= codepoint and codepoint <= 0xFFFF);
  6278. return codepoint;
  6279. }
  6280. /*!
  6281. @brief check if the next byte(s) are inside a given range
  6282. Adds the current byte and, for each passed range, reads a new byte and
  6283. checks if it is inside the range. If a violation was detected, set up an
  6284. error message and return false. Otherwise, return true.
  6285. @param[in] ranges list of integers; interpreted as list of pairs of
  6286. inclusive lower and upper bound, respectively
  6287. @pre The passed list @a ranges must have 2, 4, or 6 elements; that is,
  6288. 1, 2, or 3 pairs. This precondition is enforced by an assertion.
  6289. @return true if and only if no range violation was detected
  6290. */
  6291. bool next_byte_in_range(std::initializer_list<int> ranges)
  6292. {
  6293. assert(ranges.size() == 2 or ranges.size() == 4 or ranges.size() == 6);
  6294. add(current);
  6295. for (auto range = ranges.begin(); range != ranges.end(); ++range)
  6296. {
  6297. get();
  6298. if (JSON_HEDLEY_LIKELY(*range <= current and current <= *(++range)))
  6299. {
  6300. add(current);
  6301. }
  6302. else
  6303. {
  6304. error_message = "invalid string: ill-formed UTF-8 byte";
  6305. return false;
  6306. }
  6307. }
  6308. return true;
  6309. }
  6310. /*!
  6311. @brief scan a string literal
  6312. This function scans a string according to Sect. 7 of RFC 7159. While
  6313. scanning, bytes are escaped and copied into buffer token_buffer. Then the
  6314. function returns successfully, token_buffer is *not* null-terminated (as it
  6315. may contain \0 bytes), and token_buffer.size() is the number of bytes in the
  6316. string.
  6317. @return token_type::value_string if string could be successfully scanned,
  6318. token_type::parse_error otherwise
  6319. @note In case of errors, variable error_message contains a textual
  6320. description.
  6321. */
  6322. token_type scan_string()
  6323. {
  6324. // reset token_buffer (ignore opening quote)
  6325. reset();
  6326. // we entered the function by reading an open quote
  6327. assert(current == '\"');
  6328. while (true)
  6329. {
  6330. // get next character
  6331. switch (get())
  6332. {
  6333. // end of file while parsing string
  6334. case std::char_traits<char>::eof():
  6335. {
  6336. error_message = "invalid string: missing closing quote";
  6337. return token_type::parse_error;
  6338. }
  6339. // closing quote
  6340. case '\"':
  6341. {
  6342. return token_type::value_string;
  6343. }
  6344. // escapes
  6345. case '\\':
  6346. {
  6347. switch (get())
  6348. {
  6349. // quotation mark
  6350. case '\"':
  6351. add('\"');
  6352. break;
  6353. // reverse solidus
  6354. case '\\':
  6355. add('\\');
  6356. break;
  6357. // solidus
  6358. case '/':
  6359. add('/');
  6360. break;
  6361. // backspace
  6362. case 'b':
  6363. add('\b');
  6364. break;
  6365. // form feed
  6366. case 'f':
  6367. add('\f');
  6368. break;
  6369. // line feed
  6370. case 'n':
  6371. add('\n');
  6372. break;
  6373. // carriage return
  6374. case 'r':
  6375. add('\r');
  6376. break;
  6377. // tab
  6378. case 't':
  6379. add('\t');
  6380. break;
  6381. // unicode escapes
  6382. case 'u':
  6383. {
  6384. const int codepoint1 = get_codepoint();
  6385. int codepoint = codepoint1; // start with codepoint1
  6386. if (JSON_HEDLEY_UNLIKELY(codepoint1 == -1))
  6387. {
  6388. error_message = "invalid string: '\\u' must be followed by 4 hex digits";
  6389. return token_type::parse_error;
  6390. }
  6391. // check if code point is a high surrogate
  6392. if (0xD800 <= codepoint1 and codepoint1 <= 0xDBFF)
  6393. {
  6394. // expect next \uxxxx entry
  6395. if (JSON_HEDLEY_LIKELY(get() == '\\' and get() == 'u'))
  6396. {
  6397. const int codepoint2 = get_codepoint();
  6398. if (JSON_HEDLEY_UNLIKELY(codepoint2 == -1))
  6399. {
  6400. error_message = "invalid string: '\\u' must be followed by 4 hex digits";
  6401. return token_type::parse_error;
  6402. }
  6403. // check if codepoint2 is a low surrogate
  6404. if (JSON_HEDLEY_LIKELY(0xDC00 <= codepoint2 and codepoint2 <= 0xDFFF))
  6405. {
  6406. // overwrite codepoint
  6407. codepoint = static_cast<int>(
  6408. // high surrogate occupies the most significant 22 bits
  6409. (static_cast<unsigned int>(codepoint1) << 10u)
  6410. // low surrogate occupies the least significant 15 bits
  6411. + static_cast<unsigned int>(codepoint2)
  6412. // there is still the 0xD800, 0xDC00 and 0x10000 noise
  6413. // in the result so we have to subtract with:
  6414. // (0xD800 << 10) + DC00 - 0x10000 = 0x35FDC00
  6415. - 0x35FDC00u);
  6416. }
  6417. else
  6418. {
  6419. error_message = "invalid string: surrogate U+DC00..U+DFFF must be followed by U+DC00..U+DFFF";
  6420. return token_type::parse_error;
  6421. }
  6422. }
  6423. else
  6424. {
  6425. error_message = "invalid string: surrogate U+DC00..U+DFFF must be followed by U+DC00..U+DFFF";
  6426. return token_type::parse_error;
  6427. }
  6428. }
  6429. else
  6430. {
  6431. if (JSON_HEDLEY_UNLIKELY(0xDC00 <= codepoint1 and codepoint1 <= 0xDFFF))
  6432. {
  6433. error_message = "invalid string: surrogate U+DC00..U+DFFF must follow U+D800..U+DBFF";
  6434. return token_type::parse_error;
  6435. }
  6436. }
  6437. // result of the above calculation yields a proper codepoint
  6438. assert(0x00 <= codepoint and codepoint <= 0x10FFFF);
  6439. // translate codepoint into bytes
  6440. if (codepoint < 0x80)
  6441. {
  6442. // 1-byte characters: 0xxxxxxx (ASCII)
  6443. add(codepoint);
  6444. }
  6445. else if (codepoint <= 0x7FF)
  6446. {
  6447. // 2-byte characters: 110xxxxx 10xxxxxx
  6448. add(static_cast<int>(0xC0u | (static_cast<unsigned int>(codepoint) >> 6u)));
  6449. add(static_cast<int>(0x80u | (static_cast<unsigned int>(codepoint) & 0x3Fu)));
  6450. }
  6451. else if (codepoint <= 0xFFFF)
  6452. {
  6453. // 3-byte characters: 1110xxxx 10xxxxxx 10xxxxxx
  6454. add(static_cast<int>(0xE0u | (static_cast<unsigned int>(codepoint) >> 12u)));
  6455. add(static_cast<int>(0x80u | ((static_cast<unsigned int>(codepoint) >> 6u) & 0x3Fu)));
  6456. add(static_cast<int>(0x80u | (static_cast<unsigned int>(codepoint) & 0x3Fu)));
  6457. }
  6458. else
  6459. {
  6460. // 4-byte characters: 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
  6461. add(static_cast<int>(0xF0u | (static_cast<unsigned int>(codepoint) >> 18u)));
  6462. add(static_cast<int>(0x80u | ((static_cast<unsigned int>(codepoint) >> 12u) & 0x3Fu)));
  6463. add(static_cast<int>(0x80u | ((static_cast<unsigned int>(codepoint) >> 6u) & 0x3Fu)));
  6464. add(static_cast<int>(0x80u | (static_cast<unsigned int>(codepoint) & 0x3Fu)));
  6465. }
  6466. break;
  6467. }
  6468. // other characters after escape
  6469. default:
  6470. error_message = "invalid string: forbidden character after backslash";
  6471. return token_type::parse_error;
  6472. }
  6473. break;
  6474. }
  6475. // invalid control characters
  6476. case 0x00:
  6477. {
  6478. error_message = "invalid string: control character U+0000 (NUL) must be escaped to \\u0000";
  6479. return token_type::parse_error;
  6480. }
  6481. case 0x01:
  6482. {
  6483. error_message = "invalid string: control character U+0001 (SOH) must be escaped to \\u0001";
  6484. return token_type::parse_error;
  6485. }
  6486. case 0x02:
  6487. {
  6488. error_message = "invalid string: control character U+0002 (STX) must be escaped to \\u0002";
  6489. return token_type::parse_error;
  6490. }
  6491. case 0x03:
  6492. {
  6493. error_message = "invalid string: control character U+0003 (ETX) must be escaped to \\u0003";
  6494. return token_type::parse_error;
  6495. }
  6496. case 0x04:
  6497. {
  6498. error_message = "invalid string: control character U+0004 (EOT) must be escaped to \\u0004";
  6499. return token_type::parse_error;
  6500. }
  6501. case 0x05:
  6502. {
  6503. error_message = "invalid string: control character U+0005 (ENQ) must be escaped to \\u0005";
  6504. return token_type::parse_error;
  6505. }
  6506. case 0x06:
  6507. {
  6508. error_message = "invalid string: control character U+0006 (ACK) must be escaped to \\u0006";
  6509. return token_type::parse_error;
  6510. }
  6511. case 0x07:
  6512. {
  6513. error_message = "invalid string: control character U+0007 (BEL) must be escaped to \\u0007";
  6514. return token_type::parse_error;
  6515. }
  6516. case 0x08:
  6517. {
  6518. error_message = "invalid string: control character U+0008 (BS) must be escaped to \\u0008 or \\b";
  6519. return token_type::parse_error;
  6520. }
  6521. case 0x09:
  6522. {
  6523. error_message = "invalid string: control character U+0009 (HT) must be escaped to \\u0009 or \\t";
  6524. return token_type::parse_error;
  6525. }
  6526. case 0x0A:
  6527. {
  6528. error_message = "invalid string: control character U+000A (LF) must be escaped to \\u000A or \\n";
  6529. return token_type::parse_error;
  6530. }
  6531. case 0x0B:
  6532. {
  6533. error_message = "invalid string: control character U+000B (VT) must be escaped to \\u000B";
  6534. return token_type::parse_error;
  6535. }
  6536. case 0x0C:
  6537. {
  6538. error_message = "invalid string: control character U+000C (FF) must be escaped to \\u000C or \\f";
  6539. return token_type::parse_error;
  6540. }
  6541. case 0x0D:
  6542. {
  6543. error_message = "invalid string: control character U+000D (CR) must be escaped to \\u000D or \\r";
  6544. return token_type::parse_error;
  6545. }
  6546. case 0x0E:
  6547. {
  6548. error_message = "invalid string: control character U+000E (SO) must be escaped to \\u000E";
  6549. return token_type::parse_error;
  6550. }
  6551. case 0x0F:
  6552. {
  6553. error_message = "invalid string: control character U+000F (SI) must be escaped to \\u000F";
  6554. return token_type::parse_error;
  6555. }
  6556. case 0x10:
  6557. {
  6558. error_message = "invalid string: control character U+0010 (DLE) must be escaped to \\u0010";
  6559. return token_type::parse_error;
  6560. }
  6561. case 0x11:
  6562. {
  6563. error_message = "invalid string: control character U+0011 (DC1) must be escaped to \\u0011";
  6564. return token_type::parse_error;
  6565. }
  6566. case 0x12:
  6567. {
  6568. error_message = "invalid string: control character U+0012 (DC2) must be escaped to \\u0012";
  6569. return token_type::parse_error;
  6570. }
  6571. case 0x13:
  6572. {
  6573. error_message = "invalid string: control character U+0013 (DC3) must be escaped to \\u0013";
  6574. return token_type::parse_error;
  6575. }
  6576. case 0x14:
  6577. {
  6578. error_message = "invalid string: control character U+0014 (DC4) must be escaped to \\u0014";
  6579. return token_type::parse_error;
  6580. }
  6581. case 0x15:
  6582. {
  6583. error_message = "invalid string: control character U+0015 (NAK) must be escaped to \\u0015";
  6584. return token_type::parse_error;
  6585. }
  6586. case 0x16:
  6587. {
  6588. error_message = "invalid string: control character U+0016 (SYN) must be escaped to \\u0016";
  6589. return token_type::parse_error;
  6590. }
  6591. case 0x17:
  6592. {
  6593. error_message = "invalid string: control character U+0017 (ETB) must be escaped to \\u0017";
  6594. return token_type::parse_error;
  6595. }
  6596. case 0x18:
  6597. {
  6598. error_message = "invalid string: control character U+0018 (CAN) must be escaped to \\u0018";
  6599. return token_type::parse_error;
  6600. }
  6601. case 0x19:
  6602. {
  6603. error_message = "invalid string: control character U+0019 (EM) must be escaped to \\u0019";
  6604. return token_type::parse_error;
  6605. }
  6606. case 0x1A:
  6607. {
  6608. error_message = "invalid string: control character U+001A (SUB) must be escaped to \\u001A";
  6609. return token_type::parse_error;
  6610. }
  6611. case 0x1B:
  6612. {
  6613. error_message = "invalid string: control character U+001B (ESC) must be escaped to \\u001B";
  6614. return token_type::parse_error;
  6615. }
  6616. case 0x1C:
  6617. {
  6618. error_message = "invalid string: control character U+001C (FS) must be escaped to \\u001C";
  6619. return token_type::parse_error;
  6620. }
  6621. case 0x1D:
  6622. {
  6623. error_message = "invalid string: control character U+001D (GS) must be escaped to \\u001D";
  6624. return token_type::parse_error;
  6625. }
  6626. case 0x1E:
  6627. {
  6628. error_message = "invalid string: control character U+001E (RS) must be escaped to \\u001E";
  6629. return token_type::parse_error;
  6630. }
  6631. case 0x1F:
  6632. {
  6633. error_message = "invalid string: control character U+001F (US) must be escaped to \\u001F";
  6634. return token_type::parse_error;
  6635. }
  6636. // U+0020..U+007F (except U+0022 (quote) and U+005C (backspace))
  6637. case 0x20:
  6638. case 0x21:
  6639. case 0x23:
  6640. case 0x24:
  6641. case 0x25:
  6642. case 0x26:
  6643. case 0x27:
  6644. case 0x28:
  6645. case 0x29:
  6646. case 0x2A:
  6647. case 0x2B:
  6648. case 0x2C:
  6649. case 0x2D:
  6650. case 0x2E:
  6651. case 0x2F:
  6652. case 0x30:
  6653. case 0x31:
  6654. case 0x32:
  6655. case 0x33:
  6656. case 0x34:
  6657. case 0x35:
  6658. case 0x36:
  6659. case 0x37:
  6660. case 0x38:
  6661. case 0x39:
  6662. case 0x3A:
  6663. case 0x3B:
  6664. case 0x3C:
  6665. case 0x3D:
  6666. case 0x3E:
  6667. case 0x3F:
  6668. case 0x40:
  6669. case 0x41:
  6670. case 0x42:
  6671. case 0x43:
  6672. case 0x44:
  6673. case 0x45:
  6674. case 0x46:
  6675. case 0x47:
  6676. case 0x48:
  6677. case 0x49:
  6678. case 0x4A:
  6679. case 0x4B:
  6680. case 0x4C:
  6681. case 0x4D:
  6682. case 0x4E:
  6683. case 0x4F:
  6684. case 0x50:
  6685. case 0x51:
  6686. case 0x52:
  6687. case 0x53:
  6688. case 0x54:
  6689. case 0x55:
  6690. case 0x56:
  6691. case 0x57:
  6692. case 0x58:
  6693. case 0x59:
  6694. case 0x5A:
  6695. case 0x5B:
  6696. case 0x5D:
  6697. case 0x5E:
  6698. case 0x5F:
  6699. case 0x60:
  6700. case 0x61:
  6701. case 0x62:
  6702. case 0x63:
  6703. case 0x64:
  6704. case 0x65:
  6705. case 0x66:
  6706. case 0x67:
  6707. case 0x68:
  6708. case 0x69:
  6709. case 0x6A:
  6710. case 0x6B:
  6711. case 0x6C:
  6712. case 0x6D:
  6713. case 0x6E:
  6714. case 0x6F:
  6715. case 0x70:
  6716. case 0x71:
  6717. case 0x72:
  6718. case 0x73:
  6719. case 0x74:
  6720. case 0x75:
  6721. case 0x76:
  6722. case 0x77:
  6723. case 0x78:
  6724. case 0x79:
  6725. case 0x7A:
  6726. case 0x7B:
  6727. case 0x7C:
  6728. case 0x7D:
  6729. case 0x7E:
  6730. case 0x7F:
  6731. {
  6732. add(current);
  6733. break;
  6734. }
  6735. // U+0080..U+07FF: bytes C2..DF 80..BF
  6736. case 0xC2:
  6737. case 0xC3:
  6738. case 0xC4:
  6739. case 0xC5:
  6740. case 0xC6:
  6741. case 0xC7:
  6742. case 0xC8:
  6743. case 0xC9:
  6744. case 0xCA:
  6745. case 0xCB:
  6746. case 0xCC:
  6747. case 0xCD:
  6748. case 0xCE:
  6749. case 0xCF:
  6750. case 0xD0:
  6751. case 0xD1:
  6752. case 0xD2:
  6753. case 0xD3:
  6754. case 0xD4:
  6755. case 0xD5:
  6756. case 0xD6:
  6757. case 0xD7:
  6758. case 0xD8:
  6759. case 0xD9:
  6760. case 0xDA:
  6761. case 0xDB:
  6762. case 0xDC:
  6763. case 0xDD:
  6764. case 0xDE:
  6765. case 0xDF:
  6766. {
  6767. if (JSON_HEDLEY_UNLIKELY(not next_byte_in_range({0x80, 0xBF})))
  6768. {
  6769. return token_type::parse_error;
  6770. }
  6771. break;
  6772. }
  6773. // U+0800..U+0FFF: bytes E0 A0..BF 80..BF
  6774. case 0xE0:
  6775. {
  6776. if (JSON_HEDLEY_UNLIKELY(not (next_byte_in_range({0xA0, 0xBF, 0x80, 0xBF}))))
  6777. {
  6778. return token_type::parse_error;
  6779. }
  6780. break;
  6781. }
  6782. // U+1000..U+CFFF: bytes E1..EC 80..BF 80..BF
  6783. // U+E000..U+FFFF: bytes EE..EF 80..BF 80..BF
  6784. case 0xE1:
  6785. case 0xE2:
  6786. case 0xE3:
  6787. case 0xE4:
  6788. case 0xE5:
  6789. case 0xE6:
  6790. case 0xE7:
  6791. case 0xE8:
  6792. case 0xE9:
  6793. case 0xEA:
  6794. case 0xEB:
  6795. case 0xEC:
  6796. case 0xEE:
  6797. case 0xEF:
  6798. {
  6799. if (JSON_HEDLEY_UNLIKELY(not (next_byte_in_range({0x80, 0xBF, 0x80, 0xBF}))))
  6800. {
  6801. return token_type::parse_error;
  6802. }
  6803. break;
  6804. }
  6805. // U+D000..U+D7FF: bytes ED 80..9F 80..BF
  6806. case 0xED:
  6807. {
  6808. if (JSON_HEDLEY_UNLIKELY(not (next_byte_in_range({0x80, 0x9F, 0x80, 0xBF}))))
  6809. {
  6810. return token_type::parse_error;
  6811. }
  6812. break;
  6813. }
  6814. // U+10000..U+3FFFF F0 90..BF 80..BF 80..BF
  6815. case 0xF0:
  6816. {
  6817. if (JSON_HEDLEY_UNLIKELY(not (next_byte_in_range({0x90, 0xBF, 0x80, 0xBF, 0x80, 0xBF}))))
  6818. {
  6819. return token_type::parse_error;
  6820. }
  6821. break;
  6822. }
  6823. // U+40000..U+FFFFF F1..F3 80..BF 80..BF 80..BF
  6824. case 0xF1:
  6825. case 0xF2:
  6826. case 0xF3:
  6827. {
  6828. if (JSON_HEDLEY_UNLIKELY(not (next_byte_in_range({0x80, 0xBF, 0x80, 0xBF, 0x80, 0xBF}))))
  6829. {
  6830. return token_type::parse_error;
  6831. }
  6832. break;
  6833. }
  6834. // U+100000..U+10FFFF F4 80..8F 80..BF 80..BF
  6835. case 0xF4:
  6836. {
  6837. if (JSON_HEDLEY_UNLIKELY(not (next_byte_in_range({0x80, 0x8F, 0x80, 0xBF, 0x80, 0xBF}))))
  6838. {
  6839. return token_type::parse_error;
  6840. }
  6841. break;
  6842. }
  6843. // remaining bytes (80..C1 and F5..FF) are ill-formed
  6844. default:
  6845. {
  6846. error_message = "invalid string: ill-formed UTF-8 byte";
  6847. return token_type::parse_error;
  6848. }
  6849. }
  6850. }
  6851. }
  6852. JSON_HEDLEY_NON_NULL(2)
  6853. static void strtof(float& f, const char* str, char** endptr) noexcept
  6854. {
  6855. f = std::strtof(str, endptr);
  6856. }
  6857. JSON_HEDLEY_NON_NULL(2)
  6858. static void strtof(double& f, const char* str, char** endptr) noexcept
  6859. {
  6860. f = std::strtod(str, endptr);
  6861. }
  6862. JSON_HEDLEY_NON_NULL(2)
  6863. static void strtof(long double& f, const char* str, char** endptr) noexcept
  6864. {
  6865. f = std::strtold(str, endptr);
  6866. }
  6867. /*!
  6868. @brief scan a number literal
  6869. This function scans a string according to Sect. 6 of RFC 7159.
  6870. The function is realized with a deterministic finite state machine derived
  6871. from the grammar described in RFC 7159. Starting in state "init", the
  6872. input is read and used to determined the next state. Only state "done"
  6873. accepts the number. State "error" is a trap state to model errors. In the
  6874. table below, "anything" means any character but the ones listed before.
  6875. state | 0 | 1-9 | e E | + | - | . | anything
  6876. ---------|----------|----------|----------|---------|---------|----------|-----------
  6877. init | zero | any1 | [error] | [error] | minus | [error] | [error]
  6878. minus | zero | any1 | [error] | [error] | [error] | [error] | [error]
  6879. zero | done | done | exponent | done | done | decimal1 | done
  6880. any1 | any1 | any1 | exponent | done | done | decimal1 | done
  6881. decimal1 | decimal2 | [error] | [error] | [error] | [error] | [error] | [error]
  6882. decimal2 | decimal2 | decimal2 | exponent | done | done | done | done
  6883. exponent | any2 | any2 | [error] | sign | sign | [error] | [error]
  6884. sign | any2 | any2 | [error] | [error] | [error] | [error] | [error]
  6885. any2 | any2 | any2 | done | done | done | done | done
  6886. The state machine is realized with one label per state (prefixed with
  6887. "scan_number_") and `goto` statements between them. The state machine
  6888. contains cycles, but any cycle can be left when EOF is read. Therefore,
  6889. the function is guaranteed to terminate.
  6890. During scanning, the read bytes are stored in token_buffer. This string is
  6891. then converted to a signed integer, an unsigned integer, or a
  6892. floating-point number.
  6893. @return token_type::value_unsigned, token_type::value_integer, or
  6894. token_type::value_float if number could be successfully scanned,
  6895. token_type::parse_error otherwise
  6896. @note The scanner is independent of the current locale. Internally, the
  6897. locale's decimal point is used instead of `.` to work with the
  6898. locale-dependent converters.
  6899. */
  6900. token_type scan_number() // lgtm [cpp/use-of-goto]
  6901. {
  6902. // reset token_buffer to store the number's bytes
  6903. reset();
  6904. // the type of the parsed number; initially set to unsigned; will be
  6905. // changed if minus sign, decimal point or exponent is read
  6906. token_type number_type = token_type::value_unsigned;
  6907. // state (init): we just found out we need to scan a number
  6908. switch (current)
  6909. {
  6910. case '-':
  6911. {
  6912. add(current);
  6913. goto scan_number_minus;
  6914. }
  6915. case '0':
  6916. {
  6917. add(current);
  6918. goto scan_number_zero;
  6919. }
  6920. case '1':
  6921. case '2':
  6922. case '3':
  6923. case '4':
  6924. case '5':
  6925. case '6':
  6926. case '7':
  6927. case '8':
  6928. case '9':
  6929. {
  6930. add(current);
  6931. goto scan_number_any1;
  6932. }
  6933. // all other characters are rejected outside scan_number()
  6934. default: // LCOV_EXCL_LINE
  6935. assert(false); // LCOV_EXCL_LINE
  6936. }
  6937. scan_number_minus:
  6938. // state: we just parsed a leading minus sign
  6939. number_type = token_type::value_integer;
  6940. switch (get())
  6941. {
  6942. case '0':
  6943. {
  6944. add(current);
  6945. goto scan_number_zero;
  6946. }
  6947. case '1':
  6948. case '2':
  6949. case '3':
  6950. case '4':
  6951. case '5':
  6952. case '6':
  6953. case '7':
  6954. case '8':
  6955. case '9':
  6956. {
  6957. add(current);
  6958. goto scan_number_any1;
  6959. }
  6960. default:
  6961. {
  6962. error_message = "invalid number; expected digit after '-'";
  6963. return token_type::parse_error;
  6964. }
  6965. }
  6966. scan_number_zero:
  6967. // state: we just parse a zero (maybe with a leading minus sign)
  6968. switch (get())
  6969. {
  6970. case '.':
  6971. {
  6972. add(decimal_point_char);
  6973. goto scan_number_decimal1;
  6974. }
  6975. case 'e':
  6976. case 'E':
  6977. {
  6978. add(current);
  6979. goto scan_number_exponent;
  6980. }
  6981. default:
  6982. goto scan_number_done;
  6983. }
  6984. scan_number_any1:
  6985. // state: we just parsed a number 0-9 (maybe with a leading minus sign)
  6986. switch (get())
  6987. {
  6988. case '0':
  6989. case '1':
  6990. case '2':
  6991. case '3':
  6992. case '4':
  6993. case '5':
  6994. case '6':
  6995. case '7':
  6996. case '8':
  6997. case '9':
  6998. {
  6999. add(current);
  7000. goto scan_number_any1;
  7001. }
  7002. case '.':
  7003. {
  7004. add(decimal_point_char);
  7005. goto scan_number_decimal1;
  7006. }
  7007. case 'e':
  7008. case 'E':
  7009. {
  7010. add(current);
  7011. goto scan_number_exponent;
  7012. }
  7013. default:
  7014. goto scan_number_done;
  7015. }
  7016. scan_number_decimal1:
  7017. // state: we just parsed a decimal point
  7018. number_type = token_type::value_float;
  7019. switch (get())
  7020. {
  7021. case '0':
  7022. case '1':
  7023. case '2':
  7024. case '3':
  7025. case '4':
  7026. case '5':
  7027. case '6':
  7028. case '7':
  7029. case '8':
  7030. case '9':
  7031. {
  7032. add(current);
  7033. goto scan_number_decimal2;
  7034. }
  7035. default:
  7036. {
  7037. error_message = "invalid number; expected digit after '.'";
  7038. return token_type::parse_error;
  7039. }
  7040. }
  7041. scan_number_decimal2:
  7042. // we just parsed at least one number after a decimal point
  7043. switch (get())
  7044. {
  7045. case '0':
  7046. case '1':
  7047. case '2':
  7048. case '3':
  7049. case '4':
  7050. case '5':
  7051. case '6':
  7052. case '7':
  7053. case '8':
  7054. case '9':
  7055. {
  7056. add(current);
  7057. goto scan_number_decimal2;
  7058. }
  7059. case 'e':
  7060. case 'E':
  7061. {
  7062. add(current);
  7063. goto scan_number_exponent;
  7064. }
  7065. default:
  7066. goto scan_number_done;
  7067. }
  7068. scan_number_exponent:
  7069. // we just parsed an exponent
  7070. number_type = token_type::value_float;
  7071. switch (get())
  7072. {
  7073. case '+':
  7074. case '-':
  7075. {
  7076. add(current);
  7077. goto scan_number_sign;
  7078. }
  7079. case '0':
  7080. case '1':
  7081. case '2':
  7082. case '3':
  7083. case '4':
  7084. case '5':
  7085. case '6':
  7086. case '7':
  7087. case '8':
  7088. case '9':
  7089. {
  7090. add(current);
  7091. goto scan_number_any2;
  7092. }
  7093. default:
  7094. {
  7095. error_message =
  7096. "invalid number; expected '+', '-', or digit after exponent";
  7097. return token_type::parse_error;
  7098. }
  7099. }
  7100. scan_number_sign:
  7101. // we just parsed an exponent sign
  7102. switch (get())
  7103. {
  7104. case '0':
  7105. case '1':
  7106. case '2':
  7107. case '3':
  7108. case '4':
  7109. case '5':
  7110. case '6':
  7111. case '7':
  7112. case '8':
  7113. case '9':
  7114. {
  7115. add(current);
  7116. goto scan_number_any2;
  7117. }
  7118. default:
  7119. {
  7120. error_message = "invalid number; expected digit after exponent sign";
  7121. return token_type::parse_error;
  7122. }
  7123. }
  7124. scan_number_any2:
  7125. // we just parsed a number after the exponent or exponent sign
  7126. switch (get())
  7127. {
  7128. case '0':
  7129. case '1':
  7130. case '2':
  7131. case '3':
  7132. case '4':
  7133. case '5':
  7134. case '6':
  7135. case '7':
  7136. case '8':
  7137. case '9':
  7138. {
  7139. add(current);
  7140. goto scan_number_any2;
  7141. }
  7142. default:
  7143. goto scan_number_done;
  7144. }
  7145. scan_number_done:
  7146. // unget the character after the number (we only read it to know that
  7147. // we are done scanning a number)
  7148. unget();
  7149. char* endptr = nullptr;
  7150. errno = 0;
  7151. // try to parse integers first and fall back to floats
  7152. if (number_type == token_type::value_unsigned)
  7153. {
  7154. const auto x = std::strtoull(token_buffer.data(), &endptr, 10);
  7155. // we checked the number format before
  7156. assert(endptr == token_buffer.data() + token_buffer.size());
  7157. if (errno == 0)
  7158. {
  7159. value_unsigned = static_cast<number_unsigned_t>(x);
  7160. if (value_unsigned == x)
  7161. {
  7162. return token_type::value_unsigned;
  7163. }
  7164. }
  7165. }
  7166. else if (number_type == token_type::value_integer)
  7167. {
  7168. const auto x = std::strtoll(token_buffer.data(), &endptr, 10);
  7169. // we checked the number format before
  7170. assert(endptr == token_buffer.data() + token_buffer.size());
  7171. if (errno == 0)
  7172. {
  7173. value_integer = static_cast<number_integer_t>(x);
  7174. if (value_integer == x)
  7175. {
  7176. return token_type::value_integer;
  7177. }
  7178. }
  7179. }
  7180. // this code is reached if we parse a floating-point number or if an
  7181. // integer conversion above failed
  7182. strtof(value_float, token_buffer.data(), &endptr);
  7183. // we checked the number format before
  7184. assert(endptr == token_buffer.data() + token_buffer.size());
  7185. return token_type::value_float;
  7186. }
  7187. /*!
  7188. @param[in] literal_text the literal text to expect
  7189. @param[in] length the length of the passed literal text
  7190. @param[in] return_type the token type to return on success
  7191. */
  7192. JSON_HEDLEY_NON_NULL(2)
  7193. token_type scan_literal(const char* literal_text, const std::size_t length,
  7194. token_type return_type)
  7195. {
  7196. assert(current == literal_text[0]);
  7197. for (std::size_t i = 1; i < length; ++i)
  7198. {
  7199. if (JSON_HEDLEY_UNLIKELY(get() != literal_text[i]))
  7200. {
  7201. error_message = "invalid literal";
  7202. return token_type::parse_error;
  7203. }
  7204. }
  7205. return return_type;
  7206. }
  7207. /////////////////////
  7208. // input management
  7209. /////////////////////
  7210. /// reset token_buffer; current character is beginning of token
  7211. void reset() noexcept
  7212. {
  7213. token_buffer.clear();
  7214. token_string.clear();
  7215. token_string.push_back(std::char_traits<char>::to_char_type(current));
  7216. }
  7217. /*
  7218. @brief get next character from the input
  7219. This function provides the interface to the used input adapter. It does
  7220. not throw in case the input reached EOF, but returns a
  7221. `std::char_traits<char>::eof()` in that case. Stores the scanned characters
  7222. for use in error messages.
  7223. @return character read from the input
  7224. */
  7225. std::char_traits<char>::int_type get()
  7226. {
  7227. ++position.chars_read_total;
  7228. ++position.chars_read_current_line;
  7229. if (next_unget)
  7230. {
  7231. // just reset the next_unget variable and work with current
  7232. next_unget = false;
  7233. }
  7234. else
  7235. {
  7236. current = ia->get_character();
  7237. }
  7238. if (JSON_HEDLEY_LIKELY(current != std::char_traits<char>::eof()))
  7239. {
  7240. token_string.push_back(std::char_traits<char>::to_char_type(current));
  7241. }
  7242. if (current == '\n')
  7243. {
  7244. ++position.lines_read;
  7245. position.chars_read_current_line = 0;
  7246. }
  7247. return current;
  7248. }
  7249. /*!
  7250. @brief unget current character (read it again on next get)
  7251. We implement unget by setting variable next_unget to true. The input is not
  7252. changed - we just simulate ungetting by modifying chars_read_total,
  7253. chars_read_current_line, and token_string. The next call to get() will
  7254. behave as if the unget character is read again.
  7255. */
  7256. void unget()
  7257. {
  7258. next_unget = true;
  7259. --position.chars_read_total;
  7260. // in case we "unget" a newline, we have to also decrement the lines_read
  7261. if (position.chars_read_current_line == 0)
  7262. {
  7263. if (position.lines_read > 0)
  7264. {
  7265. --position.lines_read;
  7266. }
  7267. }
  7268. else
  7269. {
  7270. --position.chars_read_current_line;
  7271. }
  7272. if (JSON_HEDLEY_LIKELY(current != std::char_traits<char>::eof()))
  7273. {
  7274. assert(not token_string.empty());
  7275. token_string.pop_back();
  7276. }
  7277. }
  7278. /// add a character to token_buffer
  7279. void add(int c)
  7280. {
  7281. token_buffer.push_back(std::char_traits<char>::to_char_type(c));
  7282. }
  7283. public:
  7284. /////////////////////
  7285. // value getters
  7286. /////////////////////
  7287. /// return integer value
  7288. constexpr number_integer_t get_number_integer() const noexcept
  7289. {
  7290. return value_integer;
  7291. }
  7292. /// return unsigned integer value
  7293. constexpr number_unsigned_t get_number_unsigned() const noexcept
  7294. {
  7295. return value_unsigned;
  7296. }
  7297. /// return floating-point value
  7298. constexpr number_float_t get_number_float() const noexcept
  7299. {
  7300. return value_float;
  7301. }
  7302. /// return current string value (implicitly resets the token; useful only once)
  7303. string_t& get_string()
  7304. {
  7305. return token_buffer;
  7306. }
  7307. /////////////////////
  7308. // diagnostics
  7309. /////////////////////
  7310. /// return position of last read token
  7311. constexpr position_t get_position() const noexcept
  7312. {
  7313. return position;
  7314. }
  7315. /// return the last read token (for errors only). Will never contain EOF
  7316. /// (an arbitrary value that is not a valid char value, often -1), because
  7317. /// 255 may legitimately occur. May contain NUL, which should be escaped.
  7318. std::string get_token_string() const
  7319. {
  7320. // escape control characters
  7321. std::string result;
  7322. for (const auto c : token_string)
  7323. {
  7324. if ('\x00' <= c and c <= '\x1F')
  7325. {
  7326. // escape control characters
  7327. std::array<char, 9> cs{{}};
  7328. (std::snprintf)(cs.data(), cs.size(), "<U+%.4X>", static_cast<unsigned char>(c));
  7329. result += cs.data();
  7330. }
  7331. else
  7332. {
  7333. // add character as is
  7334. result.push_back(c);
  7335. }
  7336. }
  7337. return result;
  7338. }
  7339. /// return syntax error message
  7340. JSON_HEDLEY_RETURNS_NON_NULL
  7341. constexpr const char* get_error_message() const noexcept
  7342. {
  7343. return error_message;
  7344. }
  7345. /////////////////////
  7346. // actual scanner
  7347. /////////////////////
  7348. /*!
  7349. @brief skip the UTF-8 byte order mark
  7350. @return true iff there is no BOM or the correct BOM has been skipped
  7351. */
  7352. bool skip_bom()
  7353. {
  7354. if (get() == 0xEF)
  7355. {
  7356. // check if we completely parse the BOM
  7357. return get() == 0xBB and get() == 0xBF;
  7358. }
  7359. // the first character is not the beginning of the BOM; unget it to
  7360. // process is later
  7361. unget();
  7362. return true;
  7363. }
  7364. token_type scan()
  7365. {
  7366. // initially, skip the BOM
  7367. if (position.chars_read_total == 0 and not skip_bom())
  7368. {
  7369. error_message = "invalid BOM; must be 0xEF 0xBB 0xBF if given";
  7370. return token_type::parse_error;
  7371. }
  7372. // read next character and ignore whitespace
  7373. do
  7374. {
  7375. get();
  7376. }
  7377. while (current == ' ' or current == '\t' or current == '\n' or current == '\r');
  7378. switch (current)
  7379. {
  7380. // structural characters
  7381. case '[':
  7382. return token_type::begin_array;
  7383. case ']':
  7384. return token_type::end_array;
  7385. case '{':
  7386. return token_type::begin_object;
  7387. case '}':
  7388. return token_type::end_object;
  7389. case ':':
  7390. return token_type::name_separator;
  7391. case ',':
  7392. return token_type::value_separator;
  7393. // literals
  7394. case 't':
  7395. return scan_literal("true", 4, token_type::literal_true);
  7396. case 'f':
  7397. return scan_literal("false", 5, token_type::literal_false);
  7398. case 'n':
  7399. return scan_literal("null", 4, token_type::literal_null);
  7400. // string
  7401. case '\"':
  7402. return scan_string();
  7403. // number
  7404. case '-':
  7405. case '0':
  7406. case '1':
  7407. case '2':
  7408. case '3':
  7409. case '4':
  7410. case '5':
  7411. case '6':
  7412. case '7':
  7413. case '8':
  7414. case '9':
  7415. return scan_number();
  7416. // end of input (the null byte is needed when parsing from
  7417. // string literals)
  7418. case '\0':
  7419. case std::char_traits<char>::eof():
  7420. return token_type::end_of_input;
  7421. // error
  7422. default:
  7423. error_message = "invalid literal";
  7424. return token_type::parse_error;
  7425. }
  7426. }
  7427. private:
  7428. /// input adapter
  7429. detail::input_adapter_t ia = nullptr;
  7430. /// the current character
  7431. std::char_traits<char>::int_type current = std::char_traits<char>::eof();
  7432. /// whether the next get() call should just return current
  7433. bool next_unget = false;
  7434. /// the start position of the current token
  7435. position_t position {};
  7436. /// raw input token string (for error messages)
  7437. std::vector<char> token_string {};
  7438. /// buffer for variable-length tokens (numbers, strings)
  7439. string_t token_buffer {};
  7440. /// a description of occurred lexer errors
  7441. const char* error_message = "";
  7442. // number values
  7443. number_integer_t value_integer = 0;
  7444. number_unsigned_t value_unsigned = 0;
  7445. number_float_t value_float = 0;
  7446. /// the decimal point
  7447. const char decimal_point_char = '.';
  7448. };
  7449. } // namespace detail
  7450. } // namespace nlohmann
  7451. // #include <nlohmann/detail/input/parser.hpp>
  7452. #include <cassert> // assert
  7453. #include <cmath> // isfinite
  7454. #include <cstdint> // uint8_t
  7455. #include <functional> // function
  7456. #include <string> // string
  7457. #include <utility> // move
  7458. #include <vector> // vector
  7459. // #include <nlohmann/detail/exceptions.hpp>
  7460. // #include <nlohmann/detail/input/input_adapters.hpp>
  7461. // #include <nlohmann/detail/input/json_sax.hpp>
  7462. // #include <nlohmann/detail/input/lexer.hpp>
  7463. // #include <nlohmann/detail/macro_scope.hpp>
  7464. // #include <nlohmann/detail/meta/is_sax.hpp>
  7465. // #include <nlohmann/detail/value_t.hpp>
  7466. namespace nlohmann
  7467. {
  7468. namespace detail
  7469. {
  7470. ////////////
  7471. // parser //
  7472. ////////////
  7473. /*!
  7474. @brief syntax analysis
  7475. This class implements a recursive decent parser.
  7476. */
  7477. template<typename BasicJsonType>
  7478. class parser
  7479. {
  7480. using number_integer_t = typename BasicJsonType::number_integer_t;
  7481. using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
  7482. using number_float_t = typename BasicJsonType::number_float_t;
  7483. using string_t = typename BasicJsonType::string_t;
  7484. using lexer_t = lexer<BasicJsonType>;
  7485. using token_type = typename lexer_t::token_type;
  7486. public:
  7487. enum class parse_event_t : uint8_t
  7488. {
  7489. /// the parser read `{` and started to process a JSON object
  7490. object_start,
  7491. /// the parser read `}` and finished processing a JSON object
  7492. object_end,
  7493. /// the parser read `[` and started to process a JSON array
  7494. array_start,
  7495. /// the parser read `]` and finished processing a JSON array
  7496. array_end,
  7497. /// the parser read a key of a value in an object
  7498. key,
  7499. /// the parser finished reading a JSON value
  7500. value
  7501. };
  7502. using parser_callback_t =
  7503. std::function<bool(int depth, parse_event_t event, BasicJsonType& parsed)>;
  7504. /// a parser reading from an input adapter
  7505. explicit parser(detail::input_adapter_t&& adapter,
  7506. const parser_callback_t cb = nullptr,
  7507. const bool allow_exceptions_ = true)
  7508. : callback(cb), m_lexer(std::move(adapter)), allow_exceptions(allow_exceptions_)
  7509. {
  7510. // read first token
  7511. get_token();
  7512. }
  7513. /*!
  7514. @brief public parser interface
  7515. @param[in] strict whether to expect the last token to be EOF
  7516. @param[in,out] result parsed JSON value
  7517. @throw parse_error.101 in case of an unexpected token
  7518. @throw parse_error.102 if to_unicode fails or surrogate error
  7519. @throw parse_error.103 if to_unicode fails
  7520. */
  7521. void parse(const bool strict, BasicJsonType& result)
  7522. {
  7523. if (callback)
  7524. {
  7525. json_sax_dom_callback_parser<BasicJsonType> sdp(result, callback, allow_exceptions);
  7526. sax_parse_internal(&sdp);
  7527. result.assert_invariant();
  7528. // in strict mode, input must be completely read
  7529. if (strict and (get_token() != token_type::end_of_input))
  7530. {
  7531. sdp.parse_error(m_lexer.get_position(),
  7532. m_lexer.get_token_string(),
  7533. parse_error::create(101, m_lexer.get_position(),
  7534. exception_message(token_type::end_of_input, "value")));
  7535. }
  7536. // in case of an error, return discarded value
  7537. if (sdp.is_errored())
  7538. {
  7539. result = value_t::discarded;
  7540. return;
  7541. }
  7542. // set top-level value to null if it was discarded by the callback
  7543. // function
  7544. if (result.is_discarded())
  7545. {
  7546. result = nullptr;
  7547. }
  7548. }
  7549. else
  7550. {
  7551. json_sax_dom_parser<BasicJsonType> sdp(result, allow_exceptions);
  7552. sax_parse_internal(&sdp);
  7553. result.assert_invariant();
  7554. // in strict mode, input must be completely read
  7555. if (strict and (get_token() != token_type::end_of_input))
  7556. {
  7557. sdp.parse_error(m_lexer.get_position(),
  7558. m_lexer.get_token_string(),
  7559. parse_error::create(101, m_lexer.get_position(),
  7560. exception_message(token_type::end_of_input, "value")));
  7561. }
  7562. // in case of an error, return discarded value
  7563. if (sdp.is_errored())
  7564. {
  7565. result = value_t::discarded;
  7566. return;
  7567. }
  7568. }
  7569. }
  7570. /*!
  7571. @brief public accept interface
  7572. @param[in] strict whether to expect the last token to be EOF
  7573. @return whether the input is a proper JSON text
  7574. */
  7575. bool accept(const bool strict = true)
  7576. {
  7577. json_sax_acceptor<BasicJsonType> sax_acceptor;
  7578. return sax_parse(&sax_acceptor, strict);
  7579. }
  7580. template <typename SAX>
  7581. JSON_HEDLEY_NON_NULL(2)
  7582. bool sax_parse(SAX* sax, const bool strict = true)
  7583. {
  7584. (void)detail::is_sax_static_asserts<SAX, BasicJsonType> {};
  7585. const bool result = sax_parse_internal(sax);
  7586. // strict mode: next byte must be EOF
  7587. if (result and strict and (get_token() != token_type::end_of_input))
  7588. {
  7589. return sax->parse_error(m_lexer.get_position(),
  7590. m_lexer.get_token_string(),
  7591. parse_error::create(101, m_lexer.get_position(),
  7592. exception_message(token_type::end_of_input, "value")));
  7593. }
  7594. return result;
  7595. }
  7596. private:
  7597. template <typename SAX>
  7598. JSON_HEDLEY_NON_NULL(2)
  7599. bool sax_parse_internal(SAX* sax)
  7600. {
  7601. // stack to remember the hierarchy of structured values we are parsing
  7602. // true = array; false = object
  7603. std::vector<bool> states;
  7604. // value to avoid a goto (see comment where set to true)
  7605. bool skip_to_state_evaluation = false;
  7606. while (true)
  7607. {
  7608. if (not skip_to_state_evaluation)
  7609. {
  7610. // invariant: get_token() was called before each iteration
  7611. switch (last_token)
  7612. {
  7613. case token_type::begin_object:
  7614. {
  7615. if (JSON_HEDLEY_UNLIKELY(not sax->start_object(std::size_t(-1))))
  7616. {
  7617. return false;
  7618. }
  7619. // closing } -> we are done
  7620. if (get_token() == token_type::end_object)
  7621. {
  7622. if (JSON_HEDLEY_UNLIKELY(not sax->end_object()))
  7623. {
  7624. return false;
  7625. }
  7626. break;
  7627. }
  7628. // parse key
  7629. if (JSON_HEDLEY_UNLIKELY(last_token != token_type::value_string))
  7630. {
  7631. return sax->parse_error(m_lexer.get_position(),
  7632. m_lexer.get_token_string(),
  7633. parse_error::create(101, m_lexer.get_position(),
  7634. exception_message(token_type::value_string, "object key")));
  7635. }
  7636. if (JSON_HEDLEY_UNLIKELY(not sax->key(m_lexer.get_string())))
  7637. {
  7638. return false;
  7639. }
  7640. // parse separator (:)
  7641. if (JSON_HEDLEY_UNLIKELY(get_token() != token_type::name_separator))
  7642. {
  7643. return sax->parse_error(m_lexer.get_position(),
  7644. m_lexer.get_token_string(),
  7645. parse_error::create(101, m_lexer.get_position(),
  7646. exception_message(token_type::name_separator, "object separator")));
  7647. }
  7648. // remember we are now inside an object
  7649. states.push_back(false);
  7650. // parse values
  7651. get_token();
  7652. continue;
  7653. }
  7654. case token_type::begin_array:
  7655. {
  7656. if (JSON_HEDLEY_UNLIKELY(not sax->start_array(std::size_t(-1))))
  7657. {
  7658. return false;
  7659. }
  7660. // closing ] -> we are done
  7661. if (get_token() == token_type::end_array)
  7662. {
  7663. if (JSON_HEDLEY_UNLIKELY(not sax->end_array()))
  7664. {
  7665. return false;
  7666. }
  7667. break;
  7668. }
  7669. // remember we are now inside an array
  7670. states.push_back(true);
  7671. // parse values (no need to call get_token)
  7672. continue;
  7673. }
  7674. case token_type::value_float:
  7675. {
  7676. const auto res = m_lexer.get_number_float();
  7677. if (JSON_HEDLEY_UNLIKELY(not std::isfinite(res)))
  7678. {
  7679. return sax->parse_error(m_lexer.get_position(),
  7680. m_lexer.get_token_string(),
  7681. out_of_range::create(406, "number overflow parsing '" + m_lexer.get_token_string() + "'"));
  7682. }
  7683. if (JSON_HEDLEY_UNLIKELY(not sax->number_float(res, m_lexer.get_string())))
  7684. {
  7685. return false;
  7686. }
  7687. break;
  7688. }
  7689. case token_type::literal_false:
  7690. {
  7691. if (JSON_HEDLEY_UNLIKELY(not sax->boolean(false)))
  7692. {
  7693. return false;
  7694. }
  7695. break;
  7696. }
  7697. case token_type::literal_null:
  7698. {
  7699. if (JSON_HEDLEY_UNLIKELY(not sax->null()))
  7700. {
  7701. return false;
  7702. }
  7703. break;
  7704. }
  7705. case token_type::literal_true:
  7706. {
  7707. if (JSON_HEDLEY_UNLIKELY(not sax->boolean(true)))
  7708. {
  7709. return false;
  7710. }
  7711. break;
  7712. }
  7713. case token_type::value_integer:
  7714. {
  7715. if (JSON_HEDLEY_UNLIKELY(not sax->number_integer(m_lexer.get_number_integer())))
  7716. {
  7717. return false;
  7718. }
  7719. break;
  7720. }
  7721. case token_type::value_string:
  7722. {
  7723. if (JSON_HEDLEY_UNLIKELY(not sax->string(m_lexer.get_string())))
  7724. {
  7725. return false;
  7726. }
  7727. break;
  7728. }
  7729. case token_type::value_unsigned:
  7730. {
  7731. if (JSON_HEDLEY_UNLIKELY(not sax->number_unsigned(m_lexer.get_number_unsigned())))
  7732. {
  7733. return false;
  7734. }
  7735. break;
  7736. }
  7737. case token_type::parse_error:
  7738. {
  7739. // using "uninitialized" to avoid "expected" message
  7740. return sax->parse_error(m_lexer.get_position(),
  7741. m_lexer.get_token_string(),
  7742. parse_error::create(101, m_lexer.get_position(),
  7743. exception_message(token_type::uninitialized, "value")));
  7744. }
  7745. default: // the last token was unexpected
  7746. {
  7747. return sax->parse_error(m_lexer.get_position(),
  7748. m_lexer.get_token_string(),
  7749. parse_error::create(101, m_lexer.get_position(),
  7750. exception_message(token_type::literal_or_value, "value")));
  7751. }
  7752. }
  7753. }
  7754. else
  7755. {
  7756. skip_to_state_evaluation = false;
  7757. }
  7758. // we reached this line after we successfully parsed a value
  7759. if (states.empty())
  7760. {
  7761. // empty stack: we reached the end of the hierarchy: done
  7762. return true;
  7763. }
  7764. if (states.back()) // array
  7765. {
  7766. // comma -> next value
  7767. if (get_token() == token_type::value_separator)
  7768. {
  7769. // parse a new value
  7770. get_token();
  7771. continue;
  7772. }
  7773. // closing ]
  7774. if (JSON_HEDLEY_LIKELY(last_token == token_type::end_array))
  7775. {
  7776. if (JSON_HEDLEY_UNLIKELY(not sax->end_array()))
  7777. {
  7778. return false;
  7779. }
  7780. // We are done with this array. Before we can parse a
  7781. // new value, we need to evaluate the new state first.
  7782. // By setting skip_to_state_evaluation to false, we
  7783. // are effectively jumping to the beginning of this if.
  7784. assert(not states.empty());
  7785. states.pop_back();
  7786. skip_to_state_evaluation = true;
  7787. continue;
  7788. }
  7789. return sax->parse_error(m_lexer.get_position(),
  7790. m_lexer.get_token_string(),
  7791. parse_error::create(101, m_lexer.get_position(),
  7792. exception_message(token_type::end_array, "array")));
  7793. }
  7794. else // object
  7795. {
  7796. // comma -> next value
  7797. if (get_token() == token_type::value_separator)
  7798. {
  7799. // parse key
  7800. if (JSON_HEDLEY_UNLIKELY(get_token() != token_type::value_string))
  7801. {
  7802. return sax->parse_error(m_lexer.get_position(),
  7803. m_lexer.get_token_string(),
  7804. parse_error::create(101, m_lexer.get_position(),
  7805. exception_message(token_type::value_string, "object key")));
  7806. }
  7807. if (JSON_HEDLEY_UNLIKELY(not sax->key(m_lexer.get_string())))
  7808. {
  7809. return false;
  7810. }
  7811. // parse separator (:)
  7812. if (JSON_HEDLEY_UNLIKELY(get_token() != token_type::name_separator))
  7813. {
  7814. return sax->parse_error(m_lexer.get_position(),
  7815. m_lexer.get_token_string(),
  7816. parse_error::create(101, m_lexer.get_position(),
  7817. exception_message(token_type::name_separator, "object separator")));
  7818. }
  7819. // parse values
  7820. get_token();
  7821. continue;
  7822. }
  7823. // closing }
  7824. if (JSON_HEDLEY_LIKELY(last_token == token_type::end_object))
  7825. {
  7826. if (JSON_HEDLEY_UNLIKELY(not sax->end_object()))
  7827. {
  7828. return false;
  7829. }
  7830. // We are done with this object. Before we can parse a
  7831. // new value, we need to evaluate the new state first.
  7832. // By setting skip_to_state_evaluation to false, we
  7833. // are effectively jumping to the beginning of this if.
  7834. assert(not states.empty());
  7835. states.pop_back();
  7836. skip_to_state_evaluation = true;
  7837. continue;
  7838. }
  7839. return sax->parse_error(m_lexer.get_position(),
  7840. m_lexer.get_token_string(),
  7841. parse_error::create(101, m_lexer.get_position(),
  7842. exception_message(token_type::end_object, "object")));
  7843. }
  7844. }
  7845. }
  7846. /// get next token from lexer
  7847. token_type get_token()
  7848. {
  7849. return last_token = m_lexer.scan();
  7850. }
  7851. std::string exception_message(const token_type expected, const std::string& context)
  7852. {
  7853. std::string error_msg = "syntax error ";
  7854. if (not context.empty())
  7855. {
  7856. error_msg += "while parsing " + context + " ";
  7857. }
  7858. error_msg += "- ";
  7859. if (last_token == token_type::parse_error)
  7860. {
  7861. error_msg += std::string(m_lexer.get_error_message()) + "; last read: '" +
  7862. m_lexer.get_token_string() + "'";
  7863. }
  7864. else
  7865. {
  7866. error_msg += "unexpected " + std::string(lexer_t::token_type_name(last_token));
  7867. }
  7868. if (expected != token_type::uninitialized)
  7869. {
  7870. error_msg += "; expected " + std::string(lexer_t::token_type_name(expected));
  7871. }
  7872. return error_msg;
  7873. }
  7874. private:
  7875. /// callback function
  7876. const parser_callback_t callback = nullptr;
  7877. /// the type of the last read token
  7878. token_type last_token = token_type::uninitialized;
  7879. /// the lexer
  7880. lexer_t m_lexer;
  7881. /// whether to throw exceptions in case of errors
  7882. const bool allow_exceptions = true;
  7883. };
  7884. } // namespace detail
  7885. } // namespace nlohmann
  7886. // #include <nlohmann/detail/iterators/internal_iterator.hpp>
  7887. // #include <nlohmann/detail/iterators/primitive_iterator.hpp>
  7888. #include <cstddef> // ptrdiff_t
  7889. #include <limits> // numeric_limits
  7890. namespace nlohmann
  7891. {
  7892. namespace detail
  7893. {
  7894. /*
  7895. @brief an iterator for primitive JSON types
  7896. This class models an iterator for primitive JSON types (boolean, number,
  7897. string). It's only purpose is to allow the iterator/const_iterator classes
  7898. to "iterate" over primitive values. Internally, the iterator is modeled by
  7899. a `difference_type` variable. Value begin_value (`0`) models the begin,
  7900. end_value (`1`) models past the end.
  7901. */
  7902. class primitive_iterator_t
  7903. {
  7904. private:
  7905. using difference_type = std::ptrdiff_t;
  7906. static constexpr difference_type begin_value = 0;
  7907. static constexpr difference_type end_value = begin_value + 1;
  7908. /// iterator as signed integer type
  7909. difference_type m_it = (std::numeric_limits<std::ptrdiff_t>::min)();
  7910. public:
  7911. constexpr difference_type get_value() const noexcept
  7912. {
  7913. return m_it;
  7914. }
  7915. /// set iterator to a defined beginning
  7916. void set_begin() noexcept
  7917. {
  7918. m_it = begin_value;
  7919. }
  7920. /// set iterator to a defined past the end
  7921. void set_end() noexcept
  7922. {
  7923. m_it = end_value;
  7924. }
  7925. /// return whether the iterator can be dereferenced
  7926. constexpr bool is_begin() const noexcept
  7927. {
  7928. return m_it == begin_value;
  7929. }
  7930. /// return whether the iterator is at end
  7931. constexpr bool is_end() const noexcept
  7932. {
  7933. return m_it == end_value;
  7934. }
  7935. friend constexpr bool operator==(primitive_iterator_t lhs, primitive_iterator_t rhs) noexcept
  7936. {
  7937. return lhs.m_it == rhs.m_it;
  7938. }
  7939. friend constexpr bool operator<(primitive_iterator_t lhs, primitive_iterator_t rhs) noexcept
  7940. {
  7941. return lhs.m_it < rhs.m_it;
  7942. }
  7943. primitive_iterator_t operator+(difference_type n) noexcept
  7944. {
  7945. auto result = *this;
  7946. result += n;
  7947. return result;
  7948. }
  7949. friend constexpr difference_type operator-(primitive_iterator_t lhs, primitive_iterator_t rhs) noexcept
  7950. {
  7951. return lhs.m_it - rhs.m_it;
  7952. }
  7953. primitive_iterator_t& operator++() noexcept
  7954. {
  7955. ++m_it;
  7956. return *this;
  7957. }
  7958. primitive_iterator_t const operator++(int) noexcept
  7959. {
  7960. auto result = *this;
  7961. ++m_it;
  7962. return result;
  7963. }
  7964. primitive_iterator_t& operator--() noexcept
  7965. {
  7966. --m_it;
  7967. return *this;
  7968. }
  7969. primitive_iterator_t const operator--(int) noexcept
  7970. {
  7971. auto result = *this;
  7972. --m_it;
  7973. return result;
  7974. }
  7975. primitive_iterator_t& operator+=(difference_type n) noexcept
  7976. {
  7977. m_it += n;
  7978. return *this;
  7979. }
  7980. primitive_iterator_t& operator-=(difference_type n) noexcept
  7981. {
  7982. m_it -= n;
  7983. return *this;
  7984. }
  7985. };
  7986. } // namespace detail
  7987. } // namespace nlohmann
  7988. namespace nlohmann
  7989. {
  7990. namespace detail
  7991. {
  7992. /*!
  7993. @brief an iterator value
  7994. @note This structure could easily be a union, but MSVC currently does not allow
  7995. unions members with complex constructors, see https://github.com/nlohmann/json/pull/105.
  7996. */
  7997. template<typename BasicJsonType> struct internal_iterator
  7998. {
  7999. /// iterator for JSON objects
  8000. typename BasicJsonType::object_t::iterator object_iterator {};
  8001. /// iterator for JSON arrays
  8002. typename BasicJsonType::array_t::iterator array_iterator {};
  8003. /// generic iterator for all other types
  8004. primitive_iterator_t primitive_iterator {};
  8005. };
  8006. } // namespace detail
  8007. } // namespace nlohmann
  8008. // #include <nlohmann/detail/iterators/iter_impl.hpp>
  8009. #include <ciso646> // not
  8010. #include <iterator> // iterator, random_access_iterator_tag, bidirectional_iterator_tag, advance, next
  8011. #include <type_traits> // conditional, is_const, remove_const
  8012. // #include <nlohmann/detail/exceptions.hpp>
  8013. // #include <nlohmann/detail/iterators/internal_iterator.hpp>
  8014. // #include <nlohmann/detail/iterators/primitive_iterator.hpp>
  8015. // #include <nlohmann/detail/macro_scope.hpp>
  8016. // #include <nlohmann/detail/meta/cpp_future.hpp>
  8017. // #include <nlohmann/detail/meta/type_traits.hpp>
  8018. // #include <nlohmann/detail/value_t.hpp>
  8019. namespace nlohmann
  8020. {
  8021. namespace detail
  8022. {
  8023. // forward declare, to be able to friend it later on
  8024. template<typename IteratorType> class iteration_proxy;
  8025. template<typename IteratorType> class iteration_proxy_value;
  8026. /*!
  8027. @brief a template for a bidirectional iterator for the @ref basic_json class
  8028. This class implements a both iterators (iterator and const_iterator) for the
  8029. @ref basic_json class.
  8030. @note An iterator is called *initialized* when a pointer to a JSON value has
  8031. been set (e.g., by a constructor or a copy assignment). If the iterator is
  8032. default-constructed, it is *uninitialized* and most methods are undefined.
  8033. **The library uses assertions to detect calls on uninitialized iterators.**
  8034. @requirement The class satisfies the following concept requirements:
  8035. -
  8036. [BidirectionalIterator](https://en.cppreference.com/w/cpp/named_req/BidirectionalIterator):
  8037. The iterator that can be moved can be moved in both directions (i.e.
  8038. incremented and decremented).
  8039. @since version 1.0.0, simplified in version 2.0.9, change to bidirectional
  8040. iterators in version 3.0.0 (see https://github.com/nlohmann/json/issues/593)
  8041. */
  8042. template<typename BasicJsonType>
  8043. class iter_impl
  8044. {
  8045. /// allow basic_json to access private members
  8046. friend iter_impl<typename std::conditional<std::is_const<BasicJsonType>::value, typename std::remove_const<BasicJsonType>::type, const BasicJsonType>::type>;
  8047. friend BasicJsonType;
  8048. friend iteration_proxy<iter_impl>;
  8049. friend iteration_proxy_value<iter_impl>;
  8050. using object_t = typename BasicJsonType::object_t;
  8051. using array_t = typename BasicJsonType::array_t;
  8052. // make sure BasicJsonType is basic_json or const basic_json
  8053. static_assert(is_basic_json<typename std::remove_const<BasicJsonType>::type>::value,
  8054. "iter_impl only accepts (const) basic_json");
  8055. public:
  8056. /// The std::iterator class template (used as a base class to provide typedefs) is deprecated in C++17.
  8057. /// The C++ Standard has never required user-defined iterators to derive from std::iterator.
  8058. /// A user-defined iterator should provide publicly accessible typedefs named
  8059. /// iterator_category, value_type, difference_type, pointer, and reference.
  8060. /// Note that value_type is required to be non-const, even for constant iterators.
  8061. using iterator_category = std::bidirectional_iterator_tag;
  8062. /// the type of the values when the iterator is dereferenced
  8063. using value_type = typename BasicJsonType::value_type;
  8064. /// a type to represent differences between iterators
  8065. using difference_type = typename BasicJsonType::difference_type;
  8066. /// defines a pointer to the type iterated over (value_type)
  8067. using pointer = typename std::conditional<std::is_const<BasicJsonType>::value,
  8068. typename BasicJsonType::const_pointer,
  8069. typename BasicJsonType::pointer>::type;
  8070. /// defines a reference to the type iterated over (value_type)
  8071. using reference =
  8072. typename std::conditional<std::is_const<BasicJsonType>::value,
  8073. typename BasicJsonType::const_reference,
  8074. typename BasicJsonType::reference>::type;
  8075. /// default constructor
  8076. iter_impl() = default;
  8077. /*!
  8078. @brief constructor for a given JSON instance
  8079. @param[in] object pointer to a JSON object for this iterator
  8080. @pre object != nullptr
  8081. @post The iterator is initialized; i.e. `m_object != nullptr`.
  8082. */
  8083. explicit iter_impl(pointer object) noexcept : m_object(object)
  8084. {
  8085. assert(m_object != nullptr);
  8086. switch (m_object->m_type)
  8087. {
  8088. case value_t::object:
  8089. {
  8090. m_it.object_iterator = typename object_t::iterator();
  8091. break;
  8092. }
  8093. case value_t::array:
  8094. {
  8095. m_it.array_iterator = typename array_t::iterator();
  8096. break;
  8097. }
  8098. default:
  8099. {
  8100. m_it.primitive_iterator = primitive_iterator_t();
  8101. break;
  8102. }
  8103. }
  8104. }
  8105. /*!
  8106. @note The conventional copy constructor and copy assignment are implicitly
  8107. defined. Combined with the following converting constructor and
  8108. assignment, they support: (1) copy from iterator to iterator, (2)
  8109. copy from const iterator to const iterator, and (3) conversion from
  8110. iterator to const iterator. However conversion from const iterator
  8111. to iterator is not defined.
  8112. */
  8113. /*!
  8114. @brief const copy constructor
  8115. @param[in] other const iterator to copy from
  8116. @note This copy constuctor had to be defined explicitely to circumvent a bug
  8117. occuring on msvc v19.0 compiler (VS 2015) debug build. For more
  8118. information refer to: https://github.com/nlohmann/json/issues/1608
  8119. */
  8120. iter_impl(const iter_impl<const BasicJsonType>& other) noexcept
  8121. : m_object(other.m_object), m_it(other.m_it)
  8122. {}
  8123. /*!
  8124. @brief converting assignment
  8125. @param[in] other const iterator to copy from
  8126. @return const/non-const iterator
  8127. @note It is not checked whether @a other is initialized.
  8128. */
  8129. iter_impl& operator=(const iter_impl<const BasicJsonType>& other) noexcept
  8130. {
  8131. m_object = other.m_object;
  8132. m_it = other.m_it;
  8133. return *this;
  8134. }
  8135. /*!
  8136. @brief converting constructor
  8137. @param[in] other non-const iterator to copy from
  8138. @note It is not checked whether @a other is initialized.
  8139. */
  8140. iter_impl(const iter_impl<typename std::remove_const<BasicJsonType>::type>& other) noexcept
  8141. : m_object(other.m_object), m_it(other.m_it)
  8142. {}
  8143. /*!
  8144. @brief converting assignment
  8145. @param[in] other non-const iterator to copy from
  8146. @return const/non-const iterator
  8147. @note It is not checked whether @a other is initialized.
  8148. */
  8149. iter_impl& operator=(const iter_impl<typename std::remove_const<BasicJsonType>::type>& other) noexcept
  8150. {
  8151. m_object = other.m_object;
  8152. m_it = other.m_it;
  8153. return *this;
  8154. }
  8155. private:
  8156. /*!
  8157. @brief set the iterator to the first value
  8158. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  8159. */
  8160. void set_begin() noexcept
  8161. {
  8162. assert(m_object != nullptr);
  8163. switch (m_object->m_type)
  8164. {
  8165. case value_t::object:
  8166. {
  8167. m_it.object_iterator = m_object->m_value.object->begin();
  8168. break;
  8169. }
  8170. case value_t::array:
  8171. {
  8172. m_it.array_iterator = m_object->m_value.array->begin();
  8173. break;
  8174. }
  8175. case value_t::null:
  8176. {
  8177. // set to end so begin()==end() is true: null is empty
  8178. m_it.primitive_iterator.set_end();
  8179. break;
  8180. }
  8181. default:
  8182. {
  8183. m_it.primitive_iterator.set_begin();
  8184. break;
  8185. }
  8186. }
  8187. }
  8188. /*!
  8189. @brief set the iterator past the last value
  8190. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  8191. */
  8192. void set_end() noexcept
  8193. {
  8194. assert(m_object != nullptr);
  8195. switch (m_object->m_type)
  8196. {
  8197. case value_t::object:
  8198. {
  8199. m_it.object_iterator = m_object->m_value.object->end();
  8200. break;
  8201. }
  8202. case value_t::array:
  8203. {
  8204. m_it.array_iterator = m_object->m_value.array->end();
  8205. break;
  8206. }
  8207. default:
  8208. {
  8209. m_it.primitive_iterator.set_end();
  8210. break;
  8211. }
  8212. }
  8213. }
  8214. public:
  8215. /*!
  8216. @brief return a reference to the value pointed to by the iterator
  8217. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  8218. */
  8219. reference operator*() const
  8220. {
  8221. assert(m_object != nullptr);
  8222. switch (m_object->m_type)
  8223. {
  8224. case value_t::object:
  8225. {
  8226. assert(m_it.object_iterator != m_object->m_value.object->end());
  8227. return m_it.object_iterator->second;
  8228. }
  8229. case value_t::array:
  8230. {
  8231. assert(m_it.array_iterator != m_object->m_value.array->end());
  8232. return *m_it.array_iterator;
  8233. }
  8234. case value_t::null:
  8235. JSON_THROW(invalid_iterator::create(214, "cannot get value"));
  8236. default:
  8237. {
  8238. if (JSON_HEDLEY_LIKELY(m_it.primitive_iterator.is_begin()))
  8239. {
  8240. return *m_object;
  8241. }
  8242. JSON_THROW(invalid_iterator::create(214, "cannot get value"));
  8243. }
  8244. }
  8245. }
  8246. /*!
  8247. @brief dereference the iterator
  8248. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  8249. */
  8250. pointer operator->() const
  8251. {
  8252. assert(m_object != nullptr);
  8253. switch (m_object->m_type)
  8254. {
  8255. case value_t::object:
  8256. {
  8257. assert(m_it.object_iterator != m_object->m_value.object->end());
  8258. return &(m_it.object_iterator->second);
  8259. }
  8260. case value_t::array:
  8261. {
  8262. assert(m_it.array_iterator != m_object->m_value.array->end());
  8263. return &*m_it.array_iterator;
  8264. }
  8265. default:
  8266. {
  8267. if (JSON_HEDLEY_LIKELY(m_it.primitive_iterator.is_begin()))
  8268. {
  8269. return m_object;
  8270. }
  8271. JSON_THROW(invalid_iterator::create(214, "cannot get value"));
  8272. }
  8273. }
  8274. }
  8275. /*!
  8276. @brief post-increment (it++)
  8277. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  8278. */
  8279. iter_impl const operator++(int)
  8280. {
  8281. auto result = *this;
  8282. ++(*this);
  8283. return result;
  8284. }
  8285. /*!
  8286. @brief pre-increment (++it)
  8287. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  8288. */
  8289. iter_impl& operator++()
  8290. {
  8291. assert(m_object != nullptr);
  8292. switch (m_object->m_type)
  8293. {
  8294. case value_t::object:
  8295. {
  8296. std::advance(m_it.object_iterator, 1);
  8297. break;
  8298. }
  8299. case value_t::array:
  8300. {
  8301. std::advance(m_it.array_iterator, 1);
  8302. break;
  8303. }
  8304. default:
  8305. {
  8306. ++m_it.primitive_iterator;
  8307. break;
  8308. }
  8309. }
  8310. return *this;
  8311. }
  8312. /*!
  8313. @brief post-decrement (it--)
  8314. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  8315. */
  8316. iter_impl const operator--(int)
  8317. {
  8318. auto result = *this;
  8319. --(*this);
  8320. return result;
  8321. }
  8322. /*!
  8323. @brief pre-decrement (--it)
  8324. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  8325. */
  8326. iter_impl& operator--()
  8327. {
  8328. assert(m_object != nullptr);
  8329. switch (m_object->m_type)
  8330. {
  8331. case value_t::object:
  8332. {
  8333. std::advance(m_it.object_iterator, -1);
  8334. break;
  8335. }
  8336. case value_t::array:
  8337. {
  8338. std::advance(m_it.array_iterator, -1);
  8339. break;
  8340. }
  8341. default:
  8342. {
  8343. --m_it.primitive_iterator;
  8344. break;
  8345. }
  8346. }
  8347. return *this;
  8348. }
  8349. /*!
  8350. @brief comparison: equal
  8351. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  8352. */
  8353. bool operator==(const iter_impl& other) const
  8354. {
  8355. // if objects are not the same, the comparison is undefined
  8356. if (JSON_HEDLEY_UNLIKELY(m_object != other.m_object))
  8357. {
  8358. JSON_THROW(invalid_iterator::create(212, "cannot compare iterators of different containers"));
  8359. }
  8360. assert(m_object != nullptr);
  8361. switch (m_object->m_type)
  8362. {
  8363. case value_t::object:
  8364. return (m_it.object_iterator == other.m_it.object_iterator);
  8365. case value_t::array:
  8366. return (m_it.array_iterator == other.m_it.array_iterator);
  8367. default:
  8368. return (m_it.primitive_iterator == other.m_it.primitive_iterator);
  8369. }
  8370. }
  8371. /*!
  8372. @brief comparison: not equal
  8373. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  8374. */
  8375. bool operator!=(const iter_impl& other) const
  8376. {
  8377. return not operator==(other);
  8378. }
  8379. /*!
  8380. @brief comparison: smaller
  8381. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  8382. */
  8383. bool operator<(const iter_impl& other) const
  8384. {
  8385. // if objects are not the same, the comparison is undefined
  8386. if (JSON_HEDLEY_UNLIKELY(m_object != other.m_object))
  8387. {
  8388. JSON_THROW(invalid_iterator::create(212, "cannot compare iterators of different containers"));
  8389. }
  8390. assert(m_object != nullptr);
  8391. switch (m_object->m_type)
  8392. {
  8393. case value_t::object:
  8394. JSON_THROW(invalid_iterator::create(213, "cannot compare order of object iterators"));
  8395. case value_t::array:
  8396. return (m_it.array_iterator < other.m_it.array_iterator);
  8397. default:
  8398. return (m_it.primitive_iterator < other.m_it.primitive_iterator);
  8399. }
  8400. }
  8401. /*!
  8402. @brief comparison: less than or equal
  8403. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  8404. */
  8405. bool operator<=(const iter_impl& other) const
  8406. {
  8407. return not other.operator < (*this);
  8408. }
  8409. /*!
  8410. @brief comparison: greater than
  8411. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  8412. */
  8413. bool operator>(const iter_impl& other) const
  8414. {
  8415. return not operator<=(other);
  8416. }
  8417. /*!
  8418. @brief comparison: greater than or equal
  8419. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  8420. */
  8421. bool operator>=(const iter_impl& other) const
  8422. {
  8423. return not operator<(other);
  8424. }
  8425. /*!
  8426. @brief add to iterator
  8427. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  8428. */
  8429. iter_impl& operator+=(difference_type i)
  8430. {
  8431. assert(m_object != nullptr);
  8432. switch (m_object->m_type)
  8433. {
  8434. case value_t::object:
  8435. JSON_THROW(invalid_iterator::create(209, "cannot use offsets with object iterators"));
  8436. case value_t::array:
  8437. {
  8438. std::advance(m_it.array_iterator, i);
  8439. break;
  8440. }
  8441. default:
  8442. {
  8443. m_it.primitive_iterator += i;
  8444. break;
  8445. }
  8446. }
  8447. return *this;
  8448. }
  8449. /*!
  8450. @brief subtract from iterator
  8451. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  8452. */
  8453. iter_impl& operator-=(difference_type i)
  8454. {
  8455. return operator+=(-i);
  8456. }
  8457. /*!
  8458. @brief add to iterator
  8459. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  8460. */
  8461. iter_impl operator+(difference_type i) const
  8462. {
  8463. auto result = *this;
  8464. result += i;
  8465. return result;
  8466. }
  8467. /*!
  8468. @brief addition of distance and iterator
  8469. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  8470. */
  8471. friend iter_impl operator+(difference_type i, const iter_impl& it)
  8472. {
  8473. auto result = it;
  8474. result += i;
  8475. return result;
  8476. }
  8477. /*!
  8478. @brief subtract from iterator
  8479. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  8480. */
  8481. iter_impl operator-(difference_type i) const
  8482. {
  8483. auto result = *this;
  8484. result -= i;
  8485. return result;
  8486. }
  8487. /*!
  8488. @brief return difference
  8489. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  8490. */
  8491. difference_type operator-(const iter_impl& other) const
  8492. {
  8493. assert(m_object != nullptr);
  8494. switch (m_object->m_type)
  8495. {
  8496. case value_t::object:
  8497. JSON_THROW(invalid_iterator::create(209, "cannot use offsets with object iterators"));
  8498. case value_t::array:
  8499. return m_it.array_iterator - other.m_it.array_iterator;
  8500. default:
  8501. return m_it.primitive_iterator - other.m_it.primitive_iterator;
  8502. }
  8503. }
  8504. /*!
  8505. @brief access to successor
  8506. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  8507. */
  8508. reference operator[](difference_type n) const
  8509. {
  8510. assert(m_object != nullptr);
  8511. switch (m_object->m_type)
  8512. {
  8513. case value_t::object:
  8514. JSON_THROW(invalid_iterator::create(208, "cannot use operator[] for object iterators"));
  8515. case value_t::array:
  8516. return *std::next(m_it.array_iterator, n);
  8517. case value_t::null:
  8518. JSON_THROW(invalid_iterator::create(214, "cannot get value"));
  8519. default:
  8520. {
  8521. if (JSON_HEDLEY_LIKELY(m_it.primitive_iterator.get_value() == -n))
  8522. {
  8523. return *m_object;
  8524. }
  8525. JSON_THROW(invalid_iterator::create(214, "cannot get value"));
  8526. }
  8527. }
  8528. }
  8529. /*!
  8530. @brief return the key of an object iterator
  8531. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  8532. */
  8533. const typename object_t::key_type& key() const
  8534. {
  8535. assert(m_object != nullptr);
  8536. if (JSON_HEDLEY_LIKELY(m_object->is_object()))
  8537. {
  8538. return m_it.object_iterator->first;
  8539. }
  8540. JSON_THROW(invalid_iterator::create(207, "cannot use key() for non-object iterators"));
  8541. }
  8542. /*!
  8543. @brief return the value of an iterator
  8544. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  8545. */
  8546. reference value() const
  8547. {
  8548. return operator*();
  8549. }
  8550. private:
  8551. /// associated JSON instance
  8552. pointer m_object = nullptr;
  8553. /// the actual iterator of the associated instance
  8554. internal_iterator<typename std::remove_const<BasicJsonType>::type> m_it {};
  8555. };
  8556. } // namespace detail
  8557. } // namespace nlohmann
  8558. // #include <nlohmann/detail/iterators/iteration_proxy.hpp>
  8559. // #include <nlohmann/detail/iterators/json_reverse_iterator.hpp>
  8560. #include <cstddef> // ptrdiff_t
  8561. #include <iterator> // reverse_iterator
  8562. #include <utility> // declval
  8563. namespace nlohmann
  8564. {
  8565. namespace detail
  8566. {
  8567. //////////////////////
  8568. // reverse_iterator //
  8569. //////////////////////
  8570. /*!
  8571. @brief a template for a reverse iterator class
  8572. @tparam Base the base iterator type to reverse. Valid types are @ref
  8573. iterator (to create @ref reverse_iterator) and @ref const_iterator (to
  8574. create @ref const_reverse_iterator).
  8575. @requirement The class satisfies the following concept requirements:
  8576. -
  8577. [BidirectionalIterator](https://en.cppreference.com/w/cpp/named_req/BidirectionalIterator):
  8578. The iterator that can be moved can be moved in both directions (i.e.
  8579. incremented and decremented).
  8580. - [OutputIterator](https://en.cppreference.com/w/cpp/named_req/OutputIterator):
  8581. It is possible to write to the pointed-to element (only if @a Base is
  8582. @ref iterator).
  8583. @since version 1.0.0
  8584. */
  8585. template<typename Base>
  8586. class json_reverse_iterator : public std::reverse_iterator<Base>
  8587. {
  8588. public:
  8589. using difference_type = std::ptrdiff_t;
  8590. /// shortcut to the reverse iterator adapter
  8591. using base_iterator = std::reverse_iterator<Base>;
  8592. /// the reference type for the pointed-to element
  8593. using reference = typename Base::reference;
  8594. /// create reverse iterator from iterator
  8595. explicit json_reverse_iterator(const typename base_iterator::iterator_type& it) noexcept
  8596. : base_iterator(it) {}
  8597. /// create reverse iterator from base class
  8598. explicit json_reverse_iterator(const base_iterator& it) noexcept : base_iterator(it) {}
  8599. /// post-increment (it++)
  8600. json_reverse_iterator const operator++(int)
  8601. {
  8602. return static_cast<json_reverse_iterator>(base_iterator::operator++(1));
  8603. }
  8604. /// pre-increment (++it)
  8605. json_reverse_iterator& operator++()
  8606. {
  8607. return static_cast<json_reverse_iterator&>(base_iterator::operator++());
  8608. }
  8609. /// post-decrement (it--)
  8610. json_reverse_iterator const operator--(int)
  8611. {
  8612. return static_cast<json_reverse_iterator>(base_iterator::operator--(1));
  8613. }
  8614. /// pre-decrement (--it)
  8615. json_reverse_iterator& operator--()
  8616. {
  8617. return static_cast<json_reverse_iterator&>(base_iterator::operator--());
  8618. }
  8619. /// add to iterator
  8620. json_reverse_iterator& operator+=(difference_type i)
  8621. {
  8622. return static_cast<json_reverse_iterator&>(base_iterator::operator+=(i));
  8623. }
  8624. /// add to iterator
  8625. json_reverse_iterator operator+(difference_type i) const
  8626. {
  8627. return static_cast<json_reverse_iterator>(base_iterator::operator+(i));
  8628. }
  8629. /// subtract from iterator
  8630. json_reverse_iterator operator-(difference_type i) const
  8631. {
  8632. return static_cast<json_reverse_iterator>(base_iterator::operator-(i));
  8633. }
  8634. /// return difference
  8635. difference_type operator-(const json_reverse_iterator& other) const
  8636. {
  8637. return base_iterator(*this) - base_iterator(other);
  8638. }
  8639. /// access to successor
  8640. reference operator[](difference_type n) const
  8641. {
  8642. return *(this->operator+(n));
  8643. }
  8644. /// return the key of an object iterator
  8645. auto key() const -> decltype(std::declval<Base>().key())
  8646. {
  8647. auto it = --this->base();
  8648. return it.key();
  8649. }
  8650. /// return the value of an iterator
  8651. reference value() const
  8652. {
  8653. auto it = --this->base();
  8654. return it.operator * ();
  8655. }
  8656. };
  8657. } // namespace detail
  8658. } // namespace nlohmann
  8659. // #include <nlohmann/detail/iterators/primitive_iterator.hpp>
  8660. // #include <nlohmann/detail/json_pointer.hpp>
  8661. #include <algorithm> // all_of
  8662. #include <cassert> // assert
  8663. #include <cctype> // isdigit
  8664. #include <numeric> // accumulate
  8665. #include <string> // string
  8666. #include <utility> // move
  8667. #include <vector> // vector
  8668. // #include <nlohmann/detail/exceptions.hpp>
  8669. // #include <nlohmann/detail/macro_scope.hpp>
  8670. // #include <nlohmann/detail/value_t.hpp>
  8671. namespace nlohmann
  8672. {
  8673. template<typename BasicJsonType>
  8674. class json_pointer
  8675. {
  8676. // allow basic_json to access private members
  8677. NLOHMANN_BASIC_JSON_TPL_DECLARATION
  8678. friend class basic_json;
  8679. public:
  8680. /*!
  8681. @brief create JSON pointer
  8682. Create a JSON pointer according to the syntax described in
  8683. [Section 3 of RFC6901](https://tools.ietf.org/html/rfc6901#section-3).
  8684. @param[in] s string representing the JSON pointer; if omitted, the empty
  8685. string is assumed which references the whole JSON value
  8686. @throw parse_error.107 if the given JSON pointer @a s is nonempty and does
  8687. not begin with a slash (`/`); see example below
  8688. @throw parse_error.108 if a tilde (`~`) in the given JSON pointer @a s is
  8689. not followed by `0` (representing `~`) or `1` (representing `/`); see
  8690. example below
  8691. @liveexample{The example shows the construction several valid JSON pointers
  8692. as well as the exceptional behavior.,json_pointer}
  8693. @since version 2.0.0
  8694. */
  8695. explicit json_pointer(const std::string& s = "")
  8696. : reference_tokens(split(s))
  8697. {}
  8698. /*!
  8699. @brief return a string representation of the JSON pointer
  8700. @invariant For each JSON pointer `ptr`, it holds:
  8701. @code {.cpp}
  8702. ptr == json_pointer(ptr.to_string());
  8703. @endcode
  8704. @return a string representation of the JSON pointer
  8705. @liveexample{The example shows the result of `to_string`.,json_pointer__to_string}
  8706. @since version 2.0.0
  8707. */
  8708. std::string to_string() const
  8709. {
  8710. return std::accumulate(reference_tokens.begin(), reference_tokens.end(),
  8711. std::string{},
  8712. [](const std::string & a, const std::string & b)
  8713. {
  8714. return a + "/" + escape(b);
  8715. });
  8716. }
  8717. /// @copydoc to_string()
  8718. operator std::string() const
  8719. {
  8720. return to_string();
  8721. }
  8722. /*!
  8723. @brief append another JSON pointer at the end of this JSON pointer
  8724. @param[in] ptr JSON pointer to append
  8725. @return JSON pointer with @a ptr appended
  8726. @liveexample{The example shows the usage of `operator/=`.,json_pointer__operator_add}
  8727. @complexity Linear in the length of @a ptr.
  8728. @sa @ref operator/=(std::string) to append a reference token
  8729. @sa @ref operator/=(std::size_t) to append an array index
  8730. @sa @ref operator/(const json_pointer&, const json_pointer&) for a binary operator
  8731. @since version 3.6.0
  8732. */
  8733. json_pointer& operator/=(const json_pointer& ptr)
  8734. {
  8735. reference_tokens.insert(reference_tokens.end(),
  8736. ptr.reference_tokens.begin(),
  8737. ptr.reference_tokens.end());
  8738. return *this;
  8739. }
  8740. /*!
  8741. @brief append an unescaped reference token at the end of this JSON pointer
  8742. @param[in] token reference token to append
  8743. @return JSON pointer with @a token appended without escaping @a token
  8744. @liveexample{The example shows the usage of `operator/=`.,json_pointer__operator_add}
  8745. @complexity Amortized constant.
  8746. @sa @ref operator/=(const json_pointer&) to append a JSON pointer
  8747. @sa @ref operator/=(std::size_t) to append an array index
  8748. @sa @ref operator/(const json_pointer&, std::size_t) for a binary operator
  8749. @since version 3.6.0
  8750. */
  8751. json_pointer& operator/=(std::string token)
  8752. {
  8753. push_back(std::move(token));
  8754. return *this;
  8755. }
  8756. /*!
  8757. @brief append an array index at the end of this JSON pointer
  8758. @param[in] array_index array index ot append
  8759. @return JSON pointer with @a array_index appended
  8760. @liveexample{The example shows the usage of `operator/=`.,json_pointer__operator_add}
  8761. @complexity Amortized constant.
  8762. @sa @ref operator/=(const json_pointer&) to append a JSON pointer
  8763. @sa @ref operator/=(std::string) to append a reference token
  8764. @sa @ref operator/(const json_pointer&, std::string) for a binary operator
  8765. @since version 3.6.0
  8766. */
  8767. json_pointer& operator/=(std::size_t array_index)
  8768. {
  8769. return *this /= std::to_string(array_index);
  8770. }
  8771. /*!
  8772. @brief create a new JSON pointer by appending the right JSON pointer at the end of the left JSON pointer
  8773. @param[in] lhs JSON pointer
  8774. @param[in] rhs JSON pointer
  8775. @return a new JSON pointer with @a rhs appended to @a lhs
  8776. @liveexample{The example shows the usage of `operator/`.,json_pointer__operator_add_binary}
  8777. @complexity Linear in the length of @a lhs and @a rhs.
  8778. @sa @ref operator/=(const json_pointer&) to append a JSON pointer
  8779. @since version 3.6.0
  8780. */
  8781. friend json_pointer operator/(const json_pointer& lhs,
  8782. const json_pointer& rhs)
  8783. {
  8784. return json_pointer(lhs) /= rhs;
  8785. }
  8786. /*!
  8787. @brief create a new JSON pointer by appending the unescaped token at the end of the JSON pointer
  8788. @param[in] ptr JSON pointer
  8789. @param[in] token reference token
  8790. @return a new JSON pointer with unescaped @a token appended to @a ptr
  8791. @liveexample{The example shows the usage of `operator/`.,json_pointer__operator_add_binary}
  8792. @complexity Linear in the length of @a ptr.
  8793. @sa @ref operator/=(std::string) to append a reference token
  8794. @since version 3.6.0
  8795. */
  8796. friend json_pointer operator/(const json_pointer& ptr, std::string token)
  8797. {
  8798. return json_pointer(ptr) /= std::move(token);
  8799. }
  8800. /*!
  8801. @brief create a new JSON pointer by appending the array-index-token at the end of the JSON pointer
  8802. @param[in] ptr JSON pointer
  8803. @param[in] array_index array index
  8804. @return a new JSON pointer with @a array_index appended to @a ptr
  8805. @liveexample{The example shows the usage of `operator/`.,json_pointer__operator_add_binary}
  8806. @complexity Linear in the length of @a ptr.
  8807. @sa @ref operator/=(std::size_t) to append an array index
  8808. @since version 3.6.0
  8809. */
  8810. friend json_pointer operator/(const json_pointer& ptr, std::size_t array_index)
  8811. {
  8812. return json_pointer(ptr) /= array_index;
  8813. }
  8814. /*!
  8815. @brief returns the parent of this JSON pointer
  8816. @return parent of this JSON pointer; in case this JSON pointer is the root,
  8817. the root itself is returned
  8818. @complexity Linear in the length of the JSON pointer.
  8819. @liveexample{The example shows the result of `parent_pointer` for different
  8820. JSON Pointers.,json_pointer__parent_pointer}
  8821. @since version 3.6.0
  8822. */
  8823. json_pointer parent_pointer() const
  8824. {
  8825. if (empty())
  8826. {
  8827. return *this;
  8828. }
  8829. json_pointer res = *this;
  8830. res.pop_back();
  8831. return res;
  8832. }
  8833. /*!
  8834. @brief remove last reference token
  8835. @pre not `empty()`
  8836. @liveexample{The example shows the usage of `pop_back`.,json_pointer__pop_back}
  8837. @complexity Constant.
  8838. @throw out_of_range.405 if JSON pointer has no parent
  8839. @since version 3.6.0
  8840. */
  8841. void pop_back()
  8842. {
  8843. if (JSON_HEDLEY_UNLIKELY(empty()))
  8844. {
  8845. JSON_THROW(detail::out_of_range::create(405, "JSON pointer has no parent"));
  8846. }
  8847. reference_tokens.pop_back();
  8848. }
  8849. /*!
  8850. @brief return last reference token
  8851. @pre not `empty()`
  8852. @return last reference token
  8853. @liveexample{The example shows the usage of `back`.,json_pointer__back}
  8854. @complexity Constant.
  8855. @throw out_of_range.405 if JSON pointer has no parent
  8856. @since version 3.6.0
  8857. */
  8858. const std::string& back()
  8859. {
  8860. if (JSON_HEDLEY_UNLIKELY(empty()))
  8861. {
  8862. JSON_THROW(detail::out_of_range::create(405, "JSON pointer has no parent"));
  8863. }
  8864. return reference_tokens.back();
  8865. }
  8866. /*!
  8867. @brief append an unescaped token at the end of the reference pointer
  8868. @param[in] token token to add
  8869. @complexity Amortized constant.
  8870. @liveexample{The example shows the result of `push_back` for different
  8871. JSON Pointers.,json_pointer__push_back}
  8872. @since version 3.6.0
  8873. */
  8874. void push_back(const std::string& token)
  8875. {
  8876. reference_tokens.push_back(token);
  8877. }
  8878. /// @copydoc push_back(const std::string&)
  8879. void push_back(std::string&& token)
  8880. {
  8881. reference_tokens.push_back(std::move(token));
  8882. }
  8883. /*!
  8884. @brief return whether pointer points to the root document
  8885. @return true iff the JSON pointer points to the root document
  8886. @complexity Constant.
  8887. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  8888. @liveexample{The example shows the result of `empty` for different JSON
  8889. Pointers.,json_pointer__empty}
  8890. @since version 3.6.0
  8891. */
  8892. bool empty() const noexcept
  8893. {
  8894. return reference_tokens.empty();
  8895. }
  8896. private:
  8897. /*!
  8898. @param[in] s reference token to be converted into an array index
  8899. @return integer representation of @a s
  8900. @throw out_of_range.404 if string @a s could not be converted to an integer
  8901. */
  8902. static int array_index(const std::string& s)
  8903. {
  8904. std::size_t processed_chars = 0;
  8905. const int res = std::stoi(s, &processed_chars);
  8906. // check if the string was completely read
  8907. if (JSON_HEDLEY_UNLIKELY(processed_chars != s.size()))
  8908. {
  8909. JSON_THROW(detail::out_of_range::create(404, "unresolved reference token '" + s + "'"));
  8910. }
  8911. return res;
  8912. }
  8913. json_pointer top() const
  8914. {
  8915. if (JSON_HEDLEY_UNLIKELY(empty()))
  8916. {
  8917. JSON_THROW(detail::out_of_range::create(405, "JSON pointer has no parent"));
  8918. }
  8919. json_pointer result = *this;
  8920. result.reference_tokens = {reference_tokens[0]};
  8921. return result;
  8922. }
  8923. /*!
  8924. @brief create and return a reference to the pointed to value
  8925. @complexity Linear in the number of reference tokens.
  8926. @throw parse_error.109 if array index is not a number
  8927. @throw type_error.313 if value cannot be unflattened
  8928. */
  8929. BasicJsonType& get_and_create(BasicJsonType& j) const
  8930. {
  8931. using size_type = typename BasicJsonType::size_type;
  8932. auto result = &j;
  8933. // in case no reference tokens exist, return a reference to the JSON value
  8934. // j which will be overwritten by a primitive value
  8935. for (const auto& reference_token : reference_tokens)
  8936. {
  8937. switch (result->type())
  8938. {
  8939. case detail::value_t::null:
  8940. {
  8941. if (reference_token == "0")
  8942. {
  8943. // start a new array if reference token is 0
  8944. result = &result->operator[](0);
  8945. }
  8946. else
  8947. {
  8948. // start a new object otherwise
  8949. result = &result->operator[](reference_token);
  8950. }
  8951. break;
  8952. }
  8953. case detail::value_t::object:
  8954. {
  8955. // create an entry in the object
  8956. result = &result->operator[](reference_token);
  8957. break;
  8958. }
  8959. case detail::value_t::array:
  8960. {
  8961. // create an entry in the array
  8962. JSON_TRY
  8963. {
  8964. result = &result->operator[](static_cast<size_type>(array_index(reference_token)));
  8965. }
  8966. JSON_CATCH(std::invalid_argument&)
  8967. {
  8968. JSON_THROW(detail::parse_error::create(109, 0, "array index '" + reference_token + "' is not a number"));
  8969. }
  8970. break;
  8971. }
  8972. /*
  8973. The following code is only reached if there exists a reference
  8974. token _and_ the current value is primitive. In this case, we have
  8975. an error situation, because primitive values may only occur as
  8976. single value; that is, with an empty list of reference tokens.
  8977. */
  8978. default:
  8979. JSON_THROW(detail::type_error::create(313, "invalid value to unflatten"));
  8980. }
  8981. }
  8982. return *result;
  8983. }
  8984. /*!
  8985. @brief return a reference to the pointed to value
  8986. @note This version does not throw if a value is not present, but tries to
  8987. create nested values instead. For instance, calling this function
  8988. with pointer `"/this/that"` on a null value is equivalent to calling
  8989. `operator[]("this").operator[]("that")` on that value, effectively
  8990. changing the null value to an object.
  8991. @param[in] ptr a JSON value
  8992. @return reference to the JSON value pointed to by the JSON pointer
  8993. @complexity Linear in the length of the JSON pointer.
  8994. @throw parse_error.106 if an array index begins with '0'
  8995. @throw parse_error.109 if an array index was not a number
  8996. @throw out_of_range.404 if the JSON pointer can not be resolved
  8997. */
  8998. BasicJsonType& get_unchecked(BasicJsonType* ptr) const
  8999. {
  9000. using size_type = typename BasicJsonType::size_type;
  9001. for (const auto& reference_token : reference_tokens)
  9002. {
  9003. // convert null values to arrays or objects before continuing
  9004. if (ptr->is_null())
  9005. {
  9006. // check if reference token is a number
  9007. const bool nums =
  9008. std::all_of(reference_token.begin(), reference_token.end(),
  9009. [](const unsigned char x)
  9010. {
  9011. return std::isdigit(x);
  9012. });
  9013. // change value to array for numbers or "-" or to object otherwise
  9014. *ptr = (nums or reference_token == "-")
  9015. ? detail::value_t::array
  9016. : detail::value_t::object;
  9017. }
  9018. switch (ptr->type())
  9019. {
  9020. case detail::value_t::object:
  9021. {
  9022. // use unchecked object access
  9023. ptr = &ptr->operator[](reference_token);
  9024. break;
  9025. }
  9026. case detail::value_t::array:
  9027. {
  9028. // error condition (cf. RFC 6901, Sect. 4)
  9029. if (JSON_HEDLEY_UNLIKELY(reference_token.size() > 1 and reference_token[0] == '0'))
  9030. {
  9031. JSON_THROW(detail::parse_error::create(106, 0,
  9032. "array index '" + reference_token +
  9033. "' must not begin with '0'"));
  9034. }
  9035. if (reference_token == "-")
  9036. {
  9037. // explicitly treat "-" as index beyond the end
  9038. ptr = &ptr->operator[](ptr->m_value.array->size());
  9039. }
  9040. else
  9041. {
  9042. // convert array index to number; unchecked access
  9043. JSON_TRY
  9044. {
  9045. ptr = &ptr->operator[](
  9046. static_cast<size_type>(array_index(reference_token)));
  9047. }
  9048. JSON_CATCH(std::invalid_argument&)
  9049. {
  9050. JSON_THROW(detail::parse_error::create(109, 0, "array index '" + reference_token + "' is not a number"));
  9051. }
  9052. }
  9053. break;
  9054. }
  9055. default:
  9056. JSON_THROW(detail::out_of_range::create(404, "unresolved reference token '" + reference_token + "'"));
  9057. }
  9058. }
  9059. return *ptr;
  9060. }
  9061. /*!
  9062. @throw parse_error.106 if an array index begins with '0'
  9063. @throw parse_error.109 if an array index was not a number
  9064. @throw out_of_range.402 if the array index '-' is used
  9065. @throw out_of_range.404 if the JSON pointer can not be resolved
  9066. */
  9067. BasicJsonType& get_checked(BasicJsonType* ptr) const
  9068. {
  9069. using size_type = typename BasicJsonType::size_type;
  9070. for (const auto& reference_token : reference_tokens)
  9071. {
  9072. switch (ptr->type())
  9073. {
  9074. case detail::value_t::object:
  9075. {
  9076. // note: at performs range check
  9077. ptr = &ptr->at(reference_token);
  9078. break;
  9079. }
  9080. case detail::value_t::array:
  9081. {
  9082. if (JSON_HEDLEY_UNLIKELY(reference_token == "-"))
  9083. {
  9084. // "-" always fails the range check
  9085. JSON_THROW(detail::out_of_range::create(402,
  9086. "array index '-' (" + std::to_string(ptr->m_value.array->size()) +
  9087. ") is out of range"));
  9088. }
  9089. // error condition (cf. RFC 6901, Sect. 4)
  9090. if (JSON_HEDLEY_UNLIKELY(reference_token.size() > 1 and reference_token[0] == '0'))
  9091. {
  9092. JSON_THROW(detail::parse_error::create(106, 0,
  9093. "array index '" + reference_token +
  9094. "' must not begin with '0'"));
  9095. }
  9096. // note: at performs range check
  9097. JSON_TRY
  9098. {
  9099. ptr = &ptr->at(static_cast<size_type>(array_index(reference_token)));
  9100. }
  9101. JSON_CATCH(std::invalid_argument&)
  9102. {
  9103. JSON_THROW(detail::parse_error::create(109, 0, "array index '" + reference_token + "' is not a number"));
  9104. }
  9105. break;
  9106. }
  9107. default:
  9108. JSON_THROW(detail::out_of_range::create(404, "unresolved reference token '" + reference_token + "'"));
  9109. }
  9110. }
  9111. return *ptr;
  9112. }
  9113. /*!
  9114. @brief return a const reference to the pointed to value
  9115. @param[in] ptr a JSON value
  9116. @return const reference to the JSON value pointed to by the JSON
  9117. pointer
  9118. @throw parse_error.106 if an array index begins with '0'
  9119. @throw parse_error.109 if an array index was not a number
  9120. @throw out_of_range.402 if the array index '-' is used
  9121. @throw out_of_range.404 if the JSON pointer can not be resolved
  9122. */
  9123. const BasicJsonType& get_unchecked(const BasicJsonType* ptr) const
  9124. {
  9125. using size_type = typename BasicJsonType::size_type;
  9126. for (const auto& reference_token : reference_tokens)
  9127. {
  9128. switch (ptr->type())
  9129. {
  9130. case detail::value_t::object:
  9131. {
  9132. // use unchecked object access
  9133. ptr = &ptr->operator[](reference_token);
  9134. break;
  9135. }
  9136. case detail::value_t::array:
  9137. {
  9138. if (JSON_HEDLEY_UNLIKELY(reference_token == "-"))
  9139. {
  9140. // "-" cannot be used for const access
  9141. JSON_THROW(detail::out_of_range::create(402,
  9142. "array index '-' (" + std::to_string(ptr->m_value.array->size()) +
  9143. ") is out of range"));
  9144. }
  9145. // error condition (cf. RFC 6901, Sect. 4)
  9146. if (JSON_HEDLEY_UNLIKELY(reference_token.size() > 1 and reference_token[0] == '0'))
  9147. {
  9148. JSON_THROW(detail::parse_error::create(106, 0,
  9149. "array index '" + reference_token +
  9150. "' must not begin with '0'"));
  9151. }
  9152. // use unchecked array access
  9153. JSON_TRY
  9154. {
  9155. ptr = &ptr->operator[](
  9156. static_cast<size_type>(array_index(reference_token)));
  9157. }
  9158. JSON_CATCH(std::invalid_argument&)
  9159. {
  9160. JSON_THROW(detail::parse_error::create(109, 0, "array index '" + reference_token + "' is not a number"));
  9161. }
  9162. break;
  9163. }
  9164. default:
  9165. JSON_THROW(detail::out_of_range::create(404, "unresolved reference token '" + reference_token + "'"));
  9166. }
  9167. }
  9168. return *ptr;
  9169. }
  9170. /*!
  9171. @throw parse_error.106 if an array index begins with '0'
  9172. @throw parse_error.109 if an array index was not a number
  9173. @throw out_of_range.402 if the array index '-' is used
  9174. @throw out_of_range.404 if the JSON pointer can not be resolved
  9175. */
  9176. const BasicJsonType& get_checked(const BasicJsonType* ptr) const
  9177. {
  9178. using size_type = typename BasicJsonType::size_type;
  9179. for (const auto& reference_token : reference_tokens)
  9180. {
  9181. switch (ptr->type())
  9182. {
  9183. case detail::value_t::object:
  9184. {
  9185. // note: at performs range check
  9186. ptr = &ptr->at(reference_token);
  9187. break;
  9188. }
  9189. case detail::value_t::array:
  9190. {
  9191. if (JSON_HEDLEY_UNLIKELY(reference_token == "-"))
  9192. {
  9193. // "-" always fails the range check
  9194. JSON_THROW(detail::out_of_range::create(402,
  9195. "array index '-' (" + std::to_string(ptr->m_value.array->size()) +
  9196. ") is out of range"));
  9197. }
  9198. // error condition (cf. RFC 6901, Sect. 4)
  9199. if (JSON_HEDLEY_UNLIKELY(reference_token.size() > 1 and reference_token[0] == '0'))
  9200. {
  9201. JSON_THROW(detail::parse_error::create(106, 0,
  9202. "array index '" + reference_token +
  9203. "' must not begin with '0'"));
  9204. }
  9205. // note: at performs range check
  9206. JSON_TRY
  9207. {
  9208. ptr = &ptr->at(static_cast<size_type>(array_index(reference_token)));
  9209. }
  9210. JSON_CATCH(std::invalid_argument&)
  9211. {
  9212. JSON_THROW(detail::parse_error::create(109, 0, "array index '" + reference_token + "' is not a number"));
  9213. }
  9214. break;
  9215. }
  9216. default:
  9217. JSON_THROW(detail::out_of_range::create(404, "unresolved reference token '" + reference_token + "'"));
  9218. }
  9219. }
  9220. return *ptr;
  9221. }
  9222. /*!
  9223. @throw parse_error.106 if an array index begins with '0'
  9224. @throw parse_error.109 if an array index was not a number
  9225. */
  9226. bool contains(const BasicJsonType* ptr) const
  9227. {
  9228. using size_type = typename BasicJsonType::size_type;
  9229. for (const auto& reference_token : reference_tokens)
  9230. {
  9231. switch (ptr->type())
  9232. {
  9233. case detail::value_t::object:
  9234. {
  9235. if (not ptr->contains(reference_token))
  9236. {
  9237. // we did not find the key in the object
  9238. return false;
  9239. }
  9240. ptr = &ptr->operator[](reference_token);
  9241. break;
  9242. }
  9243. case detail::value_t::array:
  9244. {
  9245. if (JSON_HEDLEY_UNLIKELY(reference_token == "-"))
  9246. {
  9247. // "-" always fails the range check
  9248. return false;
  9249. }
  9250. // error condition (cf. RFC 6901, Sect. 4)
  9251. if (JSON_HEDLEY_UNLIKELY(reference_token.size() > 1 and reference_token[0] == '0'))
  9252. {
  9253. JSON_THROW(detail::parse_error::create(106, 0,
  9254. "array index '" + reference_token +
  9255. "' must not begin with '0'"));
  9256. }
  9257. JSON_TRY
  9258. {
  9259. const auto idx = static_cast<size_type>(array_index(reference_token));
  9260. if (idx >= ptr->size())
  9261. {
  9262. // index out of range
  9263. return false;
  9264. }
  9265. ptr = &ptr->operator[](idx);
  9266. break;
  9267. }
  9268. JSON_CATCH(std::invalid_argument&)
  9269. {
  9270. JSON_THROW(detail::parse_error::create(109, 0, "array index '" + reference_token + "' is not a number"));
  9271. }
  9272. break;
  9273. }
  9274. default:
  9275. {
  9276. // we do not expect primitive values if there is still a
  9277. // reference token to process
  9278. return false;
  9279. }
  9280. }
  9281. }
  9282. // no reference token left means we found a primitive value
  9283. return true;
  9284. }
  9285. /*!
  9286. @brief split the string input to reference tokens
  9287. @note This function is only called by the json_pointer constructor.
  9288. All exceptions below are documented there.
  9289. @throw parse_error.107 if the pointer is not empty or begins with '/'
  9290. @throw parse_error.108 if character '~' is not followed by '0' or '1'
  9291. */
  9292. static std::vector<std::string> split(const std::string& reference_string)
  9293. {
  9294. std::vector<std::string> result;
  9295. // special case: empty reference string -> no reference tokens
  9296. if (reference_string.empty())
  9297. {
  9298. return result;
  9299. }
  9300. // check if nonempty reference string begins with slash
  9301. if (JSON_HEDLEY_UNLIKELY(reference_string[0] != '/'))
  9302. {
  9303. JSON_THROW(detail::parse_error::create(107, 1,
  9304. "JSON pointer must be empty or begin with '/' - was: '" +
  9305. reference_string + "'"));
  9306. }
  9307. // extract the reference tokens:
  9308. // - slash: position of the last read slash (or end of string)
  9309. // - start: position after the previous slash
  9310. for (
  9311. // search for the first slash after the first character
  9312. std::size_t slash = reference_string.find_first_of('/', 1),
  9313. // set the beginning of the first reference token
  9314. start = 1;
  9315. // we can stop if start == 0 (if slash == std::string::npos)
  9316. start != 0;
  9317. // set the beginning of the next reference token
  9318. // (will eventually be 0 if slash == std::string::npos)
  9319. start = (slash == std::string::npos) ? 0 : slash + 1,
  9320. // find next slash
  9321. slash = reference_string.find_first_of('/', start))
  9322. {
  9323. // use the text between the beginning of the reference token
  9324. // (start) and the last slash (slash).
  9325. auto reference_token = reference_string.substr(start, slash - start);
  9326. // check reference tokens are properly escaped
  9327. for (std::size_t pos = reference_token.find_first_of('~');
  9328. pos != std::string::npos;
  9329. pos = reference_token.find_first_of('~', pos + 1))
  9330. {
  9331. assert(reference_token[pos] == '~');
  9332. // ~ must be followed by 0 or 1
  9333. if (JSON_HEDLEY_UNLIKELY(pos == reference_token.size() - 1 or
  9334. (reference_token[pos + 1] != '0' and
  9335. reference_token[pos + 1] != '1')))
  9336. {
  9337. JSON_THROW(detail::parse_error::create(108, 0, "escape character '~' must be followed with '0' or '1'"));
  9338. }
  9339. }
  9340. // finally, store the reference token
  9341. unescape(reference_token);
  9342. result.push_back(reference_token);
  9343. }
  9344. return result;
  9345. }
  9346. /*!
  9347. @brief replace all occurrences of a substring by another string
  9348. @param[in,out] s the string to manipulate; changed so that all
  9349. occurrences of @a f are replaced with @a t
  9350. @param[in] f the substring to replace with @a t
  9351. @param[in] t the string to replace @a f
  9352. @pre The search string @a f must not be empty. **This precondition is
  9353. enforced with an assertion.**
  9354. @since version 2.0.0
  9355. */
  9356. static void replace_substring(std::string& s, const std::string& f,
  9357. const std::string& t)
  9358. {
  9359. assert(not f.empty());
  9360. for (auto pos = s.find(f); // find first occurrence of f
  9361. pos != std::string::npos; // make sure f was found
  9362. s.replace(pos, f.size(), t), // replace with t, and
  9363. pos = s.find(f, pos + t.size())) // find next occurrence of f
  9364. {}
  9365. }
  9366. /// escape "~" to "~0" and "/" to "~1"
  9367. static std::string escape(std::string s)
  9368. {
  9369. replace_substring(s, "~", "~0");
  9370. replace_substring(s, "/", "~1");
  9371. return s;
  9372. }
  9373. /// unescape "~1" to tilde and "~0" to slash (order is important!)
  9374. static void unescape(std::string& s)
  9375. {
  9376. replace_substring(s, "~1", "/");
  9377. replace_substring(s, "~0", "~");
  9378. }
  9379. /*!
  9380. @param[in] reference_string the reference string to the current value
  9381. @param[in] value the value to consider
  9382. @param[in,out] result the result object to insert values to
  9383. @note Empty objects or arrays are flattened to `null`.
  9384. */
  9385. static void flatten(const std::string& reference_string,
  9386. const BasicJsonType& value,
  9387. BasicJsonType& result)
  9388. {
  9389. switch (value.type())
  9390. {
  9391. case detail::value_t::array:
  9392. {
  9393. if (value.m_value.array->empty())
  9394. {
  9395. // flatten empty array as null
  9396. result[reference_string] = nullptr;
  9397. }
  9398. else
  9399. {
  9400. // iterate array and use index as reference string
  9401. for (std::size_t i = 0; i < value.m_value.array->size(); ++i)
  9402. {
  9403. flatten(reference_string + "/" + std::to_string(i),
  9404. value.m_value.array->operator[](i), result);
  9405. }
  9406. }
  9407. break;
  9408. }
  9409. case detail::value_t::object:
  9410. {
  9411. if (value.m_value.object->empty())
  9412. {
  9413. // flatten empty object as null
  9414. result[reference_string] = nullptr;
  9415. }
  9416. else
  9417. {
  9418. // iterate object and use keys as reference string
  9419. for (const auto& element : *value.m_value.object)
  9420. {
  9421. flatten(reference_string + "/" + escape(element.first), element.second, result);
  9422. }
  9423. }
  9424. break;
  9425. }
  9426. default:
  9427. {
  9428. // add primitive value with its reference string
  9429. result[reference_string] = value;
  9430. break;
  9431. }
  9432. }
  9433. }
  9434. /*!
  9435. @param[in] value flattened JSON
  9436. @return unflattened JSON
  9437. @throw parse_error.109 if array index is not a number
  9438. @throw type_error.314 if value is not an object
  9439. @throw type_error.315 if object values are not primitive
  9440. @throw type_error.313 if value cannot be unflattened
  9441. */
  9442. static BasicJsonType
  9443. unflatten(const BasicJsonType& value)
  9444. {
  9445. if (JSON_HEDLEY_UNLIKELY(not value.is_object()))
  9446. {
  9447. JSON_THROW(detail::type_error::create(314, "only objects can be unflattened"));
  9448. }
  9449. BasicJsonType result;
  9450. // iterate the JSON object values
  9451. for (const auto& element : *value.m_value.object)
  9452. {
  9453. if (JSON_HEDLEY_UNLIKELY(not element.second.is_primitive()))
  9454. {
  9455. JSON_THROW(detail::type_error::create(315, "values in object must be primitive"));
  9456. }
  9457. // assign value to reference pointed to by JSON pointer; Note that if
  9458. // the JSON pointer is "" (i.e., points to the whole value), function
  9459. // get_and_create returns a reference to result itself. An assignment
  9460. // will then create a primitive value.
  9461. json_pointer(element.first).get_and_create(result) = element.second;
  9462. }
  9463. return result;
  9464. }
  9465. /*!
  9466. @brief compares two JSON pointers for equality
  9467. @param[in] lhs JSON pointer to compare
  9468. @param[in] rhs JSON pointer to compare
  9469. @return whether @a lhs is equal to @a rhs
  9470. @complexity Linear in the length of the JSON pointer
  9471. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  9472. */
  9473. friend bool operator==(json_pointer const& lhs,
  9474. json_pointer const& rhs) noexcept
  9475. {
  9476. return lhs.reference_tokens == rhs.reference_tokens;
  9477. }
  9478. /*!
  9479. @brief compares two JSON pointers for inequality
  9480. @param[in] lhs JSON pointer to compare
  9481. @param[in] rhs JSON pointer to compare
  9482. @return whether @a lhs is not equal @a rhs
  9483. @complexity Linear in the length of the JSON pointer
  9484. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  9485. */
  9486. friend bool operator!=(json_pointer const& lhs,
  9487. json_pointer const& rhs) noexcept
  9488. {
  9489. return not (lhs == rhs);
  9490. }
  9491. /// the reference tokens
  9492. std::vector<std::string> reference_tokens;
  9493. };
  9494. } // namespace nlohmann
  9495. // #include <nlohmann/detail/json_ref.hpp>
  9496. #include <initializer_list>
  9497. #include <utility>
  9498. // #include <nlohmann/detail/meta/type_traits.hpp>
  9499. namespace nlohmann
  9500. {
  9501. namespace detail
  9502. {
  9503. template<typename BasicJsonType>
  9504. class json_ref
  9505. {
  9506. public:
  9507. using value_type = BasicJsonType;
  9508. json_ref(value_type&& value)
  9509. : owned_value(std::move(value)), value_ref(&owned_value), is_rvalue(true)
  9510. {}
  9511. json_ref(const value_type& value)
  9512. : value_ref(const_cast<value_type*>(&value)), is_rvalue(false)
  9513. {}
  9514. json_ref(std::initializer_list<json_ref> init)
  9515. : owned_value(init), value_ref(&owned_value), is_rvalue(true)
  9516. {}
  9517. template <
  9518. class... Args,
  9519. enable_if_t<std::is_constructible<value_type, Args...>::value, int> = 0 >
  9520. json_ref(Args && ... args)
  9521. : owned_value(std::forward<Args>(args)...), value_ref(&owned_value),
  9522. is_rvalue(true) {}
  9523. // class should be movable only
  9524. json_ref(json_ref&&) = default;
  9525. json_ref(const json_ref&) = delete;
  9526. json_ref& operator=(const json_ref&) = delete;
  9527. json_ref& operator=(json_ref&&) = delete;
  9528. ~json_ref() = default;
  9529. value_type moved_or_copied() const
  9530. {
  9531. if (is_rvalue)
  9532. {
  9533. return std::move(*value_ref);
  9534. }
  9535. return *value_ref;
  9536. }
  9537. value_type const& operator*() const
  9538. {
  9539. return *static_cast<value_type const*>(value_ref);
  9540. }
  9541. value_type const* operator->() const
  9542. {
  9543. return static_cast<value_type const*>(value_ref);
  9544. }
  9545. private:
  9546. mutable value_type owned_value = nullptr;
  9547. value_type* value_ref = nullptr;
  9548. const bool is_rvalue;
  9549. };
  9550. } // namespace detail
  9551. } // namespace nlohmann
  9552. // #include <nlohmann/detail/macro_scope.hpp>
  9553. // #include <nlohmann/detail/meta/cpp_future.hpp>
  9554. // #include <nlohmann/detail/meta/type_traits.hpp>
  9555. // #include <nlohmann/detail/output/binary_writer.hpp>
  9556. #include <algorithm> // reverse
  9557. #include <array> // array
  9558. #include <cstdint> // uint8_t, uint16_t, uint32_t, uint64_t
  9559. #include <cstring> // memcpy
  9560. #include <limits> // numeric_limits
  9561. #include <string> // string
  9562. // #include <nlohmann/detail/input/binary_reader.hpp>
  9563. // #include <nlohmann/detail/macro_scope.hpp>
  9564. // #include <nlohmann/detail/output/output_adapters.hpp>
  9565. #include <algorithm> // copy
  9566. #include <cstddef> // size_t
  9567. #include <ios> // streamsize
  9568. #include <iterator> // back_inserter
  9569. #include <memory> // shared_ptr, make_shared
  9570. #include <ostream> // basic_ostream
  9571. #include <string> // basic_string
  9572. #include <vector> // vector
  9573. // #include <nlohmann/detail/macro_scope.hpp>
  9574. namespace nlohmann
  9575. {
  9576. namespace detail
  9577. {
  9578. /// abstract output adapter interface
  9579. template<typename CharType> struct output_adapter_protocol
  9580. {
  9581. virtual void write_character(CharType c) = 0;
  9582. virtual void write_characters(const CharType* s, std::size_t length) = 0;
  9583. virtual ~output_adapter_protocol() = default;
  9584. };
  9585. /// a type to simplify interfaces
  9586. template<typename CharType>
  9587. using output_adapter_t = std::shared_ptr<output_adapter_protocol<CharType>>;
  9588. /// output adapter for byte vectors
  9589. template<typename CharType>
  9590. class output_vector_adapter : public output_adapter_protocol<CharType>
  9591. {
  9592. public:
  9593. explicit output_vector_adapter(std::vector<CharType>& vec) noexcept
  9594. : v(vec)
  9595. {}
  9596. void write_character(CharType c) override
  9597. {
  9598. v.push_back(c);
  9599. }
  9600. JSON_HEDLEY_NON_NULL(2)
  9601. void write_characters(const CharType* s, std::size_t length) override
  9602. {
  9603. std::copy(s, s + length, std::back_inserter(v));
  9604. }
  9605. private:
  9606. std::vector<CharType>& v;
  9607. };
  9608. /// output adapter for output streams
  9609. template<typename CharType>
  9610. class output_stream_adapter : public output_adapter_protocol<CharType>
  9611. {
  9612. public:
  9613. explicit output_stream_adapter(std::basic_ostream<CharType>& s) noexcept
  9614. : stream(s)
  9615. {}
  9616. void write_character(CharType c) override
  9617. {
  9618. stream.put(c);
  9619. }
  9620. JSON_HEDLEY_NON_NULL(2)
  9621. void write_characters(const CharType* s, std::size_t length) override
  9622. {
  9623. stream.write(s, static_cast<std::streamsize>(length));
  9624. }
  9625. private:
  9626. std::basic_ostream<CharType>& stream;
  9627. };
  9628. /// output adapter for basic_string
  9629. template<typename CharType, typename StringType = std::basic_string<CharType>>
  9630. class output_string_adapter : public output_adapter_protocol<CharType>
  9631. {
  9632. public:
  9633. explicit output_string_adapter(StringType& s) noexcept
  9634. : str(s)
  9635. {}
  9636. void write_character(CharType c) override
  9637. {
  9638. str.push_back(c);
  9639. }
  9640. JSON_HEDLEY_NON_NULL(2)
  9641. void write_characters(const CharType* s, std::size_t length) override
  9642. {
  9643. str.append(s, length);
  9644. }
  9645. private:
  9646. StringType& str;
  9647. };
  9648. template<typename CharType, typename StringType = std::basic_string<CharType>>
  9649. class output_adapter
  9650. {
  9651. public:
  9652. output_adapter(std::vector<CharType>& vec)
  9653. : oa(std::make_shared<output_vector_adapter<CharType>>(vec)) {}
  9654. output_adapter(std::basic_ostream<CharType>& s)
  9655. : oa(std::make_shared<output_stream_adapter<CharType>>(s)) {}
  9656. output_adapter(StringType& s)
  9657. : oa(std::make_shared<output_string_adapter<CharType, StringType>>(s)) {}
  9658. operator output_adapter_t<CharType>()
  9659. {
  9660. return oa;
  9661. }
  9662. private:
  9663. output_adapter_t<CharType> oa = nullptr;
  9664. };
  9665. } // namespace detail
  9666. } // namespace nlohmann
  9667. namespace nlohmann
  9668. {
  9669. namespace detail
  9670. {
  9671. ///////////////////
  9672. // binary writer //
  9673. ///////////////////
  9674. /*!
  9675. @brief serialization to CBOR and MessagePack values
  9676. */
  9677. template<typename BasicJsonType, typename CharType>
  9678. class binary_writer
  9679. {
  9680. using string_t = typename BasicJsonType::string_t;
  9681. public:
  9682. /*!
  9683. @brief create a binary writer
  9684. @param[in] adapter output adapter to write to
  9685. */
  9686. explicit binary_writer(output_adapter_t<CharType> adapter) : oa(adapter)
  9687. {
  9688. assert(oa);
  9689. }
  9690. /*!
  9691. @param[in] j JSON value to serialize
  9692. @pre j.type() == value_t::object
  9693. */
  9694. void write_bson(const BasicJsonType& j)
  9695. {
  9696. switch (j.type())
  9697. {
  9698. case value_t::object:
  9699. {
  9700. write_bson_object(*j.m_value.object);
  9701. break;
  9702. }
  9703. default:
  9704. {
  9705. JSON_THROW(type_error::create(317, "to serialize to BSON, top-level type must be object, but is " + std::string(j.type_name())));
  9706. }
  9707. }
  9708. }
  9709. /*!
  9710. @param[in] j JSON value to serialize
  9711. */
  9712. void write_cbor(const BasicJsonType& j)
  9713. {
  9714. switch (j.type())
  9715. {
  9716. case value_t::null:
  9717. {
  9718. oa->write_character(to_char_type(0xF6));
  9719. break;
  9720. }
  9721. case value_t::boolean:
  9722. {
  9723. oa->write_character(j.m_value.boolean
  9724. ? to_char_type(0xF5)
  9725. : to_char_type(0xF4));
  9726. break;
  9727. }
  9728. case value_t::number_integer:
  9729. {
  9730. if (j.m_value.number_integer >= 0)
  9731. {
  9732. // CBOR does not differentiate between positive signed
  9733. // integers and unsigned integers. Therefore, we used the
  9734. // code from the value_t::number_unsigned case here.
  9735. if (j.m_value.number_integer <= 0x17)
  9736. {
  9737. write_number(static_cast<std::uint8_t>(j.m_value.number_integer));
  9738. }
  9739. else if (j.m_value.number_integer <= (std::numeric_limits<std::uint8_t>::max)())
  9740. {
  9741. oa->write_character(to_char_type(0x18));
  9742. write_number(static_cast<std::uint8_t>(j.m_value.number_integer));
  9743. }
  9744. else if (j.m_value.number_integer <= (std::numeric_limits<std::uint16_t>::max)())
  9745. {
  9746. oa->write_character(to_char_type(0x19));
  9747. write_number(static_cast<std::uint16_t>(j.m_value.number_integer));
  9748. }
  9749. else if (j.m_value.number_integer <= (std::numeric_limits<std::uint32_t>::max)())
  9750. {
  9751. oa->write_character(to_char_type(0x1A));
  9752. write_number(static_cast<std::uint32_t>(j.m_value.number_integer));
  9753. }
  9754. else
  9755. {
  9756. oa->write_character(to_char_type(0x1B));
  9757. write_number(static_cast<std::uint64_t>(j.m_value.number_integer));
  9758. }
  9759. }
  9760. else
  9761. {
  9762. // The conversions below encode the sign in the first
  9763. // byte, and the value is converted to a positive number.
  9764. const auto positive_number = -1 - j.m_value.number_integer;
  9765. if (j.m_value.number_integer >= -24)
  9766. {
  9767. write_number(static_cast<std::uint8_t>(0x20 + positive_number));
  9768. }
  9769. else if (positive_number <= (std::numeric_limits<std::uint8_t>::max)())
  9770. {
  9771. oa->write_character(to_char_type(0x38));
  9772. write_number(static_cast<std::uint8_t>(positive_number));
  9773. }
  9774. else if (positive_number <= (std::numeric_limits<std::uint16_t>::max)())
  9775. {
  9776. oa->write_character(to_char_type(0x39));
  9777. write_number(static_cast<std::uint16_t>(positive_number));
  9778. }
  9779. else if (positive_number <= (std::numeric_limits<std::uint32_t>::max)())
  9780. {
  9781. oa->write_character(to_char_type(0x3A));
  9782. write_number(static_cast<std::uint32_t>(positive_number));
  9783. }
  9784. else
  9785. {
  9786. oa->write_character(to_char_type(0x3B));
  9787. write_number(static_cast<std::uint64_t>(positive_number));
  9788. }
  9789. }
  9790. break;
  9791. }
  9792. case value_t::number_unsigned:
  9793. {
  9794. if (j.m_value.number_unsigned <= 0x17)
  9795. {
  9796. write_number(static_cast<std::uint8_t>(j.m_value.number_unsigned));
  9797. }
  9798. else if (j.m_value.number_unsigned <= (std::numeric_limits<std::uint8_t>::max)())
  9799. {
  9800. oa->write_character(to_char_type(0x18));
  9801. write_number(static_cast<std::uint8_t>(j.m_value.number_unsigned));
  9802. }
  9803. else if (j.m_value.number_unsigned <= (std::numeric_limits<std::uint16_t>::max)())
  9804. {
  9805. oa->write_character(to_char_type(0x19));
  9806. write_number(static_cast<std::uint16_t>(j.m_value.number_unsigned));
  9807. }
  9808. else if (j.m_value.number_unsigned <= (std::numeric_limits<std::uint32_t>::max)())
  9809. {
  9810. oa->write_character(to_char_type(0x1A));
  9811. write_number(static_cast<std::uint32_t>(j.m_value.number_unsigned));
  9812. }
  9813. else
  9814. {
  9815. oa->write_character(to_char_type(0x1B));
  9816. write_number(static_cast<std::uint64_t>(j.m_value.number_unsigned));
  9817. }
  9818. break;
  9819. }
  9820. case value_t::number_float:
  9821. {
  9822. oa->write_character(get_cbor_float_prefix(j.m_value.number_float));
  9823. write_number(j.m_value.number_float);
  9824. break;
  9825. }
  9826. case value_t::string:
  9827. {
  9828. // step 1: write control byte and the string length
  9829. const auto N = j.m_value.string->size();
  9830. if (N <= 0x17)
  9831. {
  9832. write_number(static_cast<std::uint8_t>(0x60 + N));
  9833. }
  9834. else if (N <= (std::numeric_limits<std::uint8_t>::max)())
  9835. {
  9836. oa->write_character(to_char_type(0x78));
  9837. write_number(static_cast<std::uint8_t>(N));
  9838. }
  9839. else if (N <= (std::numeric_limits<std::uint16_t>::max)())
  9840. {
  9841. oa->write_character(to_char_type(0x79));
  9842. write_number(static_cast<std::uint16_t>(N));
  9843. }
  9844. else if (N <= (std::numeric_limits<std::uint32_t>::max)())
  9845. {
  9846. oa->write_character(to_char_type(0x7A));
  9847. write_number(static_cast<std::uint32_t>(N));
  9848. }
  9849. // LCOV_EXCL_START
  9850. else if (N <= (std::numeric_limits<std::uint64_t>::max)())
  9851. {
  9852. oa->write_character(to_char_type(0x7B));
  9853. write_number(static_cast<std::uint64_t>(N));
  9854. }
  9855. // LCOV_EXCL_STOP
  9856. // step 2: write the string
  9857. oa->write_characters(
  9858. reinterpret_cast<const CharType*>(j.m_value.string->c_str()),
  9859. j.m_value.string->size());
  9860. break;
  9861. }
  9862. case value_t::array:
  9863. {
  9864. // step 1: write control byte and the array size
  9865. const auto N = j.m_value.array->size();
  9866. if (N <= 0x17)
  9867. {
  9868. write_number(static_cast<std::uint8_t>(0x80 + N));
  9869. }
  9870. else if (N <= (std::numeric_limits<std::uint8_t>::max)())
  9871. {
  9872. oa->write_character(to_char_type(0x98));
  9873. write_number(static_cast<std::uint8_t>(N));
  9874. }
  9875. else if (N <= (std::numeric_limits<std::uint16_t>::max)())
  9876. {
  9877. oa->write_character(to_char_type(0x99));
  9878. write_number(static_cast<std::uint16_t>(N));
  9879. }
  9880. else if (N <= (std::numeric_limits<std::uint32_t>::max)())
  9881. {
  9882. oa->write_character(to_char_type(0x9A));
  9883. write_number(static_cast<std::uint32_t>(N));
  9884. }
  9885. // LCOV_EXCL_START
  9886. else if (N <= (std::numeric_limits<std::uint64_t>::max)())
  9887. {
  9888. oa->write_character(to_char_type(0x9B));
  9889. write_number(static_cast<std::uint64_t>(N));
  9890. }
  9891. // LCOV_EXCL_STOP
  9892. // step 2: write each element
  9893. for (const auto& el : *j.m_value.array)
  9894. {
  9895. write_cbor(el);
  9896. }
  9897. break;
  9898. }
  9899. case value_t::object:
  9900. {
  9901. // step 1: write control byte and the object size
  9902. const auto N = j.m_value.object->size();
  9903. if (N <= 0x17)
  9904. {
  9905. write_number(static_cast<std::uint8_t>(0xA0 + N));
  9906. }
  9907. else if (N <= (std::numeric_limits<std::uint8_t>::max)())
  9908. {
  9909. oa->write_character(to_char_type(0xB8));
  9910. write_number(static_cast<std::uint8_t>(N));
  9911. }
  9912. else if (N <= (std::numeric_limits<std::uint16_t>::max)())
  9913. {
  9914. oa->write_character(to_char_type(0xB9));
  9915. write_number(static_cast<std::uint16_t>(N));
  9916. }
  9917. else if (N <= (std::numeric_limits<std::uint32_t>::max)())
  9918. {
  9919. oa->write_character(to_char_type(0xBA));
  9920. write_number(static_cast<std::uint32_t>(N));
  9921. }
  9922. // LCOV_EXCL_START
  9923. else if (N <= (std::numeric_limits<std::uint64_t>::max)())
  9924. {
  9925. oa->write_character(to_char_type(0xBB));
  9926. write_number(static_cast<std::uint64_t>(N));
  9927. }
  9928. // LCOV_EXCL_STOP
  9929. // step 2: write each element
  9930. for (const auto& el : *j.m_value.object)
  9931. {
  9932. write_cbor(el.first);
  9933. write_cbor(el.second);
  9934. }
  9935. break;
  9936. }
  9937. default:
  9938. break;
  9939. }
  9940. }
  9941. /*!
  9942. @param[in] j JSON value to serialize
  9943. */
  9944. void write_msgpack(const BasicJsonType& j)
  9945. {
  9946. switch (j.type())
  9947. {
  9948. case value_t::null: // nil
  9949. {
  9950. oa->write_character(to_char_type(0xC0));
  9951. break;
  9952. }
  9953. case value_t::boolean: // true and false
  9954. {
  9955. oa->write_character(j.m_value.boolean
  9956. ? to_char_type(0xC3)
  9957. : to_char_type(0xC2));
  9958. break;
  9959. }
  9960. case value_t::number_integer:
  9961. {
  9962. if (j.m_value.number_integer >= 0)
  9963. {
  9964. // MessagePack does not differentiate between positive
  9965. // signed integers and unsigned integers. Therefore, we used
  9966. // the code from the value_t::number_unsigned case here.
  9967. if (j.m_value.number_unsigned < 128)
  9968. {
  9969. // positive fixnum
  9970. write_number(static_cast<std::uint8_t>(j.m_value.number_integer));
  9971. }
  9972. else if (j.m_value.number_unsigned <= (std::numeric_limits<std::uint8_t>::max)())
  9973. {
  9974. // uint 8
  9975. oa->write_character(to_char_type(0xCC));
  9976. write_number(static_cast<std::uint8_t>(j.m_value.number_integer));
  9977. }
  9978. else if (j.m_value.number_unsigned <= (std::numeric_limits<std::uint16_t>::max)())
  9979. {
  9980. // uint 16
  9981. oa->write_character(to_char_type(0xCD));
  9982. write_number(static_cast<std::uint16_t>(j.m_value.number_integer));
  9983. }
  9984. else if (j.m_value.number_unsigned <= (std::numeric_limits<std::uint32_t>::max)())
  9985. {
  9986. // uint 32
  9987. oa->write_character(to_char_type(0xCE));
  9988. write_number(static_cast<std::uint32_t>(j.m_value.number_integer));
  9989. }
  9990. else if (j.m_value.number_unsigned <= (std::numeric_limits<std::uint64_t>::max)())
  9991. {
  9992. // uint 64
  9993. oa->write_character(to_char_type(0xCF));
  9994. write_number(static_cast<std::uint64_t>(j.m_value.number_integer));
  9995. }
  9996. }
  9997. else
  9998. {
  9999. if (j.m_value.number_integer >= -32)
  10000. {
  10001. // negative fixnum
  10002. write_number(static_cast<std::int8_t>(j.m_value.number_integer));
  10003. }
  10004. else if (j.m_value.number_integer >= (std::numeric_limits<std::int8_t>::min)() and
  10005. j.m_value.number_integer <= (std::numeric_limits<std::int8_t>::max)())
  10006. {
  10007. // int 8
  10008. oa->write_character(to_char_type(0xD0));
  10009. write_number(static_cast<std::int8_t>(j.m_value.number_integer));
  10010. }
  10011. else if (j.m_value.number_integer >= (std::numeric_limits<std::int16_t>::min)() and
  10012. j.m_value.number_integer <= (std::numeric_limits<std::int16_t>::max)())
  10013. {
  10014. // int 16
  10015. oa->write_character(to_char_type(0xD1));
  10016. write_number(static_cast<std::int16_t>(j.m_value.number_integer));
  10017. }
  10018. else if (j.m_value.number_integer >= (std::numeric_limits<std::int32_t>::min)() and
  10019. j.m_value.number_integer <= (std::numeric_limits<std::int32_t>::max)())
  10020. {
  10021. // int 32
  10022. oa->write_character(to_char_type(0xD2));
  10023. write_number(static_cast<std::int32_t>(j.m_value.number_integer));
  10024. }
  10025. else if (j.m_value.number_integer >= (std::numeric_limits<std::int64_t>::min)() and
  10026. j.m_value.number_integer <= (std::numeric_limits<std::int64_t>::max)())
  10027. {
  10028. // int 64
  10029. oa->write_character(to_char_type(0xD3));
  10030. write_number(static_cast<std::int64_t>(j.m_value.number_integer));
  10031. }
  10032. }
  10033. break;
  10034. }
  10035. case value_t::number_unsigned:
  10036. {
  10037. if (j.m_value.number_unsigned < 128)
  10038. {
  10039. // positive fixnum
  10040. write_number(static_cast<std::uint8_t>(j.m_value.number_integer));
  10041. }
  10042. else if (j.m_value.number_unsigned <= (std::numeric_limits<std::uint8_t>::max)())
  10043. {
  10044. // uint 8
  10045. oa->write_character(to_char_type(0xCC));
  10046. write_number(static_cast<std::uint8_t>(j.m_value.number_integer));
  10047. }
  10048. else if (j.m_value.number_unsigned <= (std::numeric_limits<std::uint16_t>::max)())
  10049. {
  10050. // uint 16
  10051. oa->write_character(to_char_type(0xCD));
  10052. write_number(static_cast<std::uint16_t>(j.m_value.number_integer));
  10053. }
  10054. else if (j.m_value.number_unsigned <= (std::numeric_limits<std::uint32_t>::max)())
  10055. {
  10056. // uint 32
  10057. oa->write_character(to_char_type(0xCE));
  10058. write_number(static_cast<std::uint32_t>(j.m_value.number_integer));
  10059. }
  10060. else if (j.m_value.number_unsigned <= (std::numeric_limits<std::uint64_t>::max)())
  10061. {
  10062. // uint 64
  10063. oa->write_character(to_char_type(0xCF));
  10064. write_number(static_cast<std::uint64_t>(j.m_value.number_integer));
  10065. }
  10066. break;
  10067. }
  10068. case value_t::number_float:
  10069. {
  10070. oa->write_character(get_msgpack_float_prefix(j.m_value.number_float));
  10071. write_number(j.m_value.number_float);
  10072. break;
  10073. }
  10074. case value_t::string:
  10075. {
  10076. // step 1: write control byte and the string length
  10077. const auto N = j.m_value.string->size();
  10078. if (N <= 31)
  10079. {
  10080. // fixstr
  10081. write_number(static_cast<std::uint8_t>(0xA0 | N));
  10082. }
  10083. else if (N <= (std::numeric_limits<std::uint8_t>::max)())
  10084. {
  10085. // str 8
  10086. oa->write_character(to_char_type(0xD9));
  10087. write_number(static_cast<std::uint8_t>(N));
  10088. }
  10089. else if (N <= (std::numeric_limits<std::uint16_t>::max)())
  10090. {
  10091. // str 16
  10092. oa->write_character(to_char_type(0xDA));
  10093. write_number(static_cast<std::uint16_t>(N));
  10094. }
  10095. else if (N <= (std::numeric_limits<std::uint32_t>::max)())
  10096. {
  10097. // str 32
  10098. oa->write_character(to_char_type(0xDB));
  10099. write_number(static_cast<std::uint32_t>(N));
  10100. }
  10101. // step 2: write the string
  10102. oa->write_characters(
  10103. reinterpret_cast<const CharType*>(j.m_value.string->c_str()),
  10104. j.m_value.string->size());
  10105. break;
  10106. }
  10107. case value_t::array:
  10108. {
  10109. // step 1: write control byte and the array size
  10110. const auto N = j.m_value.array->size();
  10111. if (N <= 15)
  10112. {
  10113. // fixarray
  10114. write_number(static_cast<std::uint8_t>(0x90 | N));
  10115. }
  10116. else if (N <= (std::numeric_limits<std::uint16_t>::max)())
  10117. {
  10118. // array 16
  10119. oa->write_character(to_char_type(0xDC));
  10120. write_number(static_cast<std::uint16_t>(N));
  10121. }
  10122. else if (N <= (std::numeric_limits<std::uint32_t>::max)())
  10123. {
  10124. // array 32
  10125. oa->write_character(to_char_type(0xDD));
  10126. write_number(static_cast<std::uint32_t>(N));
  10127. }
  10128. // step 2: write each element
  10129. for (const auto& el : *j.m_value.array)
  10130. {
  10131. write_msgpack(el);
  10132. }
  10133. break;
  10134. }
  10135. case value_t::object:
  10136. {
  10137. // step 1: write control byte and the object size
  10138. const auto N = j.m_value.object->size();
  10139. if (N <= 15)
  10140. {
  10141. // fixmap
  10142. write_number(static_cast<std::uint8_t>(0x80 | (N & 0xF)));
  10143. }
  10144. else if (N <= (std::numeric_limits<std::uint16_t>::max)())
  10145. {
  10146. // map 16
  10147. oa->write_character(to_char_type(0xDE));
  10148. write_number(static_cast<std::uint16_t>(N));
  10149. }
  10150. else if (N <= (std::numeric_limits<std::uint32_t>::max)())
  10151. {
  10152. // map 32
  10153. oa->write_character(to_char_type(0xDF));
  10154. write_number(static_cast<std::uint32_t>(N));
  10155. }
  10156. // step 2: write each element
  10157. for (const auto& el : *j.m_value.object)
  10158. {
  10159. write_msgpack(el.first);
  10160. write_msgpack(el.second);
  10161. }
  10162. break;
  10163. }
  10164. default:
  10165. break;
  10166. }
  10167. }
  10168. /*!
  10169. @param[in] j JSON value to serialize
  10170. @param[in] use_count whether to use '#' prefixes (optimized format)
  10171. @param[in] use_type whether to use '$' prefixes (optimized format)
  10172. @param[in] add_prefix whether prefixes need to be used for this value
  10173. */
  10174. void write_ubjson(const BasicJsonType& j, const bool use_count,
  10175. const bool use_type, const bool add_prefix = true)
  10176. {
  10177. switch (j.type())
  10178. {
  10179. case value_t::null:
  10180. {
  10181. if (add_prefix)
  10182. {
  10183. oa->write_character(to_char_type('Z'));
  10184. }
  10185. break;
  10186. }
  10187. case value_t::boolean:
  10188. {
  10189. if (add_prefix)
  10190. {
  10191. oa->write_character(j.m_value.boolean
  10192. ? to_char_type('T')
  10193. : to_char_type('F'));
  10194. }
  10195. break;
  10196. }
  10197. case value_t::number_integer:
  10198. {
  10199. write_number_with_ubjson_prefix(j.m_value.number_integer, add_prefix);
  10200. break;
  10201. }
  10202. case value_t::number_unsigned:
  10203. {
  10204. write_number_with_ubjson_prefix(j.m_value.number_unsigned, add_prefix);
  10205. break;
  10206. }
  10207. case value_t::number_float:
  10208. {
  10209. write_number_with_ubjson_prefix(j.m_value.number_float, add_prefix);
  10210. break;
  10211. }
  10212. case value_t::string:
  10213. {
  10214. if (add_prefix)
  10215. {
  10216. oa->write_character(to_char_type('S'));
  10217. }
  10218. write_number_with_ubjson_prefix(j.m_value.string->size(), true);
  10219. oa->write_characters(
  10220. reinterpret_cast<const CharType*>(j.m_value.string->c_str()),
  10221. j.m_value.string->size());
  10222. break;
  10223. }
  10224. case value_t::array:
  10225. {
  10226. if (add_prefix)
  10227. {
  10228. oa->write_character(to_char_type('['));
  10229. }
  10230. bool prefix_required = true;
  10231. if (use_type and not j.m_value.array->empty())
  10232. {
  10233. assert(use_count);
  10234. const CharType first_prefix = ubjson_prefix(j.front());
  10235. const bool same_prefix = std::all_of(j.begin() + 1, j.end(),
  10236. [this, first_prefix](const BasicJsonType & v)
  10237. {
  10238. return ubjson_prefix(v) == first_prefix;
  10239. });
  10240. if (same_prefix)
  10241. {
  10242. prefix_required = false;
  10243. oa->write_character(to_char_type('$'));
  10244. oa->write_character(first_prefix);
  10245. }
  10246. }
  10247. if (use_count)
  10248. {
  10249. oa->write_character(to_char_type('#'));
  10250. write_number_with_ubjson_prefix(j.m_value.array->size(), true);
  10251. }
  10252. for (const auto& el : *j.m_value.array)
  10253. {
  10254. write_ubjson(el, use_count, use_type, prefix_required);
  10255. }
  10256. if (not use_count)
  10257. {
  10258. oa->write_character(to_char_type(']'));
  10259. }
  10260. break;
  10261. }
  10262. case value_t::object:
  10263. {
  10264. if (add_prefix)
  10265. {
  10266. oa->write_character(to_char_type('{'));
  10267. }
  10268. bool prefix_required = true;
  10269. if (use_type and not j.m_value.object->empty())
  10270. {
  10271. assert(use_count);
  10272. const CharType first_prefix = ubjson_prefix(j.front());
  10273. const bool same_prefix = std::all_of(j.begin(), j.end(),
  10274. [this, first_prefix](const BasicJsonType & v)
  10275. {
  10276. return ubjson_prefix(v) == first_prefix;
  10277. });
  10278. if (same_prefix)
  10279. {
  10280. prefix_required = false;
  10281. oa->write_character(to_char_type('$'));
  10282. oa->write_character(first_prefix);
  10283. }
  10284. }
  10285. if (use_count)
  10286. {
  10287. oa->write_character(to_char_type('#'));
  10288. write_number_with_ubjson_prefix(j.m_value.object->size(), true);
  10289. }
  10290. for (const auto& el : *j.m_value.object)
  10291. {
  10292. write_number_with_ubjson_prefix(el.first.size(), true);
  10293. oa->write_characters(
  10294. reinterpret_cast<const CharType*>(el.first.c_str()),
  10295. el.first.size());
  10296. write_ubjson(el.second, use_count, use_type, prefix_required);
  10297. }
  10298. if (not use_count)
  10299. {
  10300. oa->write_character(to_char_type('}'));
  10301. }
  10302. break;
  10303. }
  10304. default:
  10305. break;
  10306. }
  10307. }
  10308. private:
  10309. //////////
  10310. // BSON //
  10311. //////////
  10312. /*!
  10313. @return The size of a BSON document entry header, including the id marker
  10314. and the entry name size (and its null-terminator).
  10315. */
  10316. static std::size_t calc_bson_entry_header_size(const string_t& name)
  10317. {
  10318. const auto it = name.find(static_cast<typename string_t::value_type>(0));
  10319. if (JSON_HEDLEY_UNLIKELY(it != BasicJsonType::string_t::npos))
  10320. {
  10321. JSON_THROW(out_of_range::create(409,
  10322. "BSON key cannot contain code point U+0000 (at byte " + std::to_string(it) + ")"));
  10323. }
  10324. return /*id*/ 1ul + name.size() + /*zero-terminator*/1u;
  10325. }
  10326. /*!
  10327. @brief Writes the given @a element_type and @a name to the output adapter
  10328. */
  10329. void write_bson_entry_header(const string_t& name,
  10330. const std::uint8_t element_type)
  10331. {
  10332. oa->write_character(to_char_type(element_type)); // boolean
  10333. oa->write_characters(
  10334. reinterpret_cast<const CharType*>(name.c_str()),
  10335. name.size() + 1u);
  10336. }
  10337. /*!
  10338. @brief Writes a BSON element with key @a name and boolean value @a value
  10339. */
  10340. void write_bson_boolean(const string_t& name,
  10341. const bool value)
  10342. {
  10343. write_bson_entry_header(name, 0x08);
  10344. oa->write_character(value ? to_char_type(0x01) : to_char_type(0x00));
  10345. }
  10346. /*!
  10347. @brief Writes a BSON element with key @a name and double value @a value
  10348. */
  10349. void write_bson_double(const string_t& name,
  10350. const double value)
  10351. {
  10352. write_bson_entry_header(name, 0x01);
  10353. write_number<double, true>(value);
  10354. }
  10355. /*!
  10356. @return The size of the BSON-encoded string in @a value
  10357. */
  10358. static std::size_t calc_bson_string_size(const string_t& value)
  10359. {
  10360. return sizeof(std::int32_t) + value.size() + 1ul;
  10361. }
  10362. /*!
  10363. @brief Writes a BSON element with key @a name and string value @a value
  10364. */
  10365. void write_bson_string(const string_t& name,
  10366. const string_t& value)
  10367. {
  10368. write_bson_entry_header(name, 0x02);
  10369. write_number<std::int32_t, true>(static_cast<std::int32_t>(value.size() + 1ul));
  10370. oa->write_characters(
  10371. reinterpret_cast<const CharType*>(value.c_str()),
  10372. value.size() + 1);
  10373. }
  10374. /*!
  10375. @brief Writes a BSON element with key @a name and null value
  10376. */
  10377. void write_bson_null(const string_t& name)
  10378. {
  10379. write_bson_entry_header(name, 0x0A);
  10380. }
  10381. /*!
  10382. @return The size of the BSON-encoded integer @a value
  10383. */
  10384. static std::size_t calc_bson_integer_size(const std::int64_t value)
  10385. {
  10386. return (std::numeric_limits<std::int32_t>::min)() <= value and value <= (std::numeric_limits<std::int32_t>::max)()
  10387. ? sizeof(std::int32_t)
  10388. : sizeof(std::int64_t);
  10389. }
  10390. /*!
  10391. @brief Writes a BSON element with key @a name and integer @a value
  10392. */
  10393. void write_bson_integer(const string_t& name,
  10394. const std::int64_t value)
  10395. {
  10396. if ((std::numeric_limits<std::int32_t>::min)() <= value and value <= (std::numeric_limits<std::int32_t>::max)())
  10397. {
  10398. write_bson_entry_header(name, 0x10); // int32
  10399. write_number<std::int32_t, true>(static_cast<std::int32_t>(value));
  10400. }
  10401. else
  10402. {
  10403. write_bson_entry_header(name, 0x12); // int64
  10404. write_number<std::int64_t, true>(static_cast<std::int64_t>(value));
  10405. }
  10406. }
  10407. /*!
  10408. @return The size of the BSON-encoded unsigned integer in @a j
  10409. */
  10410. static constexpr std::size_t calc_bson_unsigned_size(const std::uint64_t value) noexcept
  10411. {
  10412. return (value <= static_cast<std::uint64_t>((std::numeric_limits<std::int32_t>::max)()))
  10413. ? sizeof(std::int32_t)
  10414. : sizeof(std::int64_t);
  10415. }
  10416. /*!
  10417. @brief Writes a BSON element with key @a name and unsigned @a value
  10418. */
  10419. void write_bson_unsigned(const string_t& name,
  10420. const std::uint64_t value)
  10421. {
  10422. if (value <= static_cast<std::uint64_t>((std::numeric_limits<std::int32_t>::max)()))
  10423. {
  10424. write_bson_entry_header(name, 0x10 /* int32 */);
  10425. write_number<std::int32_t, true>(static_cast<std::int32_t>(value));
  10426. }
  10427. else if (value <= static_cast<std::uint64_t>((std::numeric_limits<std::int64_t>::max)()))
  10428. {
  10429. write_bson_entry_header(name, 0x12 /* int64 */);
  10430. write_number<std::int64_t, true>(static_cast<std::int64_t>(value));
  10431. }
  10432. else
  10433. {
  10434. JSON_THROW(out_of_range::create(407, "integer number " + std::to_string(value) + " cannot be represented by BSON as it does not fit int64"));
  10435. }
  10436. }
  10437. /*!
  10438. @brief Writes a BSON element with key @a name and object @a value
  10439. */
  10440. void write_bson_object_entry(const string_t& name,
  10441. const typename BasicJsonType::object_t& value)
  10442. {
  10443. write_bson_entry_header(name, 0x03); // object
  10444. write_bson_object(value);
  10445. }
  10446. /*!
  10447. @return The size of the BSON-encoded array @a value
  10448. */
  10449. static std::size_t calc_bson_array_size(const typename BasicJsonType::array_t& value)
  10450. {
  10451. std::size_t embedded_document_size = 0ul;
  10452. std::size_t array_index = 0ul;
  10453. for (const auto& el : value)
  10454. {
  10455. embedded_document_size += calc_bson_element_size(std::to_string(array_index++), el);
  10456. }
  10457. return sizeof(std::int32_t) + embedded_document_size + 1ul;
  10458. }
  10459. /*!
  10460. @brief Writes a BSON element with key @a name and array @a value
  10461. */
  10462. void write_bson_array(const string_t& name,
  10463. const typename BasicJsonType::array_t& value)
  10464. {
  10465. write_bson_entry_header(name, 0x04); // array
  10466. write_number<std::int32_t, true>(static_cast<std::int32_t>(calc_bson_array_size(value)));
  10467. std::size_t array_index = 0ul;
  10468. for (const auto& el : value)
  10469. {
  10470. write_bson_element(std::to_string(array_index++), el);
  10471. }
  10472. oa->write_character(to_char_type(0x00));
  10473. }
  10474. /*!
  10475. @brief Calculates the size necessary to serialize the JSON value @a j with its @a name
  10476. @return The calculated size for the BSON document entry for @a j with the given @a name.
  10477. */
  10478. static std::size_t calc_bson_element_size(const string_t& name,
  10479. const BasicJsonType& j)
  10480. {
  10481. const auto header_size = calc_bson_entry_header_size(name);
  10482. switch (j.type())
  10483. {
  10484. case value_t::object:
  10485. return header_size + calc_bson_object_size(*j.m_value.object);
  10486. case value_t::array:
  10487. return header_size + calc_bson_array_size(*j.m_value.array);
  10488. case value_t::boolean:
  10489. return header_size + 1ul;
  10490. case value_t::number_float:
  10491. return header_size + 8ul;
  10492. case value_t::number_integer:
  10493. return header_size + calc_bson_integer_size(j.m_value.number_integer);
  10494. case value_t::number_unsigned:
  10495. return header_size + calc_bson_unsigned_size(j.m_value.number_unsigned);
  10496. case value_t::string:
  10497. return header_size + calc_bson_string_size(*j.m_value.string);
  10498. case value_t::null:
  10499. return header_size + 0ul;
  10500. // LCOV_EXCL_START
  10501. default:
  10502. assert(false);
  10503. return 0ul;
  10504. // LCOV_EXCL_STOP
  10505. }
  10506. }
  10507. /*!
  10508. @brief Serializes the JSON value @a j to BSON and associates it with the
  10509. key @a name.
  10510. @param name The name to associate with the JSON entity @a j within the
  10511. current BSON document
  10512. @return The size of the BSON entry
  10513. */
  10514. void write_bson_element(const string_t& name,
  10515. const BasicJsonType& j)
  10516. {
  10517. switch (j.type())
  10518. {
  10519. case value_t::object:
  10520. return write_bson_object_entry(name, *j.m_value.object);
  10521. case value_t::array:
  10522. return write_bson_array(name, *j.m_value.array);
  10523. case value_t::boolean:
  10524. return write_bson_boolean(name, j.m_value.boolean);
  10525. case value_t::number_float:
  10526. return write_bson_double(name, j.m_value.number_float);
  10527. case value_t::number_integer:
  10528. return write_bson_integer(name, j.m_value.number_integer);
  10529. case value_t::number_unsigned:
  10530. return write_bson_unsigned(name, j.m_value.number_unsigned);
  10531. case value_t::string:
  10532. return write_bson_string(name, *j.m_value.string);
  10533. case value_t::null:
  10534. return write_bson_null(name);
  10535. // LCOV_EXCL_START
  10536. default:
  10537. assert(false);
  10538. return;
  10539. // LCOV_EXCL_STOP
  10540. }
  10541. }
  10542. /*!
  10543. @brief Calculates the size of the BSON serialization of the given
  10544. JSON-object @a j.
  10545. @param[in] j JSON value to serialize
  10546. @pre j.type() == value_t::object
  10547. */
  10548. static std::size_t calc_bson_object_size(const typename BasicJsonType::object_t& value)
  10549. {
  10550. std::size_t document_size = std::accumulate(value.begin(), value.end(), 0ul,
  10551. [](size_t result, const typename BasicJsonType::object_t::value_type & el)
  10552. {
  10553. return result += calc_bson_element_size(el.first, el.second);
  10554. });
  10555. return sizeof(std::int32_t) + document_size + 1ul;
  10556. }
  10557. /*!
  10558. @param[in] j JSON value to serialize
  10559. @pre j.type() == value_t::object
  10560. */
  10561. void write_bson_object(const typename BasicJsonType::object_t& value)
  10562. {
  10563. write_number<std::int32_t, true>(static_cast<std::int32_t>(calc_bson_object_size(value)));
  10564. for (const auto& el : value)
  10565. {
  10566. write_bson_element(el.first, el.second);
  10567. }
  10568. oa->write_character(to_char_type(0x00));
  10569. }
  10570. //////////
  10571. // CBOR //
  10572. //////////
  10573. static constexpr CharType get_cbor_float_prefix(float /*unused*/)
  10574. {
  10575. return to_char_type(0xFA); // Single-Precision Float
  10576. }
  10577. static constexpr CharType get_cbor_float_prefix(double /*unused*/)
  10578. {
  10579. return to_char_type(0xFB); // Double-Precision Float
  10580. }
  10581. /////////////
  10582. // MsgPack //
  10583. /////////////
  10584. static constexpr CharType get_msgpack_float_prefix(float /*unused*/)
  10585. {
  10586. return to_char_type(0xCA); // float 32
  10587. }
  10588. static constexpr CharType get_msgpack_float_prefix(double /*unused*/)
  10589. {
  10590. return to_char_type(0xCB); // float 64
  10591. }
  10592. ////////////
  10593. // UBJSON //
  10594. ////////////
  10595. // UBJSON: write number (floating point)
  10596. template<typename NumberType, typename std::enable_if<
  10597. std::is_floating_point<NumberType>::value, int>::type = 0>
  10598. void write_number_with_ubjson_prefix(const NumberType n,
  10599. const bool add_prefix)
  10600. {
  10601. if (add_prefix)
  10602. {
  10603. oa->write_character(get_ubjson_float_prefix(n));
  10604. }
  10605. write_number(n);
  10606. }
  10607. // UBJSON: write number (unsigned integer)
  10608. template<typename NumberType, typename std::enable_if<
  10609. std::is_unsigned<NumberType>::value, int>::type = 0>
  10610. void write_number_with_ubjson_prefix(const NumberType n,
  10611. const bool add_prefix)
  10612. {
  10613. if (n <= static_cast<std::uint64_t>((std::numeric_limits<std::int8_t>::max)()))
  10614. {
  10615. if (add_prefix)
  10616. {
  10617. oa->write_character(to_char_type('i')); // int8
  10618. }
  10619. write_number(static_cast<std::uint8_t>(n));
  10620. }
  10621. else if (n <= (std::numeric_limits<std::uint8_t>::max)())
  10622. {
  10623. if (add_prefix)
  10624. {
  10625. oa->write_character(to_char_type('U')); // uint8
  10626. }
  10627. write_number(static_cast<std::uint8_t>(n));
  10628. }
  10629. else if (n <= static_cast<std::uint64_t>((std::numeric_limits<std::int16_t>::max)()))
  10630. {
  10631. if (add_prefix)
  10632. {
  10633. oa->write_character(to_char_type('I')); // int16
  10634. }
  10635. write_number(static_cast<std::int16_t>(n));
  10636. }
  10637. else if (n <= static_cast<std::uint64_t>((std::numeric_limits<std::int32_t>::max)()))
  10638. {
  10639. if (add_prefix)
  10640. {
  10641. oa->write_character(to_char_type('l')); // int32
  10642. }
  10643. write_number(static_cast<std::int32_t>(n));
  10644. }
  10645. else if (n <= static_cast<std::uint64_t>((std::numeric_limits<std::int64_t>::max)()))
  10646. {
  10647. if (add_prefix)
  10648. {
  10649. oa->write_character(to_char_type('L')); // int64
  10650. }
  10651. write_number(static_cast<std::int64_t>(n));
  10652. }
  10653. else
  10654. {
  10655. JSON_THROW(out_of_range::create(407, "integer number " + std::to_string(n) + " cannot be represented by UBJSON as it does not fit int64"));
  10656. }
  10657. }
  10658. // UBJSON: write number (signed integer)
  10659. template<typename NumberType, typename std::enable_if<
  10660. std::is_signed<NumberType>::value and
  10661. not std::is_floating_point<NumberType>::value, int>::type = 0>
  10662. void write_number_with_ubjson_prefix(const NumberType n,
  10663. const bool add_prefix)
  10664. {
  10665. if ((std::numeric_limits<std::int8_t>::min)() <= n and n <= (std::numeric_limits<std::int8_t>::max)())
  10666. {
  10667. if (add_prefix)
  10668. {
  10669. oa->write_character(to_char_type('i')); // int8
  10670. }
  10671. write_number(static_cast<std::int8_t>(n));
  10672. }
  10673. else if (static_cast<std::int64_t>((std::numeric_limits<std::uint8_t>::min)()) <= n and n <= static_cast<std::int64_t>((std::numeric_limits<std::uint8_t>::max)()))
  10674. {
  10675. if (add_prefix)
  10676. {
  10677. oa->write_character(to_char_type('U')); // uint8
  10678. }
  10679. write_number(static_cast<std::uint8_t>(n));
  10680. }
  10681. else if ((std::numeric_limits<std::int16_t>::min)() <= n and n <= (std::numeric_limits<std::int16_t>::max)())
  10682. {
  10683. if (add_prefix)
  10684. {
  10685. oa->write_character(to_char_type('I')); // int16
  10686. }
  10687. write_number(static_cast<std::int16_t>(n));
  10688. }
  10689. else if ((std::numeric_limits<std::int32_t>::min)() <= n and n <= (std::numeric_limits<std::int32_t>::max)())
  10690. {
  10691. if (add_prefix)
  10692. {
  10693. oa->write_character(to_char_type('l')); // int32
  10694. }
  10695. write_number(static_cast<std::int32_t>(n));
  10696. }
  10697. else if ((std::numeric_limits<std::int64_t>::min)() <= n and n <= (std::numeric_limits<std::int64_t>::max)())
  10698. {
  10699. if (add_prefix)
  10700. {
  10701. oa->write_character(to_char_type('L')); // int64
  10702. }
  10703. write_number(static_cast<std::int64_t>(n));
  10704. }
  10705. // LCOV_EXCL_START
  10706. else
  10707. {
  10708. JSON_THROW(out_of_range::create(407, "integer number " + std::to_string(n) + " cannot be represented by UBJSON as it does not fit int64"));
  10709. }
  10710. // LCOV_EXCL_STOP
  10711. }
  10712. /*!
  10713. @brief determine the type prefix of container values
  10714. @note This function does not need to be 100% accurate when it comes to
  10715. integer limits. In case a number exceeds the limits of int64_t,
  10716. this will be detected by a later call to function
  10717. write_number_with_ubjson_prefix. Therefore, we return 'L' for any
  10718. value that does not fit the previous limits.
  10719. */
  10720. CharType ubjson_prefix(const BasicJsonType& j) const noexcept
  10721. {
  10722. switch (j.type())
  10723. {
  10724. case value_t::null:
  10725. return 'Z';
  10726. case value_t::boolean:
  10727. return j.m_value.boolean ? 'T' : 'F';
  10728. case value_t::number_integer:
  10729. {
  10730. if ((std::numeric_limits<std::int8_t>::min)() <= j.m_value.number_integer and j.m_value.number_integer <= (std::numeric_limits<std::int8_t>::max)())
  10731. {
  10732. return 'i';
  10733. }
  10734. if ((std::numeric_limits<std::uint8_t>::min)() <= j.m_value.number_integer and j.m_value.number_integer <= (std::numeric_limits<std::uint8_t>::max)())
  10735. {
  10736. return 'U';
  10737. }
  10738. if ((std::numeric_limits<std::int16_t>::min)() <= j.m_value.number_integer and j.m_value.number_integer <= (std::numeric_limits<std::int16_t>::max)())
  10739. {
  10740. return 'I';
  10741. }
  10742. if ((std::numeric_limits<std::int32_t>::min)() <= j.m_value.number_integer and j.m_value.number_integer <= (std::numeric_limits<std::int32_t>::max)())
  10743. {
  10744. return 'l';
  10745. }
  10746. // no check and assume int64_t (see note above)
  10747. return 'L';
  10748. }
  10749. case value_t::number_unsigned:
  10750. {
  10751. if (j.m_value.number_unsigned <= static_cast<std::uint64_t>((std::numeric_limits<std::int8_t>::max)()))
  10752. {
  10753. return 'i';
  10754. }
  10755. if (j.m_value.number_unsigned <= static_cast<std::uint64_t>((std::numeric_limits<std::uint8_t>::max)()))
  10756. {
  10757. return 'U';
  10758. }
  10759. if (j.m_value.number_unsigned <= static_cast<std::uint64_t>((std::numeric_limits<std::int16_t>::max)()))
  10760. {
  10761. return 'I';
  10762. }
  10763. if (j.m_value.number_unsigned <= static_cast<std::uint64_t>((std::numeric_limits<std::int32_t>::max)()))
  10764. {
  10765. return 'l';
  10766. }
  10767. // no check and assume int64_t (see note above)
  10768. return 'L';
  10769. }
  10770. case value_t::number_float:
  10771. return get_ubjson_float_prefix(j.m_value.number_float);
  10772. case value_t::string:
  10773. return 'S';
  10774. case value_t::array:
  10775. return '[';
  10776. case value_t::object:
  10777. return '{';
  10778. default: // discarded values
  10779. return 'N';
  10780. }
  10781. }
  10782. static constexpr CharType get_ubjson_float_prefix(float /*unused*/)
  10783. {
  10784. return 'd'; // float 32
  10785. }
  10786. static constexpr CharType get_ubjson_float_prefix(double /*unused*/)
  10787. {
  10788. return 'D'; // float 64
  10789. }
  10790. ///////////////////////
  10791. // Utility functions //
  10792. ///////////////////////
  10793. /*
  10794. @brief write a number to output input
  10795. @param[in] n number of type @a NumberType
  10796. @tparam NumberType the type of the number
  10797. @tparam OutputIsLittleEndian Set to true if output data is
  10798. required to be little endian
  10799. @note This function needs to respect the system's endianess, because bytes
  10800. in CBOR, MessagePack, and UBJSON are stored in network order (big
  10801. endian) and therefore need reordering on little endian systems.
  10802. */
  10803. template<typename NumberType, bool OutputIsLittleEndian = false>
  10804. void write_number(const NumberType n)
  10805. {
  10806. // step 1: write number to array of length NumberType
  10807. std::array<CharType, sizeof(NumberType)> vec;
  10808. std::memcpy(vec.data(), &n, sizeof(NumberType));
  10809. // step 2: write array to output (with possible reordering)
  10810. if (is_little_endian != OutputIsLittleEndian)
  10811. {
  10812. // reverse byte order prior to conversion if necessary
  10813. std::reverse(vec.begin(), vec.end());
  10814. }
  10815. oa->write_characters(vec.data(), sizeof(NumberType));
  10816. }
  10817. public:
  10818. // The following to_char_type functions are implement the conversion
  10819. // between uint8_t and CharType. In case CharType is not unsigned,
  10820. // such a conversion is required to allow values greater than 128.
  10821. // See <https://github.com/nlohmann/json/issues/1286> for a discussion.
  10822. template < typename C = CharType,
  10823. enable_if_t < std::is_signed<C>::value and std::is_signed<char>::value > * = nullptr >
  10824. static constexpr CharType to_char_type(std::uint8_t x) noexcept
  10825. {
  10826. return *reinterpret_cast<char*>(&x);
  10827. }
  10828. template < typename C = CharType,
  10829. enable_if_t < std::is_signed<C>::value and std::is_unsigned<char>::value > * = nullptr >
  10830. static CharType to_char_type(std::uint8_t x) noexcept
  10831. {
  10832. static_assert(sizeof(std::uint8_t) == sizeof(CharType), "size of CharType must be equal to std::uint8_t");
  10833. static_assert(std::is_pod<CharType>::value, "CharType must be POD");
  10834. CharType result;
  10835. std::memcpy(&result, &x, sizeof(x));
  10836. return result;
  10837. }
  10838. template<typename C = CharType,
  10839. enable_if_t<std::is_unsigned<C>::value>* = nullptr>
  10840. static constexpr CharType to_char_type(std::uint8_t x) noexcept
  10841. {
  10842. return x;
  10843. }
  10844. template < typename InputCharType, typename C = CharType,
  10845. enable_if_t <
  10846. std::is_signed<C>::value and
  10847. std::is_signed<char>::value and
  10848. std::is_same<char, typename std::remove_cv<InputCharType>::type>::value
  10849. > * = nullptr >
  10850. static constexpr CharType to_char_type(InputCharType x) noexcept
  10851. {
  10852. return x;
  10853. }
  10854. private:
  10855. /// whether we can assume little endianess
  10856. const bool is_little_endian = binary_reader<BasicJsonType>::little_endianess();
  10857. /// the output
  10858. output_adapter_t<CharType> oa = nullptr;
  10859. };
  10860. } // namespace detail
  10861. } // namespace nlohmann
  10862. // #include <nlohmann/detail/output/output_adapters.hpp>
  10863. // #include <nlohmann/detail/output/serializer.hpp>
  10864. #include <algorithm> // reverse, remove, fill, find, none_of
  10865. #include <array> // array
  10866. #include <cassert> // assert
  10867. #include <ciso646> // and, or
  10868. #include <clocale> // localeconv, lconv
  10869. #include <cmath> // labs, isfinite, isnan, signbit
  10870. #include <cstddef> // size_t, ptrdiff_t
  10871. #include <cstdint> // uint8_t
  10872. #include <cstdio> // snprintf
  10873. #include <limits> // numeric_limits
  10874. #include <string> // string
  10875. #include <type_traits> // is_same
  10876. #include <utility> // move
  10877. // #include <nlohmann/detail/conversions/to_chars.hpp>
  10878. #include <array> // array
  10879. #include <cassert> // assert
  10880. #include <ciso646> // or, and, not
  10881. #include <cmath> // signbit, isfinite
  10882. #include <cstdint> // intN_t, uintN_t
  10883. #include <cstring> // memcpy, memmove
  10884. #include <limits> // numeric_limits
  10885. #include <type_traits> // conditional
  10886. // #include <nlohmann/detail/macro_scope.hpp>
  10887. namespace nlohmann
  10888. {
  10889. namespace detail
  10890. {
  10891. /*!
  10892. @brief implements the Grisu2 algorithm for binary to decimal floating-point
  10893. conversion.
  10894. This implementation is a slightly modified version of the reference
  10895. implementation which may be obtained from
  10896. http://florian.loitsch.com/publications (bench.tar.gz).
  10897. The code is distributed under the MIT license, Copyright (c) 2009 Florian Loitsch.
  10898. For a detailed description of the algorithm see:
  10899. [1] Loitsch, "Printing Floating-Point Numbers Quickly and Accurately with
  10900. Integers", Proceedings of the ACM SIGPLAN 2010 Conference on Programming
  10901. Language Design and Implementation, PLDI 2010
  10902. [2] Burger, Dybvig, "Printing Floating-Point Numbers Quickly and Accurately",
  10903. Proceedings of the ACM SIGPLAN 1996 Conference on Programming Language
  10904. Design and Implementation, PLDI 1996
  10905. */
  10906. namespace dtoa_impl
  10907. {
  10908. template <typename Target, typename Source>
  10909. Target reinterpret_bits(const Source source)
  10910. {
  10911. static_assert(sizeof(Target) == sizeof(Source), "size mismatch");
  10912. Target target;
  10913. std::memcpy(&target, &source, sizeof(Source));
  10914. return target;
  10915. }
  10916. struct diyfp // f * 2^e
  10917. {
  10918. static constexpr int kPrecision = 64; // = q
  10919. std::uint64_t f = 0;
  10920. int e = 0;
  10921. constexpr diyfp(std::uint64_t f_, int e_) noexcept : f(f_), e(e_) {}
  10922. /*!
  10923. @brief returns x - y
  10924. @pre x.e == y.e and x.f >= y.f
  10925. */
  10926. static diyfp sub(const diyfp& x, const diyfp& y) noexcept
  10927. {
  10928. assert(x.e == y.e);
  10929. assert(x.f >= y.f);
  10930. return {x.f - y.f, x.e};
  10931. }
  10932. /*!
  10933. @brief returns x * y
  10934. @note The result is rounded. (Only the upper q bits are returned.)
  10935. */
  10936. static diyfp mul(const diyfp& x, const diyfp& y) noexcept
  10937. {
  10938. static_assert(kPrecision == 64, "internal error");
  10939. // Computes:
  10940. // f = round((x.f * y.f) / 2^q)
  10941. // e = x.e + y.e + q
  10942. // Emulate the 64-bit * 64-bit multiplication:
  10943. //
  10944. // p = u * v
  10945. // = (u_lo + 2^32 u_hi) (v_lo + 2^32 v_hi)
  10946. // = (u_lo v_lo ) + 2^32 ((u_lo v_hi ) + (u_hi v_lo )) + 2^64 (u_hi v_hi )
  10947. // = (p0 ) + 2^32 ((p1 ) + (p2 )) + 2^64 (p3 )
  10948. // = (p0_lo + 2^32 p0_hi) + 2^32 ((p1_lo + 2^32 p1_hi) + (p2_lo + 2^32 p2_hi)) + 2^64 (p3 )
  10949. // = (p0_lo ) + 2^32 (p0_hi + p1_lo + p2_lo ) + 2^64 (p1_hi + p2_hi + p3)
  10950. // = (p0_lo ) + 2^32 (Q ) + 2^64 (H )
  10951. // = (p0_lo ) + 2^32 (Q_lo + 2^32 Q_hi ) + 2^64 (H )
  10952. //
  10953. // (Since Q might be larger than 2^32 - 1)
  10954. //
  10955. // = (p0_lo + 2^32 Q_lo) + 2^64 (Q_hi + H)
  10956. //
  10957. // (Q_hi + H does not overflow a 64-bit int)
  10958. //
  10959. // = p_lo + 2^64 p_hi
  10960. const std::uint64_t u_lo = x.f & 0xFFFFFFFFu;
  10961. const std::uint64_t u_hi = x.f >> 32u;
  10962. const std::uint64_t v_lo = y.f & 0xFFFFFFFFu;
  10963. const std::uint64_t v_hi = y.f >> 32u;
  10964. const std::uint64_t p0 = u_lo * v_lo;
  10965. const std::uint64_t p1 = u_lo * v_hi;
  10966. const std::uint64_t p2 = u_hi * v_lo;
  10967. const std::uint64_t p3 = u_hi * v_hi;
  10968. const std::uint64_t p0_hi = p0 >> 32u;
  10969. const std::uint64_t p1_lo = p1 & 0xFFFFFFFFu;
  10970. const std::uint64_t p1_hi = p1 >> 32u;
  10971. const std::uint64_t p2_lo = p2 & 0xFFFFFFFFu;
  10972. const std::uint64_t p2_hi = p2 >> 32u;
  10973. std::uint64_t Q = p0_hi + p1_lo + p2_lo;
  10974. // The full product might now be computed as
  10975. //
  10976. // p_hi = p3 + p2_hi + p1_hi + (Q >> 32)
  10977. // p_lo = p0_lo + (Q << 32)
  10978. //
  10979. // But in this particular case here, the full p_lo is not required.
  10980. // Effectively we only need to add the highest bit in p_lo to p_hi (and
  10981. // Q_hi + 1 does not overflow).
  10982. Q += std::uint64_t{1} << (64u - 32u - 1u); // round, ties up
  10983. const std::uint64_t h = p3 + p2_hi + p1_hi + (Q >> 32u);
  10984. return {h, x.e + y.e + 64};
  10985. }
  10986. /*!
  10987. @brief normalize x such that the significand is >= 2^(q-1)
  10988. @pre x.f != 0
  10989. */
  10990. static diyfp normalize(diyfp x) noexcept
  10991. {
  10992. assert(x.f != 0);
  10993. while ((x.f >> 63u) == 0)
  10994. {
  10995. x.f <<= 1u;
  10996. x.e--;
  10997. }
  10998. return x;
  10999. }
  11000. /*!
  11001. @brief normalize x such that the result has the exponent E
  11002. @pre e >= x.e and the upper e - x.e bits of x.f must be zero.
  11003. */
  11004. static diyfp normalize_to(const diyfp& x, const int target_exponent) noexcept
  11005. {
  11006. const int delta = x.e - target_exponent;
  11007. assert(delta >= 0);
  11008. assert(((x.f << delta) >> delta) == x.f);
  11009. return {x.f << delta, target_exponent};
  11010. }
  11011. };
  11012. struct boundaries
  11013. {
  11014. diyfp w;
  11015. diyfp minus;
  11016. diyfp plus;
  11017. };
  11018. /*!
  11019. Compute the (normalized) diyfp representing the input number 'value' and its
  11020. boundaries.
  11021. @pre value must be finite and positive
  11022. */
  11023. template <typename FloatType>
  11024. boundaries compute_boundaries(FloatType value)
  11025. {
  11026. assert(std::isfinite(value));
  11027. assert(value > 0);
  11028. // Convert the IEEE representation into a diyfp.
  11029. //
  11030. // If v is denormal:
  11031. // value = 0.F * 2^(1 - bias) = ( F) * 2^(1 - bias - (p-1))
  11032. // If v is normalized:
  11033. // value = 1.F * 2^(E - bias) = (2^(p-1) + F) * 2^(E - bias - (p-1))
  11034. static_assert(std::numeric_limits<FloatType>::is_iec559,
  11035. "internal error: dtoa_short requires an IEEE-754 floating-point implementation");
  11036. constexpr int kPrecision = std::numeric_limits<FloatType>::digits; // = p (includes the hidden bit)
  11037. constexpr int kBias = std::numeric_limits<FloatType>::max_exponent - 1 + (kPrecision - 1);
  11038. constexpr int kMinExp = 1 - kBias;
  11039. constexpr std::uint64_t kHiddenBit = std::uint64_t{1} << (kPrecision - 1); // = 2^(p-1)
  11040. using bits_type = typename std::conditional<kPrecision == 24, std::uint32_t, std::uint64_t >::type;
  11041. const std::uint64_t bits = reinterpret_bits<bits_type>(value);
  11042. const std::uint64_t E = bits >> (kPrecision - 1);
  11043. const std::uint64_t F = bits & (kHiddenBit - 1);
  11044. const bool is_denormal = E == 0;
  11045. const diyfp v = is_denormal
  11046. ? diyfp(F, kMinExp)
  11047. : diyfp(F + kHiddenBit, static_cast<int>(E) - kBias);
  11048. // Compute the boundaries m- and m+ of the floating-point value
  11049. // v = f * 2^e.
  11050. //
  11051. // Determine v- and v+, the floating-point predecessor and successor if v,
  11052. // respectively.
  11053. //
  11054. // v- = v - 2^e if f != 2^(p-1) or e == e_min (A)
  11055. // = v - 2^(e-1) if f == 2^(p-1) and e > e_min (B)
  11056. //
  11057. // v+ = v + 2^e
  11058. //
  11059. // Let m- = (v- + v) / 2 and m+ = (v + v+) / 2. All real numbers _strictly_
  11060. // between m- and m+ round to v, regardless of how the input rounding
  11061. // algorithm breaks ties.
  11062. //
  11063. // ---+-------------+-------------+-------------+-------------+--- (A)
  11064. // v- m- v m+ v+
  11065. //
  11066. // -----------------+------+------+-------------+-------------+--- (B)
  11067. // v- m- v m+ v+
  11068. const bool lower_boundary_is_closer = F == 0 and E > 1;
  11069. const diyfp m_plus = diyfp(2 * v.f + 1, v.e - 1);
  11070. const diyfp m_minus = lower_boundary_is_closer
  11071. ? diyfp(4 * v.f - 1, v.e - 2) // (B)
  11072. : diyfp(2 * v.f - 1, v.e - 1); // (A)
  11073. // Determine the normalized w+ = m+.
  11074. const diyfp w_plus = diyfp::normalize(m_plus);
  11075. // Determine w- = m- such that e_(w-) = e_(w+).
  11076. const diyfp w_minus = diyfp::normalize_to(m_minus, w_plus.e);
  11077. return {diyfp::normalize(v), w_minus, w_plus};
  11078. }
  11079. // Given normalized diyfp w, Grisu needs to find a (normalized) cached
  11080. // power-of-ten c, such that the exponent of the product c * w = f * 2^e lies
  11081. // within a certain range [alpha, gamma] (Definition 3.2 from [1])
  11082. //
  11083. // alpha <= e = e_c + e_w + q <= gamma
  11084. //
  11085. // or
  11086. //
  11087. // f_c * f_w * 2^alpha <= f_c 2^(e_c) * f_w 2^(e_w) * 2^q
  11088. // <= f_c * f_w * 2^gamma
  11089. //
  11090. // Since c and w are normalized, i.e. 2^(q-1) <= f < 2^q, this implies
  11091. //
  11092. // 2^(q-1) * 2^(q-1) * 2^alpha <= c * w * 2^q < 2^q * 2^q * 2^gamma
  11093. //
  11094. // or
  11095. //
  11096. // 2^(q - 2 + alpha) <= c * w < 2^(q + gamma)
  11097. //
  11098. // The choice of (alpha,gamma) determines the size of the table and the form of
  11099. // the digit generation procedure. Using (alpha,gamma)=(-60,-32) works out well
  11100. // in practice:
  11101. //
  11102. // The idea is to cut the number c * w = f * 2^e into two parts, which can be
  11103. // processed independently: An integral part p1, and a fractional part p2:
  11104. //
  11105. // f * 2^e = ( (f div 2^-e) * 2^-e + (f mod 2^-e) ) * 2^e
  11106. // = (f div 2^-e) + (f mod 2^-e) * 2^e
  11107. // = p1 + p2 * 2^e
  11108. //
  11109. // The conversion of p1 into decimal form requires a series of divisions and
  11110. // modulos by (a power of) 10. These operations are faster for 32-bit than for
  11111. // 64-bit integers, so p1 should ideally fit into a 32-bit integer. This can be
  11112. // achieved by choosing
  11113. //
  11114. // -e >= 32 or e <= -32 := gamma
  11115. //
  11116. // In order to convert the fractional part
  11117. //
  11118. // p2 * 2^e = p2 / 2^-e = d[-1] / 10^1 + d[-2] / 10^2 + ...
  11119. //
  11120. // into decimal form, the fraction is repeatedly multiplied by 10 and the digits
  11121. // d[-i] are extracted in order:
  11122. //
  11123. // (10 * p2) div 2^-e = d[-1]
  11124. // (10 * p2) mod 2^-e = d[-2] / 10^1 + ...
  11125. //
  11126. // The multiplication by 10 must not overflow. It is sufficient to choose
  11127. //
  11128. // 10 * p2 < 16 * p2 = 2^4 * p2 <= 2^64.
  11129. //
  11130. // Since p2 = f mod 2^-e < 2^-e,
  11131. //
  11132. // -e <= 60 or e >= -60 := alpha
  11133. constexpr int kAlpha = -60;
  11134. constexpr int kGamma = -32;
  11135. struct cached_power // c = f * 2^e ~= 10^k
  11136. {
  11137. std::uint64_t f;
  11138. int e;
  11139. int k;
  11140. };
  11141. /*!
  11142. For a normalized diyfp w = f * 2^e, this function returns a (normalized) cached
  11143. power-of-ten c = f_c * 2^e_c, such that the exponent of the product w * c
  11144. satisfies (Definition 3.2 from [1])
  11145. alpha <= e_c + e + q <= gamma.
  11146. */
  11147. inline cached_power get_cached_power_for_binary_exponent(int e)
  11148. {
  11149. // Now
  11150. //
  11151. // alpha <= e_c + e + q <= gamma (1)
  11152. // ==> f_c * 2^alpha <= c * 2^e * 2^q
  11153. //
  11154. // and since the c's are normalized, 2^(q-1) <= f_c,
  11155. //
  11156. // ==> 2^(q - 1 + alpha) <= c * 2^(e + q)
  11157. // ==> 2^(alpha - e - 1) <= c
  11158. //
  11159. // If c were an exakt power of ten, i.e. c = 10^k, one may determine k as
  11160. //
  11161. // k = ceil( log_10( 2^(alpha - e - 1) ) )
  11162. // = ceil( (alpha - e - 1) * log_10(2) )
  11163. //
  11164. // From the paper:
  11165. // "In theory the result of the procedure could be wrong since c is rounded,
  11166. // and the computation itself is approximated [...]. In practice, however,
  11167. // this simple function is sufficient."
  11168. //
  11169. // For IEEE double precision floating-point numbers converted into
  11170. // normalized diyfp's w = f * 2^e, with q = 64,
  11171. //
  11172. // e >= -1022 (min IEEE exponent)
  11173. // -52 (p - 1)
  11174. // -52 (p - 1, possibly normalize denormal IEEE numbers)
  11175. // -11 (normalize the diyfp)
  11176. // = -1137
  11177. //
  11178. // and
  11179. //
  11180. // e <= +1023 (max IEEE exponent)
  11181. // -52 (p - 1)
  11182. // -11 (normalize the diyfp)
  11183. // = 960
  11184. //
  11185. // This binary exponent range [-1137,960] results in a decimal exponent
  11186. // range [-307,324]. One does not need to store a cached power for each
  11187. // k in this range. For each such k it suffices to find a cached power
  11188. // such that the exponent of the product lies in [alpha,gamma].
  11189. // This implies that the difference of the decimal exponents of adjacent
  11190. // table entries must be less than or equal to
  11191. //
  11192. // floor( (gamma - alpha) * log_10(2) ) = 8.
  11193. //
  11194. // (A smaller distance gamma-alpha would require a larger table.)
  11195. // NB:
  11196. // Actually this function returns c, such that -60 <= e_c + e + 64 <= -34.
  11197. constexpr int kCachedPowersMinDecExp = -300;
  11198. constexpr int kCachedPowersDecStep = 8;
  11199. static constexpr std::array<cached_power, 79> kCachedPowers =
  11200. {
  11201. {
  11202. { 0xAB70FE17C79AC6CA, -1060, -300 },
  11203. { 0xFF77B1FCBEBCDC4F, -1034, -292 },
  11204. { 0xBE5691EF416BD60C, -1007, -284 },
  11205. { 0x8DD01FAD907FFC3C, -980, -276 },
  11206. { 0xD3515C2831559A83, -954, -268 },
  11207. { 0x9D71AC8FADA6C9B5, -927, -260 },
  11208. { 0xEA9C227723EE8BCB, -901, -252 },
  11209. { 0xAECC49914078536D, -874, -244 },
  11210. { 0x823C12795DB6CE57, -847, -236 },
  11211. { 0xC21094364DFB5637, -821, -228 },
  11212. { 0x9096EA6F3848984F, -794, -220 },
  11213. { 0xD77485CB25823AC7, -768, -212 },
  11214. { 0xA086CFCD97BF97F4, -741, -204 },
  11215. { 0xEF340A98172AACE5, -715, -196 },
  11216. { 0xB23867FB2A35B28E, -688, -188 },
  11217. { 0x84C8D4DFD2C63F3B, -661, -180 },
  11218. { 0xC5DD44271AD3CDBA, -635, -172 },
  11219. { 0x936B9FCEBB25C996, -608, -164 },
  11220. { 0xDBAC6C247D62A584, -582, -156 },
  11221. { 0xA3AB66580D5FDAF6, -555, -148 },
  11222. { 0xF3E2F893DEC3F126, -529, -140 },
  11223. { 0xB5B5ADA8AAFF80B8, -502, -132 },
  11224. { 0x87625F056C7C4A8B, -475, -124 },
  11225. { 0xC9BCFF6034C13053, -449, -116 },
  11226. { 0x964E858C91BA2655, -422, -108 },
  11227. { 0xDFF9772470297EBD, -396, -100 },
  11228. { 0xA6DFBD9FB8E5B88F, -369, -92 },
  11229. { 0xF8A95FCF88747D94, -343, -84 },
  11230. { 0xB94470938FA89BCF, -316, -76 },
  11231. { 0x8A08F0F8BF0F156B, -289, -68 },
  11232. { 0xCDB02555653131B6, -263, -60 },
  11233. { 0x993FE2C6D07B7FAC, -236, -52 },
  11234. { 0xE45C10C42A2B3B06, -210, -44 },
  11235. { 0xAA242499697392D3, -183, -36 },
  11236. { 0xFD87B5F28300CA0E, -157, -28 },
  11237. { 0xBCE5086492111AEB, -130, -20 },
  11238. { 0x8CBCCC096F5088CC, -103, -12 },
  11239. { 0xD1B71758E219652C, -77, -4 },
  11240. { 0x9C40000000000000, -50, 4 },
  11241. { 0xE8D4A51000000000, -24, 12 },
  11242. { 0xAD78EBC5AC620000, 3, 20 },
  11243. { 0x813F3978F8940984, 30, 28 },
  11244. { 0xC097CE7BC90715B3, 56, 36 },
  11245. { 0x8F7E32CE7BEA5C70, 83, 44 },
  11246. { 0xD5D238A4ABE98068, 109, 52 },
  11247. { 0x9F4F2726179A2245, 136, 60 },
  11248. { 0xED63A231D4C4FB27, 162, 68 },
  11249. { 0xB0DE65388CC8ADA8, 189, 76 },
  11250. { 0x83C7088E1AAB65DB, 216, 84 },
  11251. { 0xC45D1DF942711D9A, 242, 92 },
  11252. { 0x924D692CA61BE758, 269, 100 },
  11253. { 0xDA01EE641A708DEA, 295, 108 },
  11254. { 0xA26DA3999AEF774A, 322, 116 },
  11255. { 0xF209787BB47D6B85, 348, 124 },
  11256. { 0xB454E4A179DD1877, 375, 132 },
  11257. { 0x865B86925B9BC5C2, 402, 140 },
  11258. { 0xC83553C5C8965D3D, 428, 148 },
  11259. { 0x952AB45CFA97A0B3, 455, 156 },
  11260. { 0xDE469FBD99A05FE3, 481, 164 },
  11261. { 0xA59BC234DB398C25, 508, 172 },
  11262. { 0xF6C69A72A3989F5C, 534, 180 },
  11263. { 0xB7DCBF5354E9BECE, 561, 188 },
  11264. { 0x88FCF317F22241E2, 588, 196 },
  11265. { 0xCC20CE9BD35C78A5, 614, 204 },
  11266. { 0x98165AF37B2153DF, 641, 212 },
  11267. { 0xE2A0B5DC971F303A, 667, 220 },
  11268. { 0xA8D9D1535CE3B396, 694, 228 },
  11269. { 0xFB9B7CD9A4A7443C, 720, 236 },
  11270. { 0xBB764C4CA7A44410, 747, 244 },
  11271. { 0x8BAB8EEFB6409C1A, 774, 252 },
  11272. { 0xD01FEF10A657842C, 800, 260 },
  11273. { 0x9B10A4E5E9913129, 827, 268 },
  11274. { 0xE7109BFBA19C0C9D, 853, 276 },
  11275. { 0xAC2820D9623BF429, 880, 284 },
  11276. { 0x80444B5E7AA7CF85, 907, 292 },
  11277. { 0xBF21E44003ACDD2D, 933, 300 },
  11278. { 0x8E679C2F5E44FF8F, 960, 308 },
  11279. { 0xD433179D9C8CB841, 986, 316 },
  11280. { 0x9E19DB92B4E31BA9, 1013, 324 },
  11281. }
  11282. };
  11283. // This computation gives exactly the same results for k as
  11284. // k = ceil((kAlpha - e - 1) * 0.30102999566398114)
  11285. // for |e| <= 1500, but doesn't require floating-point operations.
  11286. // NB: log_10(2) ~= 78913 / 2^18
  11287. assert(e >= -1500);
  11288. assert(e <= 1500);
  11289. const int f = kAlpha - e - 1;
  11290. const int k = (f * 78913) / (1 << 18) + static_cast<int>(f > 0);
  11291. const int index = (-kCachedPowersMinDecExp + k + (kCachedPowersDecStep - 1)) / kCachedPowersDecStep;
  11292. assert(index >= 0);
  11293. assert(static_cast<std::size_t>(index) < kCachedPowers.size());
  11294. const cached_power cached = kCachedPowers[static_cast<std::size_t>(index)];
  11295. assert(kAlpha <= cached.e + e + 64);
  11296. assert(kGamma >= cached.e + e + 64);
  11297. return cached;
  11298. }
  11299. /*!
  11300. For n != 0, returns k, such that pow10 := 10^(k-1) <= n < 10^k.
  11301. For n == 0, returns 1 and sets pow10 := 1.
  11302. */
  11303. inline int find_largest_pow10(const std::uint32_t n, std::uint32_t& pow10)
  11304. {
  11305. // LCOV_EXCL_START
  11306. if (n >= 1000000000)
  11307. {
  11308. pow10 = 1000000000;
  11309. return 10;
  11310. }
  11311. // LCOV_EXCL_STOP
  11312. else if (n >= 100000000)
  11313. {
  11314. pow10 = 100000000;
  11315. return 9;
  11316. }
  11317. else if (n >= 10000000)
  11318. {
  11319. pow10 = 10000000;
  11320. return 8;
  11321. }
  11322. else if (n >= 1000000)
  11323. {
  11324. pow10 = 1000000;
  11325. return 7;
  11326. }
  11327. else if (n >= 100000)
  11328. {
  11329. pow10 = 100000;
  11330. return 6;
  11331. }
  11332. else if (n >= 10000)
  11333. {
  11334. pow10 = 10000;
  11335. return 5;
  11336. }
  11337. else if (n >= 1000)
  11338. {
  11339. pow10 = 1000;
  11340. return 4;
  11341. }
  11342. else if (n >= 100)
  11343. {
  11344. pow10 = 100;
  11345. return 3;
  11346. }
  11347. else if (n >= 10)
  11348. {
  11349. pow10 = 10;
  11350. return 2;
  11351. }
  11352. else
  11353. {
  11354. pow10 = 1;
  11355. return 1;
  11356. }
  11357. }
  11358. inline void grisu2_round(char* buf, int len, std::uint64_t dist, std::uint64_t delta,
  11359. std::uint64_t rest, std::uint64_t ten_k)
  11360. {
  11361. assert(len >= 1);
  11362. assert(dist <= delta);
  11363. assert(rest <= delta);
  11364. assert(ten_k > 0);
  11365. // <--------------------------- delta ---->
  11366. // <---- dist --------->
  11367. // --------------[------------------+-------------------]--------------
  11368. // M- w M+
  11369. //
  11370. // ten_k
  11371. // <------>
  11372. // <---- rest ---->
  11373. // --------------[------------------+----+--------------]--------------
  11374. // w V
  11375. // = buf * 10^k
  11376. //
  11377. // ten_k represents a unit-in-the-last-place in the decimal representation
  11378. // stored in buf.
  11379. // Decrement buf by ten_k while this takes buf closer to w.
  11380. // The tests are written in this order to avoid overflow in unsigned
  11381. // integer arithmetic.
  11382. while (rest < dist
  11383. and delta - rest >= ten_k
  11384. and (rest + ten_k < dist or dist - rest > rest + ten_k - dist))
  11385. {
  11386. assert(buf[len - 1] != '0');
  11387. buf[len - 1]--;
  11388. rest += ten_k;
  11389. }
  11390. }
  11391. /*!
  11392. Generates V = buffer * 10^decimal_exponent, such that M- <= V <= M+.
  11393. M- and M+ must be normalized and share the same exponent -60 <= e <= -32.
  11394. */
  11395. inline void grisu2_digit_gen(char* buffer, int& length, int& decimal_exponent,
  11396. diyfp M_minus, diyfp w, diyfp M_plus)
  11397. {
  11398. static_assert(kAlpha >= -60, "internal error");
  11399. static_assert(kGamma <= -32, "internal error");
  11400. // Generates the digits (and the exponent) of a decimal floating-point
  11401. // number V = buffer * 10^decimal_exponent in the range [M-, M+]. The diyfp's
  11402. // w, M- and M+ share the same exponent e, which satisfies alpha <= e <= gamma.
  11403. //
  11404. // <--------------------------- delta ---->
  11405. // <---- dist --------->
  11406. // --------------[------------------+-------------------]--------------
  11407. // M- w M+
  11408. //
  11409. // Grisu2 generates the digits of M+ from left to right and stops as soon as
  11410. // V is in [M-,M+].
  11411. assert(M_plus.e >= kAlpha);
  11412. assert(M_plus.e <= kGamma);
  11413. std::uint64_t delta = diyfp::sub(M_plus, M_minus).f; // (significand of (M+ - M-), implicit exponent is e)
  11414. std::uint64_t dist = diyfp::sub(M_plus, w ).f; // (significand of (M+ - w ), implicit exponent is e)
  11415. // Split M+ = f * 2^e into two parts p1 and p2 (note: e < 0):
  11416. //
  11417. // M+ = f * 2^e
  11418. // = ((f div 2^-e) * 2^-e + (f mod 2^-e)) * 2^e
  11419. // = ((p1 ) * 2^-e + (p2 )) * 2^e
  11420. // = p1 + p2 * 2^e
  11421. const diyfp one(std::uint64_t{1} << -M_plus.e, M_plus.e);
  11422. 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.)
  11423. std::uint64_t p2 = M_plus.f & (one.f - 1); // p2 = f mod 2^-e
  11424. // 1)
  11425. //
  11426. // Generate the digits of the integral part p1 = d[n-1]...d[1]d[0]
  11427. assert(p1 > 0);
  11428. std::uint32_t pow10;
  11429. const int k = find_largest_pow10(p1, pow10);
  11430. // 10^(k-1) <= p1 < 10^k, pow10 = 10^(k-1)
  11431. //
  11432. // p1 = (p1 div 10^(k-1)) * 10^(k-1) + (p1 mod 10^(k-1))
  11433. // = (d[k-1] ) * 10^(k-1) + (p1 mod 10^(k-1))
  11434. //
  11435. // M+ = p1 + p2 * 2^e
  11436. // = d[k-1] * 10^(k-1) + (p1 mod 10^(k-1)) + p2 * 2^e
  11437. // = d[k-1] * 10^(k-1) + ((p1 mod 10^(k-1)) * 2^-e + p2) * 2^e
  11438. // = d[k-1] * 10^(k-1) + ( rest) * 2^e
  11439. //
  11440. // Now generate the digits d[n] of p1 from left to right (n = k-1,...,0)
  11441. //
  11442. // p1 = d[k-1]...d[n] * 10^n + d[n-1]...d[0]
  11443. //
  11444. // but stop as soon as
  11445. //
  11446. // rest * 2^e = (d[n-1]...d[0] * 2^-e + p2) * 2^e <= delta * 2^e
  11447. int n = k;
  11448. while (n > 0)
  11449. {
  11450. // Invariants:
  11451. // M+ = buffer * 10^n + (p1 + p2 * 2^e) (buffer = 0 for n = k)
  11452. // pow10 = 10^(n-1) <= p1 < 10^n
  11453. //
  11454. const std::uint32_t d = p1 / pow10; // d = p1 div 10^(n-1)
  11455. const std::uint32_t r = p1 % pow10; // r = p1 mod 10^(n-1)
  11456. //
  11457. // M+ = buffer * 10^n + (d * 10^(n-1) + r) + p2 * 2^e
  11458. // = (buffer * 10 + d) * 10^(n-1) + (r + p2 * 2^e)
  11459. //
  11460. assert(d <= 9);
  11461. buffer[length++] = static_cast<char>('0' + d); // buffer := buffer * 10 + d
  11462. //
  11463. // M+ = buffer * 10^(n-1) + (r + p2 * 2^e)
  11464. //
  11465. p1 = r;
  11466. n--;
  11467. //
  11468. // M+ = buffer * 10^n + (p1 + p2 * 2^e)
  11469. // pow10 = 10^n
  11470. //
  11471. // Now check if enough digits have been generated.
  11472. // Compute
  11473. //
  11474. // p1 + p2 * 2^e = (p1 * 2^-e + p2) * 2^e = rest * 2^e
  11475. //
  11476. // Note:
  11477. // Since rest and delta share the same exponent e, it suffices to
  11478. // compare the significands.
  11479. const std::uint64_t rest = (std::uint64_t{p1} << -one.e) + p2;
  11480. if (rest <= delta)
  11481. {
  11482. // V = buffer * 10^n, with M- <= V <= M+.
  11483. decimal_exponent += n;
  11484. // We may now just stop. But instead look if the buffer could be
  11485. // decremented to bring V closer to w.
  11486. //
  11487. // pow10 = 10^n is now 1 ulp in the decimal representation V.
  11488. // The rounding procedure works with diyfp's with an implicit
  11489. // exponent of e.
  11490. //
  11491. // 10^n = (10^n * 2^-e) * 2^e = ulp * 2^e
  11492. //
  11493. const std::uint64_t ten_n = std::uint64_t{pow10} << -one.e;
  11494. grisu2_round(buffer, length, dist, delta, rest, ten_n);
  11495. return;
  11496. }
  11497. pow10 /= 10;
  11498. //
  11499. // pow10 = 10^(n-1) <= p1 < 10^n
  11500. // Invariants restored.
  11501. }
  11502. // 2)
  11503. //
  11504. // The digits of the integral part have been generated:
  11505. //
  11506. // M+ = d[k-1]...d[1]d[0] + p2 * 2^e
  11507. // = buffer + p2 * 2^e
  11508. //
  11509. // Now generate the digits of the fractional part p2 * 2^e.
  11510. //
  11511. // Note:
  11512. // No decimal point is generated: the exponent is adjusted instead.
  11513. //
  11514. // p2 actually represents the fraction
  11515. //
  11516. // p2 * 2^e
  11517. // = p2 / 2^-e
  11518. // = d[-1] / 10^1 + d[-2] / 10^2 + ...
  11519. //
  11520. // Now generate the digits d[-m] of p1 from left to right (m = 1,2,...)
  11521. //
  11522. // p2 * 2^e = d[-1]d[-2]...d[-m] * 10^-m
  11523. // + 10^-m * (d[-m-1] / 10^1 + d[-m-2] / 10^2 + ...)
  11524. //
  11525. // using
  11526. //
  11527. // 10^m * p2 = ((10^m * p2) div 2^-e) * 2^-e + ((10^m * p2) mod 2^-e)
  11528. // = ( d) * 2^-e + ( r)
  11529. //
  11530. // or
  11531. // 10^m * p2 * 2^e = d + r * 2^e
  11532. //
  11533. // i.e.
  11534. //
  11535. // M+ = buffer + p2 * 2^e
  11536. // = buffer + 10^-m * (d + r * 2^e)
  11537. // = (buffer * 10^m + d) * 10^-m + 10^-m * r * 2^e
  11538. //
  11539. // and stop as soon as 10^-m * r * 2^e <= delta * 2^e
  11540. assert(p2 > delta);
  11541. int m = 0;
  11542. for (;;)
  11543. {
  11544. // Invariant:
  11545. // M+ = buffer * 10^-m + 10^-m * (d[-m-1] / 10 + d[-m-2] / 10^2 + ...) * 2^e
  11546. // = buffer * 10^-m + 10^-m * (p2 ) * 2^e
  11547. // = buffer * 10^-m + 10^-m * (1/10 * (10 * p2) ) * 2^e
  11548. // = buffer * 10^-m + 10^-m * (1/10 * ((10*p2 div 2^-e) * 2^-e + (10*p2 mod 2^-e)) * 2^e
  11549. //
  11550. assert(p2 <= (std::numeric_limits<std::uint64_t>::max)() / 10);
  11551. p2 *= 10;
  11552. const std::uint64_t d = p2 >> -one.e; // d = (10 * p2) div 2^-e
  11553. const std::uint64_t r = p2 & (one.f - 1); // r = (10 * p2) mod 2^-e
  11554. //
  11555. // M+ = buffer * 10^-m + 10^-m * (1/10 * (d * 2^-e + r) * 2^e
  11556. // = buffer * 10^-m + 10^-m * (1/10 * (d + r * 2^e))
  11557. // = (buffer * 10 + d) * 10^(-m-1) + 10^(-m-1) * r * 2^e
  11558. //
  11559. assert(d <= 9);
  11560. buffer[length++] = static_cast<char>('0' + d); // buffer := buffer * 10 + d
  11561. //
  11562. // M+ = buffer * 10^(-m-1) + 10^(-m-1) * r * 2^e
  11563. //
  11564. p2 = r;
  11565. m++;
  11566. //
  11567. // M+ = buffer * 10^-m + 10^-m * p2 * 2^e
  11568. // Invariant restored.
  11569. // Check if enough digits have been generated.
  11570. //
  11571. // 10^-m * p2 * 2^e <= delta * 2^e
  11572. // p2 * 2^e <= 10^m * delta * 2^e
  11573. // p2 <= 10^m * delta
  11574. delta *= 10;
  11575. dist *= 10;
  11576. if (p2 <= delta)
  11577. {
  11578. break;
  11579. }
  11580. }
  11581. // V = buffer * 10^-m, with M- <= V <= M+.
  11582. decimal_exponent -= m;
  11583. // 1 ulp in the decimal representation is now 10^-m.
  11584. // Since delta and dist are now scaled by 10^m, we need to do the
  11585. // same with ulp in order to keep the units in sync.
  11586. //
  11587. // 10^m * 10^-m = 1 = 2^-e * 2^e = ten_m * 2^e
  11588. //
  11589. const std::uint64_t ten_m = one.f;
  11590. grisu2_round(buffer, length, dist, delta, p2, ten_m);
  11591. // By construction this algorithm generates the shortest possible decimal
  11592. // number (Loitsch, Theorem 6.2) which rounds back to w.
  11593. // For an input number of precision p, at least
  11594. //
  11595. // N = 1 + ceil(p * log_10(2))
  11596. //
  11597. // decimal digits are sufficient to identify all binary floating-point
  11598. // numbers (Matula, "In-and-Out conversions").
  11599. // This implies that the algorithm does not produce more than N decimal
  11600. // digits.
  11601. //
  11602. // N = 17 for p = 53 (IEEE double precision)
  11603. // N = 9 for p = 24 (IEEE single precision)
  11604. }
  11605. /*!
  11606. v = buf * 10^decimal_exponent
  11607. len is the length of the buffer (number of decimal digits)
  11608. The buffer must be large enough, i.e. >= max_digits10.
  11609. */
  11610. JSON_HEDLEY_NON_NULL(1)
  11611. inline void grisu2(char* buf, int& len, int& decimal_exponent,
  11612. diyfp m_minus, diyfp v, diyfp m_plus)
  11613. {
  11614. assert(m_plus.e == m_minus.e);
  11615. assert(m_plus.e == v.e);
  11616. // --------(-----------------------+-----------------------)-------- (A)
  11617. // m- v m+
  11618. //
  11619. // --------------------(-----------+-----------------------)-------- (B)
  11620. // m- v m+
  11621. //
  11622. // First scale v (and m- and m+) such that the exponent is in the range
  11623. // [alpha, gamma].
  11624. const cached_power cached = get_cached_power_for_binary_exponent(m_plus.e);
  11625. const diyfp c_minus_k(cached.f, cached.e); // = c ~= 10^-k
  11626. // The exponent of the products is = v.e + c_minus_k.e + q and is in the range [alpha,gamma]
  11627. const diyfp w = diyfp::mul(v, c_minus_k);
  11628. const diyfp w_minus = diyfp::mul(m_minus, c_minus_k);
  11629. const diyfp w_plus = diyfp::mul(m_plus, c_minus_k);
  11630. // ----(---+---)---------------(---+---)---------------(---+---)----
  11631. // w- w w+
  11632. // = c*m- = c*v = c*m+
  11633. //
  11634. // diyfp::mul rounds its result and c_minus_k is approximated too. w, w- and
  11635. // w+ are now off by a small amount.
  11636. // In fact:
  11637. //
  11638. // w - v * 10^k < 1 ulp
  11639. //
  11640. // To account for this inaccuracy, add resp. subtract 1 ulp.
  11641. //
  11642. // --------+---[---------------(---+---)---------------]---+--------
  11643. // w- M- w M+ w+
  11644. //
  11645. // Now any number in [M-, M+] (bounds included) will round to w when input,
  11646. // regardless of how the input rounding algorithm breaks ties.
  11647. //
  11648. // And digit_gen generates the shortest possible such number in [M-, M+].
  11649. // Note that this does not mean that Grisu2 always generates the shortest
  11650. // possible number in the interval (m-, m+).
  11651. const diyfp M_minus(w_minus.f + 1, w_minus.e);
  11652. const diyfp M_plus (w_plus.f - 1, w_plus.e );
  11653. decimal_exponent = -cached.k; // = -(-k) = k
  11654. grisu2_digit_gen(buf, len, decimal_exponent, M_minus, w, M_plus);
  11655. }
  11656. /*!
  11657. v = buf * 10^decimal_exponent
  11658. len is the length of the buffer (number of decimal digits)
  11659. The buffer must be large enough, i.e. >= max_digits10.
  11660. */
  11661. template <typename FloatType>
  11662. JSON_HEDLEY_NON_NULL(1)
  11663. void grisu2(char* buf, int& len, int& decimal_exponent, FloatType value)
  11664. {
  11665. static_assert(diyfp::kPrecision >= std::numeric_limits<FloatType>::digits + 3,
  11666. "internal error: not enough precision");
  11667. assert(std::isfinite(value));
  11668. assert(value > 0);
  11669. // If the neighbors (and boundaries) of 'value' are always computed for double-precision
  11670. // numbers, all float's can be recovered using strtod (and strtof). However, the resulting
  11671. // decimal representations are not exactly "short".
  11672. //
  11673. // The documentation for 'std::to_chars' (https://en.cppreference.com/w/cpp/utility/to_chars)
  11674. // says "value is converted to a string as if by std::sprintf in the default ("C") locale"
  11675. // and since sprintf promotes float's to double's, I think this is exactly what 'std::to_chars'
  11676. // does.
  11677. // On the other hand, the documentation for 'std::to_chars' requires that "parsing the
  11678. // representation using the corresponding std::from_chars function recovers value exactly". That
  11679. // indicates that single precision floating-point numbers should be recovered using
  11680. // 'std::strtof'.
  11681. //
  11682. // NB: If the neighbors are computed for single-precision numbers, there is a single float
  11683. // (7.0385307e-26f) which can't be recovered using strtod. The resulting double precision
  11684. // value is off by 1 ulp.
  11685. #if 0
  11686. const boundaries w = compute_boundaries(static_cast<double>(value));
  11687. #else
  11688. const boundaries w = compute_boundaries(value);
  11689. #endif
  11690. grisu2(buf, len, decimal_exponent, w.minus, w.w, w.plus);
  11691. }
  11692. /*!
  11693. @brief appends a decimal representation of e to buf
  11694. @return a pointer to the element following the exponent.
  11695. @pre -1000 < e < 1000
  11696. */
  11697. JSON_HEDLEY_NON_NULL(1)
  11698. JSON_HEDLEY_RETURNS_NON_NULL
  11699. inline char* append_exponent(char* buf, int e)
  11700. {
  11701. assert(e > -1000);
  11702. assert(e < 1000);
  11703. if (e < 0)
  11704. {
  11705. e = -e;
  11706. *buf++ = '-';
  11707. }
  11708. else
  11709. {
  11710. *buf++ = '+';
  11711. }
  11712. auto k = static_cast<std::uint32_t>(e);
  11713. if (k < 10)
  11714. {
  11715. // Always print at least two digits in the exponent.
  11716. // This is for compatibility with printf("%g").
  11717. *buf++ = '0';
  11718. *buf++ = static_cast<char>('0' + k);
  11719. }
  11720. else if (k < 100)
  11721. {
  11722. *buf++ = static_cast<char>('0' + k / 10);
  11723. k %= 10;
  11724. *buf++ = static_cast<char>('0' + k);
  11725. }
  11726. else
  11727. {
  11728. *buf++ = static_cast<char>('0' + k / 100);
  11729. k %= 100;
  11730. *buf++ = static_cast<char>('0' + k / 10);
  11731. k %= 10;
  11732. *buf++ = static_cast<char>('0' + k);
  11733. }
  11734. return buf;
  11735. }
  11736. /*!
  11737. @brief prettify v = buf * 10^decimal_exponent
  11738. If v is in the range [10^min_exp, 10^max_exp) it will be printed in fixed-point
  11739. notation. Otherwise it will be printed in exponential notation.
  11740. @pre min_exp < 0
  11741. @pre max_exp > 0
  11742. */
  11743. JSON_HEDLEY_NON_NULL(1)
  11744. JSON_HEDLEY_RETURNS_NON_NULL
  11745. inline char* format_buffer(char* buf, int len, int decimal_exponent,
  11746. int min_exp, int max_exp)
  11747. {
  11748. assert(min_exp < 0);
  11749. assert(max_exp > 0);
  11750. const int k = len;
  11751. const int n = len + decimal_exponent;
  11752. // v = buf * 10^(n-k)
  11753. // k is the length of the buffer (number of decimal digits)
  11754. // n is the position of the decimal point relative to the start of the buffer.
  11755. if (k <= n and n <= max_exp)
  11756. {
  11757. // digits[000]
  11758. // len <= max_exp + 2
  11759. std::memset(buf + k, '0', static_cast<size_t>(n - k));
  11760. // Make it look like a floating-point number (#362, #378)
  11761. buf[n + 0] = '.';
  11762. buf[n + 1] = '0';
  11763. return buf + (n + 2);
  11764. }
  11765. if (0 < n and n <= max_exp)
  11766. {
  11767. // dig.its
  11768. // len <= max_digits10 + 1
  11769. assert(k > n);
  11770. std::memmove(buf + (n + 1), buf + n, static_cast<size_t>(k - n));
  11771. buf[n] = '.';
  11772. return buf + (k + 1);
  11773. }
  11774. if (min_exp < n and n <= 0)
  11775. {
  11776. // 0.[000]digits
  11777. // len <= 2 + (-min_exp - 1) + max_digits10
  11778. std::memmove(buf + (2 + -n), buf, static_cast<size_t>(k));
  11779. buf[0] = '0';
  11780. buf[1] = '.';
  11781. std::memset(buf + 2, '0', static_cast<size_t>(-n));
  11782. return buf + (2 + (-n) + k);
  11783. }
  11784. if (k == 1)
  11785. {
  11786. // dE+123
  11787. // len <= 1 + 5
  11788. buf += 1;
  11789. }
  11790. else
  11791. {
  11792. // d.igitsE+123
  11793. // len <= max_digits10 + 1 + 5
  11794. std::memmove(buf + 2, buf + 1, static_cast<size_t>(k - 1));
  11795. buf[1] = '.';
  11796. buf += 1 + k;
  11797. }
  11798. *buf++ = 'e';
  11799. return append_exponent(buf, n - 1);
  11800. }
  11801. } // namespace dtoa_impl
  11802. /*!
  11803. @brief generates a decimal representation of the floating-point number value in [first, last).
  11804. The format of the resulting decimal representation is similar to printf's %g
  11805. format. Returns an iterator pointing past-the-end of the decimal representation.
  11806. @note The input number must be finite, i.e. NaN's and Inf's are not supported.
  11807. @note The buffer must be large enough.
  11808. @note The result is NOT null-terminated.
  11809. */
  11810. template <typename FloatType>
  11811. JSON_HEDLEY_NON_NULL(1, 2)
  11812. JSON_HEDLEY_RETURNS_NON_NULL
  11813. char* to_chars(char* first, const char* last, FloatType value)
  11814. {
  11815. static_cast<void>(last); // maybe unused - fix warning
  11816. assert(std::isfinite(value));
  11817. // Use signbit(value) instead of (value < 0) since signbit works for -0.
  11818. if (std::signbit(value))
  11819. {
  11820. value = -value;
  11821. *first++ = '-';
  11822. }
  11823. if (value == 0) // +-0
  11824. {
  11825. *first++ = '0';
  11826. // Make it look like a floating-point number (#362, #378)
  11827. *first++ = '.';
  11828. *first++ = '0';
  11829. return first;
  11830. }
  11831. assert(last - first >= std::numeric_limits<FloatType>::max_digits10);
  11832. // Compute v = buffer * 10^decimal_exponent.
  11833. // The decimal digits are stored in the buffer, which needs to be interpreted
  11834. // as an unsigned decimal integer.
  11835. // len is the length of the buffer, i.e. the number of decimal digits.
  11836. int len = 0;
  11837. int decimal_exponent = 0;
  11838. dtoa_impl::grisu2(first, len, decimal_exponent, value);
  11839. assert(len <= std::numeric_limits<FloatType>::max_digits10);
  11840. // Format the buffer like printf("%.*g", prec, value)
  11841. constexpr int kMinExp = -4;
  11842. // Use digits10 here to increase compatibility with version 2.
  11843. constexpr int kMaxExp = std::numeric_limits<FloatType>::digits10;
  11844. assert(last - first >= kMaxExp + 2);
  11845. assert(last - first >= 2 + (-kMinExp - 1) + std::numeric_limits<FloatType>::max_digits10);
  11846. assert(last - first >= std::numeric_limits<FloatType>::max_digits10 + 6);
  11847. return dtoa_impl::format_buffer(first, len, decimal_exponent, kMinExp, kMaxExp);
  11848. }
  11849. } // namespace detail
  11850. } // namespace nlohmann
  11851. // #include <nlohmann/detail/exceptions.hpp>
  11852. // #include <nlohmann/detail/macro_scope.hpp>
  11853. // #include <nlohmann/detail/meta/cpp_future.hpp>
  11854. // #include <nlohmann/detail/output/binary_writer.hpp>
  11855. // #include <nlohmann/detail/output/output_adapters.hpp>
  11856. // #include <nlohmann/detail/value_t.hpp>
  11857. namespace nlohmann
  11858. {
  11859. namespace detail
  11860. {
  11861. ///////////////////
  11862. // serialization //
  11863. ///////////////////
  11864. /// how to treat decoding errors
  11865. enum class error_handler_t
  11866. {
  11867. strict, ///< throw a type_error exception in case of invalid UTF-8
  11868. replace, ///< replace invalid UTF-8 sequences with U+FFFD
  11869. ignore ///< ignore invalid UTF-8 sequences
  11870. };
  11871. template<typename BasicJsonType>
  11872. class serializer
  11873. {
  11874. using string_t = typename BasicJsonType::string_t;
  11875. using number_float_t = typename BasicJsonType::number_float_t;
  11876. using number_integer_t = typename BasicJsonType::number_integer_t;
  11877. using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
  11878. static constexpr std::uint8_t UTF8_ACCEPT = 0;
  11879. static constexpr std::uint8_t UTF8_REJECT = 1;
  11880. public:
  11881. /*!
  11882. @param[in] s output stream to serialize to
  11883. @param[in] ichar indentation character to use
  11884. @param[in] error_handler_ how to react on decoding errors
  11885. */
  11886. serializer(output_adapter_t<char> s, const char ichar,
  11887. error_handler_t error_handler_ = error_handler_t::strict)
  11888. : o(std::move(s))
  11889. , loc(std::localeconv())
  11890. , thousands_sep(loc->thousands_sep == nullptr ? '\0' : * (loc->thousands_sep))
  11891. , decimal_point(loc->decimal_point == nullptr ? '\0' : * (loc->decimal_point))
  11892. , indent_char(ichar)
  11893. , indent_string(512, indent_char)
  11894. , error_handler(error_handler_)
  11895. {}
  11896. // delete because of pointer members
  11897. serializer(const serializer&) = delete;
  11898. serializer& operator=(const serializer&) = delete;
  11899. serializer(serializer&&) = delete;
  11900. serializer& operator=(serializer&&) = delete;
  11901. ~serializer() = default;
  11902. /*!
  11903. @brief internal implementation of the serialization function
  11904. This function is called by the public member function dump and organizes
  11905. the serialization internally. The indentation level is propagated as
  11906. additional parameter. In case of arrays and objects, the function is
  11907. called recursively.
  11908. - strings and object keys are escaped using `escape_string()`
  11909. - integer numbers are converted implicitly via `operator<<`
  11910. - floating-point numbers are converted to a string using `"%g"` format
  11911. @param[in] val value to serialize
  11912. @param[in] pretty_print whether the output shall be pretty-printed
  11913. @param[in] indent_step the indent level
  11914. @param[in] current_indent the current indent level (only used internally)
  11915. */
  11916. void dump(const BasicJsonType& val, const bool pretty_print,
  11917. const bool ensure_ascii,
  11918. const unsigned int indent_step,
  11919. const unsigned int current_indent = 0)
  11920. {
  11921. switch (val.m_type)
  11922. {
  11923. case value_t::object:
  11924. {
  11925. if (val.m_value.object->empty())
  11926. {
  11927. o->write_characters("{}", 2);
  11928. return;
  11929. }
  11930. if (pretty_print)
  11931. {
  11932. o->write_characters("{\n", 2);
  11933. // variable to hold indentation for recursive calls
  11934. const auto new_indent = current_indent + indent_step;
  11935. if (JSON_HEDLEY_UNLIKELY(indent_string.size() < new_indent))
  11936. {
  11937. indent_string.resize(indent_string.size() * 2, ' ');
  11938. }
  11939. // first n-1 elements
  11940. auto i = val.m_value.object->cbegin();
  11941. for (std::size_t cnt = 0; cnt < val.m_value.object->size() - 1; ++cnt, ++i)
  11942. {
  11943. o->write_characters(indent_string.c_str(), new_indent);
  11944. o->write_character('\"');
  11945. dump_escaped(i->first, ensure_ascii);
  11946. o->write_characters("\": ", 3);
  11947. dump(i->second, true, ensure_ascii, indent_step, new_indent);
  11948. o->write_characters(",\n", 2);
  11949. }
  11950. // last element
  11951. assert(i != val.m_value.object->cend());
  11952. assert(std::next(i) == val.m_value.object->cend());
  11953. o->write_characters(indent_string.c_str(), new_indent);
  11954. o->write_character('\"');
  11955. dump_escaped(i->first, ensure_ascii);
  11956. o->write_characters("\": ", 3);
  11957. dump(i->second, true, ensure_ascii, indent_step, new_indent);
  11958. o->write_character('\n');
  11959. o->write_characters(indent_string.c_str(), current_indent);
  11960. o->write_character('}');
  11961. }
  11962. else
  11963. {
  11964. o->write_character('{');
  11965. // first n-1 elements
  11966. auto i = val.m_value.object->cbegin();
  11967. for (std::size_t cnt = 0; cnt < val.m_value.object->size() - 1; ++cnt, ++i)
  11968. {
  11969. o->write_character('\"');
  11970. dump_escaped(i->first, ensure_ascii);
  11971. o->write_characters("\":", 2);
  11972. dump(i->second, false, ensure_ascii, indent_step, current_indent);
  11973. o->write_character(',');
  11974. }
  11975. // last element
  11976. assert(i != val.m_value.object->cend());
  11977. assert(std::next(i) == val.m_value.object->cend());
  11978. o->write_character('\"');
  11979. dump_escaped(i->first, ensure_ascii);
  11980. o->write_characters("\":", 2);
  11981. dump(i->second, false, ensure_ascii, indent_step, current_indent);
  11982. o->write_character('}');
  11983. }
  11984. return;
  11985. }
  11986. case value_t::array:
  11987. {
  11988. if (val.m_value.array->empty())
  11989. {
  11990. o->write_characters("[]", 2);
  11991. return;
  11992. }
  11993. if (pretty_print)
  11994. {
  11995. o->write_characters("[\n", 2);
  11996. // variable to hold indentation for recursive calls
  11997. const auto new_indent = current_indent + indent_step;
  11998. if (JSON_HEDLEY_UNLIKELY(indent_string.size() < new_indent))
  11999. {
  12000. indent_string.resize(indent_string.size() * 2, ' ');
  12001. }
  12002. // first n-1 elements
  12003. for (auto i = val.m_value.array->cbegin();
  12004. i != val.m_value.array->cend() - 1; ++i)
  12005. {
  12006. o->write_characters(indent_string.c_str(), new_indent);
  12007. dump(*i, true, ensure_ascii, indent_step, new_indent);
  12008. o->write_characters(",\n", 2);
  12009. }
  12010. // last element
  12011. assert(not val.m_value.array->empty());
  12012. o->write_characters(indent_string.c_str(), new_indent);
  12013. dump(val.m_value.array->back(), true, ensure_ascii, indent_step, new_indent);
  12014. o->write_character('\n');
  12015. o->write_characters(indent_string.c_str(), current_indent);
  12016. o->write_character(']');
  12017. }
  12018. else
  12019. {
  12020. o->write_character('[');
  12021. // first n-1 elements
  12022. for (auto i = val.m_value.array->cbegin();
  12023. i != val.m_value.array->cend() - 1; ++i)
  12024. {
  12025. dump(*i, false, ensure_ascii, indent_step, current_indent);
  12026. o->write_character(',');
  12027. }
  12028. // last element
  12029. assert(not val.m_value.array->empty());
  12030. dump(val.m_value.array->back(), false, ensure_ascii, indent_step, current_indent);
  12031. o->write_character(']');
  12032. }
  12033. return;
  12034. }
  12035. case value_t::string:
  12036. {
  12037. o->write_character('\"');
  12038. dump_escaped(*val.m_value.string, ensure_ascii);
  12039. o->write_character('\"');
  12040. return;
  12041. }
  12042. case value_t::boolean:
  12043. {
  12044. if (val.m_value.boolean)
  12045. {
  12046. o->write_characters("true", 4);
  12047. }
  12048. else
  12049. {
  12050. o->write_characters("false", 5);
  12051. }
  12052. return;
  12053. }
  12054. case value_t::number_integer:
  12055. {
  12056. dump_integer(val.m_value.number_integer);
  12057. return;
  12058. }
  12059. case value_t::number_unsigned:
  12060. {
  12061. dump_integer(val.m_value.number_unsigned);
  12062. return;
  12063. }
  12064. case value_t::number_float:
  12065. {
  12066. dump_float(val.m_value.number_float);
  12067. return;
  12068. }
  12069. case value_t::discarded:
  12070. {
  12071. o->write_characters("<discarded>", 11);
  12072. return;
  12073. }
  12074. case value_t::null:
  12075. {
  12076. o->write_characters("null", 4);
  12077. return;
  12078. }
  12079. default: // LCOV_EXCL_LINE
  12080. assert(false); // LCOV_EXCL_LINE
  12081. }
  12082. }
  12083. private:
  12084. /*!
  12085. @brief dump escaped string
  12086. Escape a string by replacing certain special characters by a sequence of an
  12087. escape character (backslash) and another character and other control
  12088. characters by a sequence of "\u" followed by a four-digit hex
  12089. representation. The escaped string is written to output stream @a o.
  12090. @param[in] s the string to escape
  12091. @param[in] ensure_ascii whether to escape non-ASCII characters with
  12092. \uXXXX sequences
  12093. @complexity Linear in the length of string @a s.
  12094. */
  12095. void dump_escaped(const string_t& s, const bool ensure_ascii)
  12096. {
  12097. std::uint32_t codepoint;
  12098. std::uint8_t state = UTF8_ACCEPT;
  12099. std::size_t bytes = 0; // number of bytes written to string_buffer
  12100. // number of bytes written at the point of the last valid byte
  12101. std::size_t bytes_after_last_accept = 0;
  12102. std::size_t undumped_chars = 0;
  12103. for (std::size_t i = 0; i < s.size(); ++i)
  12104. {
  12105. const auto byte = static_cast<uint8_t>(s[i]);
  12106. switch (decode(state, codepoint, byte))
  12107. {
  12108. case UTF8_ACCEPT: // decode found a new code point
  12109. {
  12110. switch (codepoint)
  12111. {
  12112. case 0x08: // backspace
  12113. {
  12114. string_buffer[bytes++] = '\\';
  12115. string_buffer[bytes++] = 'b';
  12116. break;
  12117. }
  12118. case 0x09: // horizontal tab
  12119. {
  12120. string_buffer[bytes++] = '\\';
  12121. string_buffer[bytes++] = 't';
  12122. break;
  12123. }
  12124. case 0x0A: // newline
  12125. {
  12126. string_buffer[bytes++] = '\\';
  12127. string_buffer[bytes++] = 'n';
  12128. break;
  12129. }
  12130. case 0x0C: // formfeed
  12131. {
  12132. string_buffer[bytes++] = '\\';
  12133. string_buffer[bytes++] = 'f';
  12134. break;
  12135. }
  12136. case 0x0D: // carriage return
  12137. {
  12138. string_buffer[bytes++] = '\\';
  12139. string_buffer[bytes++] = 'r';
  12140. break;
  12141. }
  12142. case 0x22: // quotation mark
  12143. {
  12144. string_buffer[bytes++] = '\\';
  12145. string_buffer[bytes++] = '\"';
  12146. break;
  12147. }
  12148. case 0x5C: // reverse solidus
  12149. {
  12150. string_buffer[bytes++] = '\\';
  12151. string_buffer[bytes++] = '\\';
  12152. break;
  12153. }
  12154. default:
  12155. {
  12156. // escape control characters (0x00..0x1F) or, if
  12157. // ensure_ascii parameter is used, non-ASCII characters
  12158. if ((codepoint <= 0x1F) or (ensure_ascii and (codepoint >= 0x7F)))
  12159. {
  12160. if (codepoint <= 0xFFFF)
  12161. {
  12162. (std::snprintf)(string_buffer.data() + bytes, 7, "\\u%04x",
  12163. static_cast<std::uint16_t>(codepoint));
  12164. bytes += 6;
  12165. }
  12166. else
  12167. {
  12168. (std::snprintf)(string_buffer.data() + bytes, 13, "\\u%04x\\u%04x",
  12169. static_cast<std::uint16_t>(0xD7C0u + (codepoint >> 10u)),
  12170. static_cast<std::uint16_t>(0xDC00u + (codepoint & 0x3FFu)));
  12171. bytes += 12;
  12172. }
  12173. }
  12174. else
  12175. {
  12176. // copy byte to buffer (all previous bytes
  12177. // been copied have in default case above)
  12178. string_buffer[bytes++] = s[i];
  12179. }
  12180. break;
  12181. }
  12182. }
  12183. // write buffer and reset index; there must be 13 bytes
  12184. // left, as this is the maximal number of bytes to be
  12185. // written ("\uxxxx\uxxxx\0") for one code point
  12186. if (string_buffer.size() - bytes < 13)
  12187. {
  12188. o->write_characters(string_buffer.data(), bytes);
  12189. bytes = 0;
  12190. }
  12191. // remember the byte position of this accept
  12192. bytes_after_last_accept = bytes;
  12193. undumped_chars = 0;
  12194. break;
  12195. }
  12196. case UTF8_REJECT: // decode found invalid UTF-8 byte
  12197. {
  12198. switch (error_handler)
  12199. {
  12200. case error_handler_t::strict:
  12201. {
  12202. std::string sn(3, '\0');
  12203. (std::snprintf)(&sn[0], sn.size(), "%.2X", byte);
  12204. JSON_THROW(type_error::create(316, "invalid UTF-8 byte at index " + std::to_string(i) + ": 0x" + sn));
  12205. }
  12206. case error_handler_t::ignore:
  12207. case error_handler_t::replace:
  12208. {
  12209. // in case we saw this character the first time, we
  12210. // would like to read it again, because the byte
  12211. // may be OK for itself, but just not OK for the
  12212. // previous sequence
  12213. if (undumped_chars > 0)
  12214. {
  12215. --i;
  12216. }
  12217. // reset length buffer to the last accepted index;
  12218. // thus removing/ignoring the invalid characters
  12219. bytes = bytes_after_last_accept;
  12220. if (error_handler == error_handler_t::replace)
  12221. {
  12222. // add a replacement character
  12223. if (ensure_ascii)
  12224. {
  12225. string_buffer[bytes++] = '\\';
  12226. string_buffer[bytes++] = 'u';
  12227. string_buffer[bytes++] = 'f';
  12228. string_buffer[bytes++] = 'f';
  12229. string_buffer[bytes++] = 'f';
  12230. string_buffer[bytes++] = 'd';
  12231. }
  12232. else
  12233. {
  12234. string_buffer[bytes++] = detail::binary_writer<BasicJsonType, char>::to_char_type('\xEF');
  12235. string_buffer[bytes++] = detail::binary_writer<BasicJsonType, char>::to_char_type('\xBF');
  12236. string_buffer[bytes++] = detail::binary_writer<BasicJsonType, char>::to_char_type('\xBD');
  12237. }
  12238. // write buffer and reset index; there must be 13 bytes
  12239. // left, as this is the maximal number of bytes to be
  12240. // written ("\uxxxx\uxxxx\0") for one code point
  12241. if (string_buffer.size() - bytes < 13)
  12242. {
  12243. o->write_characters(string_buffer.data(), bytes);
  12244. bytes = 0;
  12245. }
  12246. bytes_after_last_accept = bytes;
  12247. }
  12248. undumped_chars = 0;
  12249. // continue processing the string
  12250. state = UTF8_ACCEPT;
  12251. break;
  12252. }
  12253. default: // LCOV_EXCL_LINE
  12254. assert(false); // LCOV_EXCL_LINE
  12255. }
  12256. break;
  12257. }
  12258. default: // decode found yet incomplete multi-byte code point
  12259. {
  12260. if (not ensure_ascii)
  12261. {
  12262. // code point will not be escaped - copy byte to buffer
  12263. string_buffer[bytes++] = s[i];
  12264. }
  12265. ++undumped_chars;
  12266. break;
  12267. }
  12268. }
  12269. }
  12270. // we finished processing the string
  12271. if (JSON_HEDLEY_LIKELY(state == UTF8_ACCEPT))
  12272. {
  12273. // write buffer
  12274. if (bytes > 0)
  12275. {
  12276. o->write_characters(string_buffer.data(), bytes);
  12277. }
  12278. }
  12279. else
  12280. {
  12281. // we finish reading, but do not accept: string was incomplete
  12282. switch (error_handler)
  12283. {
  12284. case error_handler_t::strict:
  12285. {
  12286. std::string sn(3, '\0');
  12287. (std::snprintf)(&sn[0], sn.size(), "%.2X", static_cast<std::uint8_t>(s.back()));
  12288. JSON_THROW(type_error::create(316, "incomplete UTF-8 string; last byte: 0x" + sn));
  12289. }
  12290. case error_handler_t::ignore:
  12291. {
  12292. // write all accepted bytes
  12293. o->write_characters(string_buffer.data(), bytes_after_last_accept);
  12294. break;
  12295. }
  12296. case error_handler_t::replace:
  12297. {
  12298. // write all accepted bytes
  12299. o->write_characters(string_buffer.data(), bytes_after_last_accept);
  12300. // add a replacement character
  12301. if (ensure_ascii)
  12302. {
  12303. o->write_characters("\\ufffd", 6);
  12304. }
  12305. else
  12306. {
  12307. o->write_characters("\xEF\xBF\xBD", 3);
  12308. }
  12309. break;
  12310. }
  12311. default: // LCOV_EXCL_LINE
  12312. assert(false); // LCOV_EXCL_LINE
  12313. }
  12314. }
  12315. }
  12316. /*!
  12317. @brief count digits
  12318. Count the number of decimal (base 10) digits for an input unsigned integer.
  12319. @param[in] x unsigned integer number to count its digits
  12320. @return number of decimal digits
  12321. */
  12322. inline unsigned int count_digits(number_unsigned_t x) noexcept
  12323. {
  12324. unsigned int n_digits = 1;
  12325. for (;;)
  12326. {
  12327. if (x < 10)
  12328. {
  12329. return n_digits;
  12330. }
  12331. if (x < 100)
  12332. {
  12333. return n_digits + 1;
  12334. }
  12335. if (x < 1000)
  12336. {
  12337. return n_digits + 2;
  12338. }
  12339. if (x < 10000)
  12340. {
  12341. return n_digits + 3;
  12342. }
  12343. x = x / 10000u;
  12344. n_digits += 4;
  12345. }
  12346. }
  12347. /*!
  12348. @brief dump an integer
  12349. Dump a given integer to output stream @a o. Works internally with
  12350. @a number_buffer.
  12351. @param[in] x integer number (signed or unsigned) to dump
  12352. @tparam NumberType either @a number_integer_t or @a number_unsigned_t
  12353. */
  12354. template<typename NumberType, detail::enable_if_t<
  12355. std::is_same<NumberType, number_unsigned_t>::value or
  12356. std::is_same<NumberType, number_integer_t>::value,
  12357. int> = 0>
  12358. void dump_integer(NumberType x)
  12359. {
  12360. static constexpr std::array<std::array<char, 2>, 100> digits_to_99
  12361. {
  12362. {
  12363. {{'0', '0'}}, {{'0', '1'}}, {{'0', '2'}}, {{'0', '3'}}, {{'0', '4'}}, {{'0', '5'}}, {{'0', '6'}}, {{'0', '7'}}, {{'0', '8'}}, {{'0', '9'}},
  12364. {{'1', '0'}}, {{'1', '1'}}, {{'1', '2'}}, {{'1', '3'}}, {{'1', '4'}}, {{'1', '5'}}, {{'1', '6'}}, {{'1', '7'}}, {{'1', '8'}}, {{'1', '9'}},
  12365. {{'2', '0'}}, {{'2', '1'}}, {{'2', '2'}}, {{'2', '3'}}, {{'2', '4'}}, {{'2', '5'}}, {{'2', '6'}}, {{'2', '7'}}, {{'2', '8'}}, {{'2', '9'}},
  12366. {{'3', '0'}}, {{'3', '1'}}, {{'3', '2'}}, {{'3', '3'}}, {{'3', '4'}}, {{'3', '5'}}, {{'3', '6'}}, {{'3', '7'}}, {{'3', '8'}}, {{'3', '9'}},
  12367. {{'4', '0'}}, {{'4', '1'}}, {{'4', '2'}}, {{'4', '3'}}, {{'4', '4'}}, {{'4', '5'}}, {{'4', '6'}}, {{'4', '7'}}, {{'4', '8'}}, {{'4', '9'}},
  12368. {{'5', '0'}}, {{'5', '1'}}, {{'5', '2'}}, {{'5', '3'}}, {{'5', '4'}}, {{'5', '5'}}, {{'5', '6'}}, {{'5', '7'}}, {{'5', '8'}}, {{'5', '9'}},
  12369. {{'6', '0'}}, {{'6', '1'}}, {{'6', '2'}}, {{'6', '3'}}, {{'6', '4'}}, {{'6', '5'}}, {{'6', '6'}}, {{'6', '7'}}, {{'6', '8'}}, {{'6', '9'}},
  12370. {{'7', '0'}}, {{'7', '1'}}, {{'7', '2'}}, {{'7', '3'}}, {{'7', '4'}}, {{'7', '5'}}, {{'7', '6'}}, {{'7', '7'}}, {{'7', '8'}}, {{'7', '9'}},
  12371. {{'8', '0'}}, {{'8', '1'}}, {{'8', '2'}}, {{'8', '3'}}, {{'8', '4'}}, {{'8', '5'}}, {{'8', '6'}}, {{'8', '7'}}, {{'8', '8'}}, {{'8', '9'}},
  12372. {{'9', '0'}}, {{'9', '1'}}, {{'9', '2'}}, {{'9', '3'}}, {{'9', '4'}}, {{'9', '5'}}, {{'9', '6'}}, {{'9', '7'}}, {{'9', '8'}}, {{'9', '9'}},
  12373. }
  12374. };
  12375. // special case for "0"
  12376. if (x == 0)
  12377. {
  12378. o->write_character('0');
  12379. return;
  12380. }
  12381. // use a pointer to fill the buffer
  12382. auto buffer_ptr = number_buffer.begin();
  12383. const bool is_negative = std::is_same<NumberType, number_integer_t>::value and not(x >= 0); // see issue #755
  12384. number_unsigned_t abs_value;
  12385. unsigned int n_chars;
  12386. if (is_negative)
  12387. {
  12388. *buffer_ptr = '-';
  12389. abs_value = static_cast<number_unsigned_t>(std::abs(static_cast<std::intmax_t>(x)));
  12390. // account one more byte for the minus sign
  12391. n_chars = 1 + count_digits(abs_value);
  12392. }
  12393. else
  12394. {
  12395. abs_value = static_cast<number_unsigned_t>(x);
  12396. n_chars = count_digits(abs_value);
  12397. }
  12398. // spare 1 byte for '\0'
  12399. assert(n_chars < number_buffer.size() - 1);
  12400. // jump to the end to generate the string from backward
  12401. // so we later avoid reversing the result
  12402. buffer_ptr += n_chars;
  12403. // Fast int2ascii implementation inspired by "Fastware" talk by Andrei Alexandrescu
  12404. // See: https://www.youtube.com/watch?v=o4-CwDo2zpg
  12405. while (abs_value >= 100)
  12406. {
  12407. const auto digits_index = static_cast<unsigned>((abs_value % 100));
  12408. abs_value /= 100;
  12409. *(--buffer_ptr) = digits_to_99[digits_index][1];
  12410. *(--buffer_ptr) = digits_to_99[digits_index][0];
  12411. }
  12412. if (abs_value >= 10)
  12413. {
  12414. const auto digits_index = static_cast<unsigned>(abs_value);
  12415. *(--buffer_ptr) = digits_to_99[digits_index][1];
  12416. *(--buffer_ptr) = digits_to_99[digits_index][0];
  12417. }
  12418. else
  12419. {
  12420. *(--buffer_ptr) = static_cast<char>('0' + abs_value);
  12421. }
  12422. o->write_characters(number_buffer.data(), n_chars);
  12423. }
  12424. /*!
  12425. @brief dump a floating-point number
  12426. Dump a given floating-point number to output stream @a o. Works internally
  12427. with @a number_buffer.
  12428. @param[in] x floating-point number to dump
  12429. */
  12430. void dump_float(number_float_t x)
  12431. {
  12432. // NaN / inf
  12433. if (not std::isfinite(x))
  12434. {
  12435. o->write_characters("null", 4);
  12436. return;
  12437. }
  12438. // If number_float_t is an IEEE-754 single or double precision number,
  12439. // use the Grisu2 algorithm to produce short numbers which are
  12440. // guaranteed to round-trip, using strtof and strtod, resp.
  12441. //
  12442. // NB: The test below works if <long double> == <double>.
  12443. static constexpr bool is_ieee_single_or_double
  12444. = (std::numeric_limits<number_float_t>::is_iec559 and std::numeric_limits<number_float_t>::digits == 24 and std::numeric_limits<number_float_t>::max_exponent == 128) or
  12445. (std::numeric_limits<number_float_t>::is_iec559 and std::numeric_limits<number_float_t>::digits == 53 and std::numeric_limits<number_float_t>::max_exponent == 1024);
  12446. dump_float(x, std::integral_constant<bool, is_ieee_single_or_double>());
  12447. }
  12448. void dump_float(number_float_t x, std::true_type /*is_ieee_single_or_double*/)
  12449. {
  12450. char* begin = number_buffer.data();
  12451. char* end = ::nlohmann::detail::to_chars(begin, begin + number_buffer.size(), x);
  12452. o->write_characters(begin, static_cast<size_t>(end - begin));
  12453. }
  12454. void dump_float(number_float_t x, std::false_type /*is_ieee_single_or_double*/)
  12455. {
  12456. // get number of digits for a float -> text -> float round-trip
  12457. static constexpr auto d = std::numeric_limits<number_float_t>::max_digits10;
  12458. // the actual conversion
  12459. std::ptrdiff_t len = (std::snprintf)(number_buffer.data(), number_buffer.size(), "%.*g", d, x);
  12460. // negative value indicates an error
  12461. assert(len > 0);
  12462. // check if buffer was large enough
  12463. assert(static_cast<std::size_t>(len) < number_buffer.size());
  12464. // erase thousands separator
  12465. if (thousands_sep != '\0')
  12466. {
  12467. const auto end = std::remove(number_buffer.begin(),
  12468. number_buffer.begin() + len, thousands_sep);
  12469. std::fill(end, number_buffer.end(), '\0');
  12470. assert((end - number_buffer.begin()) <= len);
  12471. len = (end - number_buffer.begin());
  12472. }
  12473. // convert decimal point to '.'
  12474. if (decimal_point != '\0' and decimal_point != '.')
  12475. {
  12476. const auto dec_pos = std::find(number_buffer.begin(), number_buffer.end(), decimal_point);
  12477. if (dec_pos != number_buffer.end())
  12478. {
  12479. *dec_pos = '.';
  12480. }
  12481. }
  12482. o->write_characters(number_buffer.data(), static_cast<std::size_t>(len));
  12483. // determine if need to append ".0"
  12484. const bool value_is_int_like =
  12485. std::none_of(number_buffer.begin(), number_buffer.begin() + len + 1,
  12486. [](char c)
  12487. {
  12488. return c == '.' or c == 'e';
  12489. });
  12490. if (value_is_int_like)
  12491. {
  12492. o->write_characters(".0", 2);
  12493. }
  12494. }
  12495. /*!
  12496. @brief check whether a string is UTF-8 encoded
  12497. The function checks each byte of a string whether it is UTF-8 encoded. The
  12498. result of the check is stored in the @a state parameter. The function must
  12499. be called initially with state 0 (accept). State 1 means the string must
  12500. be rejected, because the current byte is not allowed. If the string is
  12501. completely processed, but the state is non-zero, the string ended
  12502. prematurely; that is, the last byte indicated more bytes should have
  12503. followed.
  12504. @param[in,out] state the state of the decoding
  12505. @param[in,out] codep codepoint (valid only if resulting state is UTF8_ACCEPT)
  12506. @param[in] byte next byte to decode
  12507. @return new state
  12508. @note The function has been edited: a std::array is used.
  12509. @copyright Copyright (c) 2008-2009 Bjoern Hoehrmann <bjoern@hoehrmann.de>
  12510. @sa http://bjoern.hoehrmann.de/utf-8/decoder/dfa/
  12511. */
  12512. static std::uint8_t decode(std::uint8_t& state, std::uint32_t& codep, const std::uint8_t byte) noexcept
  12513. {
  12514. static const std::array<std::uint8_t, 400> utf8d =
  12515. {
  12516. {
  12517. 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
  12518. 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
  12519. 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
  12520. 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
  12521. 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
  12522. 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
  12523. 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
  12524. 0xA, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x4, 0x3, 0x3, // E0..EF
  12525. 0xB, 0x6, 0x6, 0x6, 0x5, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, // F0..FF
  12526. 0x0, 0x1, 0x2, 0x3, 0x5, 0x8, 0x7, 0x1, 0x1, 0x1, 0x4, 0x6, 0x1, 0x1, 0x1, 0x1, // s0..s0
  12527. 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
  12528. 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
  12529. 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
  12530. 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
  12531. }
  12532. };
  12533. const std::uint8_t type = utf8d[byte];
  12534. codep = (state != UTF8_ACCEPT)
  12535. ? (byte & 0x3fu) | (codep << 6u)
  12536. : (0xFFu >> type) & (byte);
  12537. state = utf8d[256u + state * 16u + type];
  12538. return state;
  12539. }
  12540. private:
  12541. /// the output of the serializer
  12542. output_adapter_t<char> o = nullptr;
  12543. /// a (hopefully) large enough character buffer
  12544. std::array<char, 64> number_buffer{{}};
  12545. /// the locale
  12546. const std::lconv* loc = nullptr;
  12547. /// the locale's thousand separator character
  12548. const char thousands_sep = '\0';
  12549. /// the locale's decimal point character
  12550. const char decimal_point = '\0';
  12551. /// string buffer
  12552. std::array<char, 512> string_buffer{{}};
  12553. /// the indentation character
  12554. const char indent_char;
  12555. /// the indentation string
  12556. string_t indent_string;
  12557. /// error_handler how to react on decoding errors
  12558. const error_handler_t error_handler;
  12559. };
  12560. } // namespace detail
  12561. } // namespace nlohmann
  12562. // #include <nlohmann/detail/value_t.hpp>
  12563. // #include <nlohmann/json_fwd.hpp>
  12564. /*!
  12565. @brief namespace for Niels Lohmann
  12566. @see https://github.com/nlohmann
  12567. @since version 1.0.0
  12568. */
  12569. namespace nlohmann
  12570. {
  12571. /*!
  12572. @brief a class to store JSON values
  12573. @tparam ObjectType type for JSON objects (`std::map` by default; will be used
  12574. in @ref object_t)
  12575. @tparam ArrayType type for JSON arrays (`std::vector` by default; will be used
  12576. in @ref array_t)
  12577. @tparam StringType type for JSON strings and object keys (`std::string` by
  12578. default; will be used in @ref string_t)
  12579. @tparam BooleanType type for JSON booleans (`bool` by default; will be used
  12580. in @ref boolean_t)
  12581. @tparam NumberIntegerType type for JSON integer numbers (`int64_t` by
  12582. default; will be used in @ref number_integer_t)
  12583. @tparam NumberUnsignedType type for JSON unsigned integer numbers (@c
  12584. `uint64_t` by default; will be used in @ref number_unsigned_t)
  12585. @tparam NumberFloatType type for JSON floating-point numbers (`double` by
  12586. default; will be used in @ref number_float_t)
  12587. @tparam AllocatorType type of the allocator to use (`std::allocator` by
  12588. default)
  12589. @tparam JSONSerializer the serializer to resolve internal calls to `to_json()`
  12590. and `from_json()` (@ref adl_serializer by default)
  12591. @requirement The class satisfies the following concept requirements:
  12592. - Basic
  12593. - [DefaultConstructible](https://en.cppreference.com/w/cpp/named_req/DefaultConstructible):
  12594. JSON values can be default constructed. The result will be a JSON null
  12595. value.
  12596. - [MoveConstructible](https://en.cppreference.com/w/cpp/named_req/MoveConstructible):
  12597. A JSON value can be constructed from an rvalue argument.
  12598. - [CopyConstructible](https://en.cppreference.com/w/cpp/named_req/CopyConstructible):
  12599. A JSON value can be copy-constructed from an lvalue expression.
  12600. - [MoveAssignable](https://en.cppreference.com/w/cpp/named_req/MoveAssignable):
  12601. A JSON value van be assigned from an rvalue argument.
  12602. - [CopyAssignable](https://en.cppreference.com/w/cpp/named_req/CopyAssignable):
  12603. A JSON value can be copy-assigned from an lvalue expression.
  12604. - [Destructible](https://en.cppreference.com/w/cpp/named_req/Destructible):
  12605. JSON values can be destructed.
  12606. - Layout
  12607. - [StandardLayoutType](https://en.cppreference.com/w/cpp/named_req/StandardLayoutType):
  12608. JSON values have
  12609. [standard layout](https://en.cppreference.com/w/cpp/language/data_members#Standard_layout):
  12610. All non-static data members are private and standard layout types, the
  12611. class has no virtual functions or (virtual) base classes.
  12612. - Library-wide
  12613. - [EqualityComparable](https://en.cppreference.com/w/cpp/named_req/EqualityComparable):
  12614. JSON values can be compared with `==`, see @ref
  12615. operator==(const_reference,const_reference).
  12616. - [LessThanComparable](https://en.cppreference.com/w/cpp/named_req/LessThanComparable):
  12617. JSON values can be compared with `<`, see @ref
  12618. operator<(const_reference,const_reference).
  12619. - [Swappable](https://en.cppreference.com/w/cpp/named_req/Swappable):
  12620. Any JSON lvalue or rvalue of can be swapped with any lvalue or rvalue of
  12621. other compatible types, using unqualified function call @ref swap().
  12622. - [NullablePointer](https://en.cppreference.com/w/cpp/named_req/NullablePointer):
  12623. JSON values can be compared against `std::nullptr_t` objects which are used
  12624. to model the `null` value.
  12625. - Container
  12626. - [Container](https://en.cppreference.com/w/cpp/named_req/Container):
  12627. JSON values can be used like STL containers and provide iterator access.
  12628. - [ReversibleContainer](https://en.cppreference.com/w/cpp/named_req/ReversibleContainer);
  12629. JSON values can be used like STL containers and provide reverse iterator
  12630. access.
  12631. @invariant The member variables @a m_value and @a m_type have the following
  12632. relationship:
  12633. - If `m_type == value_t::object`, then `m_value.object != nullptr`.
  12634. - If `m_type == value_t::array`, then `m_value.array != nullptr`.
  12635. - If `m_type == value_t::string`, then `m_value.string != nullptr`.
  12636. The invariants are checked by member function assert_invariant().
  12637. @internal
  12638. @note ObjectType trick from http://stackoverflow.com/a/9860911
  12639. @endinternal
  12640. @see [RFC 7159: The JavaScript Object Notation (JSON) Data Interchange
  12641. Format](http://rfc7159.net/rfc7159)
  12642. @since version 1.0.0
  12643. @nosubgrouping
  12644. */
  12645. NLOHMANN_BASIC_JSON_TPL_DECLARATION
  12646. class basic_json
  12647. {
  12648. private:
  12649. template<detail::value_t> friend struct detail::external_constructor;
  12650. friend ::nlohmann::json_pointer<basic_json>;
  12651. friend ::nlohmann::detail::parser<basic_json>;
  12652. friend ::nlohmann::detail::serializer<basic_json>;
  12653. template<typename BasicJsonType>
  12654. friend class ::nlohmann::detail::iter_impl;
  12655. template<typename BasicJsonType, typename CharType>
  12656. friend class ::nlohmann::detail::binary_writer;
  12657. template<typename BasicJsonType, typename SAX>
  12658. friend class ::nlohmann::detail::binary_reader;
  12659. template<typename BasicJsonType>
  12660. friend class ::nlohmann::detail::json_sax_dom_parser;
  12661. template<typename BasicJsonType>
  12662. friend class ::nlohmann::detail::json_sax_dom_callback_parser;
  12663. /// workaround type for MSVC
  12664. using basic_json_t = NLOHMANN_BASIC_JSON_TPL;
  12665. // convenience aliases for types residing in namespace detail;
  12666. using lexer = ::nlohmann::detail::lexer<basic_json>;
  12667. using parser = ::nlohmann::detail::parser<basic_json>;
  12668. using primitive_iterator_t = ::nlohmann::detail::primitive_iterator_t;
  12669. template<typename BasicJsonType>
  12670. using internal_iterator = ::nlohmann::detail::internal_iterator<BasicJsonType>;
  12671. template<typename BasicJsonType>
  12672. using iter_impl = ::nlohmann::detail::iter_impl<BasicJsonType>;
  12673. template<typename Iterator>
  12674. using iteration_proxy = ::nlohmann::detail::iteration_proxy<Iterator>;
  12675. template<typename Base> using json_reverse_iterator = ::nlohmann::detail::json_reverse_iterator<Base>;
  12676. template<typename CharType>
  12677. using output_adapter_t = ::nlohmann::detail::output_adapter_t<CharType>;
  12678. using binary_reader = ::nlohmann::detail::binary_reader<basic_json>;
  12679. template<typename CharType> using binary_writer = ::nlohmann::detail::binary_writer<basic_json, CharType>;
  12680. using serializer = ::nlohmann::detail::serializer<basic_json>;
  12681. public:
  12682. using value_t = detail::value_t;
  12683. /// JSON Pointer, see @ref nlohmann::json_pointer
  12684. using json_pointer = ::nlohmann::json_pointer<basic_json>;
  12685. template<typename T, typename SFINAE>
  12686. using json_serializer = JSONSerializer<T, SFINAE>;
  12687. /// how to treat decoding errors
  12688. using error_handler_t = detail::error_handler_t;
  12689. /// helper type for initializer lists of basic_json values
  12690. using initializer_list_t = std::initializer_list<detail::json_ref<basic_json>>;
  12691. using input_format_t = detail::input_format_t;
  12692. /// SAX interface type, see @ref nlohmann::json_sax
  12693. using json_sax_t = json_sax<basic_json>;
  12694. ////////////////
  12695. // exceptions //
  12696. ////////////////
  12697. /// @name exceptions
  12698. /// Classes to implement user-defined exceptions.
  12699. /// @{
  12700. /// @copydoc detail::exception
  12701. using exception = detail::exception;
  12702. /// @copydoc detail::parse_error
  12703. using parse_error = detail::parse_error;
  12704. /// @copydoc detail::invalid_iterator
  12705. using invalid_iterator = detail::invalid_iterator;
  12706. /// @copydoc detail::type_error
  12707. using type_error = detail::type_error;
  12708. /// @copydoc detail::out_of_range
  12709. using out_of_range = detail::out_of_range;
  12710. /// @copydoc detail::other_error
  12711. using other_error = detail::other_error;
  12712. /// @}
  12713. /////////////////////
  12714. // container types //
  12715. /////////////////////
  12716. /// @name container types
  12717. /// The canonic container types to use @ref basic_json like any other STL
  12718. /// container.
  12719. /// @{
  12720. /// the type of elements in a basic_json container
  12721. using value_type = basic_json;
  12722. /// the type of an element reference
  12723. using reference = value_type&;
  12724. /// the type of an element const reference
  12725. using const_reference = const value_type&;
  12726. /// a type to represent differences between iterators
  12727. using difference_type = std::ptrdiff_t;
  12728. /// a type to represent container sizes
  12729. using size_type = std::size_t;
  12730. /// the allocator type
  12731. using allocator_type = AllocatorType<basic_json>;
  12732. /// the type of an element pointer
  12733. using pointer = typename std::allocator_traits<allocator_type>::pointer;
  12734. /// the type of an element const pointer
  12735. using const_pointer = typename std::allocator_traits<allocator_type>::const_pointer;
  12736. /// an iterator for a basic_json container
  12737. using iterator = iter_impl<basic_json>;
  12738. /// a const iterator for a basic_json container
  12739. using const_iterator = iter_impl<const basic_json>;
  12740. /// a reverse iterator for a basic_json container
  12741. using reverse_iterator = json_reverse_iterator<typename basic_json::iterator>;
  12742. /// a const reverse iterator for a basic_json container
  12743. using const_reverse_iterator = json_reverse_iterator<typename basic_json::const_iterator>;
  12744. /// @}
  12745. /*!
  12746. @brief returns the allocator associated with the container
  12747. */
  12748. static allocator_type get_allocator()
  12749. {
  12750. return allocator_type();
  12751. }
  12752. /*!
  12753. @brief returns version information on the library
  12754. This function returns a JSON object with information about the library,
  12755. including the version number and information on the platform and compiler.
  12756. @return JSON object holding version information
  12757. key | description
  12758. ----------- | ---------------
  12759. `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).
  12760. `copyright` | The copyright line for the library as string.
  12761. `name` | The name of the library as string.
  12762. `platform` | The used platform as string. Possible values are `win32`, `linux`, `apple`, `unix`, and `unknown`.
  12763. `url` | The URL of the project as string.
  12764. `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).
  12765. @liveexample{The following code shows an example output of the `meta()`
  12766. function.,meta}
  12767. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  12768. changes to any JSON value.
  12769. @complexity Constant.
  12770. @since 2.1.0
  12771. */
  12772. JSON_HEDLEY_WARN_UNUSED_RESULT
  12773. static basic_json meta()
  12774. {
  12775. basic_json result;
  12776. result["copyright"] = "(C) 2013-2017 Niels Lohmann";
  12777. result["name"] = "JSON for Modern C++";
  12778. result["url"] = "https://github.com/nlohmann/json";
  12779. result["version"]["string"] =
  12780. std::to_string(NLOHMANN_JSON_VERSION_MAJOR) + "." +
  12781. std::to_string(NLOHMANN_JSON_VERSION_MINOR) + "." +
  12782. std::to_string(NLOHMANN_JSON_VERSION_PATCH);
  12783. result["version"]["major"] = NLOHMANN_JSON_VERSION_MAJOR;
  12784. result["version"]["minor"] = NLOHMANN_JSON_VERSION_MINOR;
  12785. result["version"]["patch"] = NLOHMANN_JSON_VERSION_PATCH;
  12786. #ifdef _WIN32
  12787. result["platform"] = "win32";
  12788. #elif defined __linux__
  12789. result["platform"] = "linux";
  12790. #elif defined __APPLE__
  12791. result["platform"] = "apple";
  12792. #elif defined __unix__
  12793. result["platform"] = "unix";
  12794. #else
  12795. result["platform"] = "unknown";
  12796. #endif
  12797. #if defined(__ICC) || defined(__INTEL_COMPILER)
  12798. result["compiler"] = {{"family", "icc"}, {"version", __INTEL_COMPILER}};
  12799. #elif defined(__clang__)
  12800. result["compiler"] = {{"family", "clang"}, {"version", __clang_version__}};
  12801. #elif defined(__GNUC__) || defined(__GNUG__)
  12802. result["compiler"] = {{"family", "gcc"}, {"version", std::to_string(__GNUC__) + "." + std::to_string(__GNUC_MINOR__) + "." + std::to_string(__GNUC_PATCHLEVEL__)}};
  12803. #elif defined(__HP_cc) || defined(__HP_aCC)
  12804. result["compiler"] = "hp"
  12805. #elif defined(__IBMCPP__)
  12806. result["compiler"] = {{"family", "ilecpp"}, {"version", __IBMCPP__}};
  12807. #elif defined(_MSC_VER)
  12808. result["compiler"] = {{"family", "msvc"}, {"version", _MSC_VER}};
  12809. #elif defined(__PGI)
  12810. result["compiler"] = {{"family", "pgcpp"}, {"version", __PGI}};
  12811. #elif defined(__SUNPRO_CC)
  12812. result["compiler"] = {{"family", "sunpro"}, {"version", __SUNPRO_CC}};
  12813. #else
  12814. result["compiler"] = {{"family", "unknown"}, {"version", "unknown"}};
  12815. #endif
  12816. #ifdef __cplusplus
  12817. result["compiler"]["c++"] = std::to_string(__cplusplus);
  12818. #else
  12819. result["compiler"]["c++"] = "unknown";
  12820. #endif
  12821. return result;
  12822. }
  12823. ///////////////////////////
  12824. // JSON value data types //
  12825. ///////////////////////////
  12826. /// @name JSON value data types
  12827. /// The data types to store a JSON value. These types are derived from
  12828. /// the template arguments passed to class @ref basic_json.
  12829. /// @{
  12830. #if defined(JSON_HAS_CPP_14)
  12831. // Use transparent comparator if possible, combined with perfect forwarding
  12832. // on find() and count() calls prevents unnecessary string construction.
  12833. using object_comparator_t = std::less<>;
  12834. #else
  12835. using object_comparator_t = std::less<StringType>;
  12836. #endif
  12837. /*!
  12838. @brief a type for an object
  12839. [RFC 7159](http://rfc7159.net/rfc7159) describes JSON objects as follows:
  12840. > An object is an unordered collection of zero or more name/value pairs,
  12841. > where a name is a string and a value is a string, number, boolean, null,
  12842. > object, or array.
  12843. To store objects in C++, a type is defined by the template parameters
  12844. described below.
  12845. @tparam ObjectType the container to store objects (e.g., `std::map` or
  12846. `std::unordered_map`)
  12847. @tparam StringType the type of the keys or names (e.g., `std::string`).
  12848. The comparison function `std::less<StringType>` is used to order elements
  12849. inside the container.
  12850. @tparam AllocatorType the allocator to use for objects (e.g.,
  12851. `std::allocator`)
  12852. #### Default type
  12853. With the default values for @a ObjectType (`std::map`), @a StringType
  12854. (`std::string`), and @a AllocatorType (`std::allocator`), the default
  12855. value for @a object_t is:
  12856. @code {.cpp}
  12857. std::map<
  12858. std::string, // key_type
  12859. basic_json, // value_type
  12860. std::less<std::string>, // key_compare
  12861. std::allocator<std::pair<const std::string, basic_json>> // allocator_type
  12862. >
  12863. @endcode
  12864. #### Behavior
  12865. The choice of @a object_t influences the behavior of the JSON class. With
  12866. the default type, objects have the following behavior:
  12867. - When all names are unique, objects will be interoperable in the sense
  12868. that all software implementations receiving that object will agree on
  12869. the name-value mappings.
  12870. - When the names within an object are not unique, it is unspecified which
  12871. one of the values for a given key will be chosen. For instance,
  12872. `{"key": 2, "key": 1}` could be equal to either `{"key": 1}` or
  12873. `{"key": 2}`.
  12874. - Internally, name/value pairs are stored in lexicographical order of the
  12875. names. Objects will also be serialized (see @ref dump) in this order.
  12876. For instance, `{"b": 1, "a": 2}` and `{"a": 2, "b": 1}` will be stored
  12877. and serialized as `{"a": 2, "b": 1}`.
  12878. - When comparing objects, the order of the name/value pairs is irrelevant.
  12879. This makes objects interoperable in the sense that they will not be
  12880. affected by these differences. For instance, `{"b": 1, "a": 2}` and
  12881. `{"a": 2, "b": 1}` will be treated as equal.
  12882. #### Limits
  12883. [RFC 7159](http://rfc7159.net/rfc7159) specifies:
  12884. > An implementation may set limits on the maximum depth of nesting.
  12885. In this class, the object's limit of nesting is not explicitly constrained.
  12886. However, a maximum depth of nesting may be introduced by the compiler or
  12887. runtime environment. A theoretical limit can be queried by calling the
  12888. @ref max_size function of a JSON object.
  12889. #### Storage
  12890. Objects are stored as pointers in a @ref basic_json type. That is, for any
  12891. access to object values, a pointer of type `object_t*` must be
  12892. dereferenced.
  12893. @sa @ref array_t -- type for an array value
  12894. @since version 1.0.0
  12895. @note The order name/value pairs are added to the object is *not*
  12896. preserved by the library. Therefore, iterating an object may return
  12897. name/value pairs in a different order than they were originally stored. In
  12898. fact, keys will be traversed in alphabetical order as `std::map` with
  12899. `std::less` is used by default. Please note this behavior conforms to [RFC
  12900. 7159](http://rfc7159.net/rfc7159), because any order implements the
  12901. specified "unordered" nature of JSON objects.
  12902. */
  12903. using object_t = ObjectType<StringType,
  12904. basic_json,
  12905. object_comparator_t,
  12906. AllocatorType<std::pair<const StringType,
  12907. basic_json>>>;
  12908. /*!
  12909. @brief a type for an array
  12910. [RFC 7159](http://rfc7159.net/rfc7159) describes JSON arrays as follows:
  12911. > An array is an ordered sequence of zero or more values.
  12912. To store objects in C++, a type is defined by the template parameters
  12913. explained below.
  12914. @tparam ArrayType container type to store arrays (e.g., `std::vector` or
  12915. `std::list`)
  12916. @tparam AllocatorType allocator to use for arrays (e.g., `std::allocator`)
  12917. #### Default type
  12918. With the default values for @a ArrayType (`std::vector`) and @a
  12919. AllocatorType (`std::allocator`), the default value for @a array_t is:
  12920. @code {.cpp}
  12921. std::vector<
  12922. basic_json, // value_type
  12923. std::allocator<basic_json> // allocator_type
  12924. >
  12925. @endcode
  12926. #### Limits
  12927. [RFC 7159](http://rfc7159.net/rfc7159) specifies:
  12928. > An implementation may set limits on the maximum depth of nesting.
  12929. In this class, the array's limit of nesting is not explicitly constrained.
  12930. However, a maximum depth of nesting may be introduced by the compiler or
  12931. runtime environment. A theoretical limit can be queried by calling the
  12932. @ref max_size function of a JSON array.
  12933. #### Storage
  12934. Arrays are stored as pointers in a @ref basic_json type. That is, for any
  12935. access to array values, a pointer of type `array_t*` must be dereferenced.
  12936. @sa @ref object_t -- type for an object value
  12937. @since version 1.0.0
  12938. */
  12939. using array_t = ArrayType<basic_json, AllocatorType<basic_json>>;
  12940. /*!
  12941. @brief a type for a string
  12942. [RFC 7159](http://rfc7159.net/rfc7159) describes JSON strings as follows:
  12943. > A string is a sequence of zero or more Unicode characters.
  12944. To store objects in C++, a type is defined by the template parameter
  12945. described below. Unicode values are split by the JSON class into
  12946. byte-sized characters during deserialization.
  12947. @tparam StringType the container to store strings (e.g., `std::string`).
  12948. Note this container is used for keys/names in objects, see @ref object_t.
  12949. #### Default type
  12950. With the default values for @a StringType (`std::string`), the default
  12951. value for @a string_t is:
  12952. @code {.cpp}
  12953. std::string
  12954. @endcode
  12955. #### Encoding
  12956. Strings are stored in UTF-8 encoding. Therefore, functions like
  12957. `std::string::size()` or `std::string::length()` return the number of
  12958. bytes in the string rather than the number of characters or glyphs.
  12959. #### String comparison
  12960. [RFC 7159](http://rfc7159.net/rfc7159) states:
  12961. > Software implementations are typically required to test names of object
  12962. > members for equality. Implementations that transform the textual
  12963. > representation into sequences of Unicode code units and then perform the
  12964. > comparison numerically, code unit by code unit, are interoperable in the
  12965. > sense that implementations will agree in all cases on equality or
  12966. > inequality of two strings. For example, implementations that compare
  12967. > strings with escaped characters unconverted may incorrectly find that
  12968. > `"a\\b"` and `"a\u005Cb"` are not equal.
  12969. This implementation is interoperable as it does compare strings code unit
  12970. by code unit.
  12971. #### Storage
  12972. String values are stored as pointers in a @ref basic_json type. That is,
  12973. for any access to string values, a pointer of type `string_t*` must be
  12974. dereferenced.
  12975. @since version 1.0.0
  12976. */
  12977. using string_t = StringType;
  12978. /*!
  12979. @brief a type for a boolean
  12980. [RFC 7159](http://rfc7159.net/rfc7159) implicitly describes a boolean as a
  12981. type which differentiates the two literals `true` and `false`.
  12982. To store objects in C++, a type is defined by the template parameter @a
  12983. BooleanType which chooses the type to use.
  12984. #### Default type
  12985. With the default values for @a BooleanType (`bool`), the default value for
  12986. @a boolean_t is:
  12987. @code {.cpp}
  12988. bool
  12989. @endcode
  12990. #### Storage
  12991. Boolean values are stored directly inside a @ref basic_json type.
  12992. @since version 1.0.0
  12993. */
  12994. using boolean_t = BooleanType;
  12995. /*!
  12996. @brief a type for a number (integer)
  12997. [RFC 7159](http://rfc7159.net/rfc7159) describes numbers as follows:
  12998. > The representation of numbers is similar to that used in most
  12999. > programming languages. A number is represented in base 10 using decimal
  13000. > digits. It contains an integer component that may be prefixed with an
  13001. > optional minus sign, which may be followed by a fraction part and/or an
  13002. > exponent part. Leading zeros are not allowed. (...) Numeric values that
  13003. > cannot be represented in the grammar below (such as Infinity and NaN)
  13004. > are not permitted.
  13005. This description includes both integer and floating-point numbers.
  13006. However, C++ allows more precise storage if it is known whether the number
  13007. is a signed integer, an unsigned integer or a floating-point number.
  13008. Therefore, three different types, @ref number_integer_t, @ref
  13009. number_unsigned_t and @ref number_float_t are used.
  13010. To store integer numbers in C++, a type is defined by the template
  13011. parameter @a NumberIntegerType which chooses the type to use.
  13012. #### Default type
  13013. With the default values for @a NumberIntegerType (`int64_t`), the default
  13014. value for @a number_integer_t is:
  13015. @code {.cpp}
  13016. int64_t
  13017. @endcode
  13018. #### Default behavior
  13019. - The restrictions about leading zeros is not enforced in C++. Instead,
  13020. leading zeros in integer literals lead to an interpretation as octal
  13021. number. Internally, the value will be stored as decimal number. For
  13022. instance, the C++ integer literal `010` will be serialized to `8`.
  13023. During deserialization, leading zeros yield an error.
  13024. - Not-a-number (NaN) values will be serialized to `null`.
  13025. #### Limits
  13026. [RFC 7159](http://rfc7159.net/rfc7159) specifies:
  13027. > An implementation may set limits on the range and precision of numbers.
  13028. When the default type is used, the maximal integer number that can be
  13029. stored is `9223372036854775807` (INT64_MAX) and the minimal integer number
  13030. that can be stored is `-9223372036854775808` (INT64_MIN). Integer numbers
  13031. that are out of range will yield over/underflow when used in a
  13032. constructor. During deserialization, too large or small integer numbers
  13033. will be automatically be stored as @ref number_unsigned_t or @ref
  13034. number_float_t.
  13035. [RFC 7159](http://rfc7159.net/rfc7159) further states:
  13036. > Note that when such software is used, numbers that are integers and are
  13037. > in the range \f$[-2^{53}+1, 2^{53}-1]\f$ are interoperable in the sense
  13038. > that implementations will agree exactly on their numeric values.
  13039. As this range is a subrange of the exactly supported range [INT64_MIN,
  13040. INT64_MAX], this class's integer type is interoperable.
  13041. #### Storage
  13042. Integer number values are stored directly inside a @ref basic_json type.
  13043. @sa @ref number_float_t -- type for number values (floating-point)
  13044. @sa @ref number_unsigned_t -- type for number values (unsigned integer)
  13045. @since version 1.0.0
  13046. */
  13047. using number_integer_t = NumberIntegerType;
  13048. /*!
  13049. @brief a type for a number (unsigned)
  13050. [RFC 7159](http://rfc7159.net/rfc7159) describes numbers as follows:
  13051. > The representation of numbers is similar to that used in most
  13052. > programming languages. A number is represented in base 10 using decimal
  13053. > digits. It contains an integer component that may be prefixed with an
  13054. > optional minus sign, which may be followed by a fraction part and/or an
  13055. > exponent part. Leading zeros are not allowed. (...) Numeric values that
  13056. > cannot be represented in the grammar below (such as Infinity and NaN)
  13057. > are not permitted.
  13058. This description includes both integer and floating-point numbers.
  13059. However, C++ allows more precise storage if it is known whether the number
  13060. is a signed integer, an unsigned integer or a floating-point number.
  13061. Therefore, three different types, @ref number_integer_t, @ref
  13062. number_unsigned_t and @ref number_float_t are used.
  13063. To store unsigned integer numbers in C++, a type is defined by the
  13064. template parameter @a NumberUnsignedType which chooses the type to use.
  13065. #### Default type
  13066. With the default values for @a NumberUnsignedType (`uint64_t`), the
  13067. default value for @a number_unsigned_t is:
  13068. @code {.cpp}
  13069. uint64_t
  13070. @endcode
  13071. #### Default behavior
  13072. - The restrictions about leading zeros is not enforced in C++. Instead,
  13073. leading zeros in integer literals lead to an interpretation as octal
  13074. number. Internally, the value will be stored as decimal number. For
  13075. instance, the C++ integer literal `010` will be serialized to `8`.
  13076. During deserialization, leading zeros yield an error.
  13077. - Not-a-number (NaN) values will be serialized to `null`.
  13078. #### Limits
  13079. [RFC 7159](http://rfc7159.net/rfc7159) specifies:
  13080. > An implementation may set limits on the range and precision of numbers.
  13081. When the default type is used, the maximal integer number that can be
  13082. stored is `18446744073709551615` (UINT64_MAX) and the minimal integer
  13083. number that can be stored is `0`. Integer numbers that are out of range
  13084. will yield over/underflow when used in a constructor. During
  13085. deserialization, too large or small integer numbers will be automatically
  13086. be stored as @ref number_integer_t or @ref number_float_t.
  13087. [RFC 7159](http://rfc7159.net/rfc7159) further states:
  13088. > Note that when such software is used, numbers that are integers and are
  13089. > in the range \f$[-2^{53}+1, 2^{53}-1]\f$ are interoperable in the sense
  13090. > that implementations will agree exactly on their numeric values.
  13091. As this range is a subrange (when considered in conjunction with the
  13092. number_integer_t type) of the exactly supported range [0, UINT64_MAX],
  13093. this class's integer type is interoperable.
  13094. #### Storage
  13095. Integer number values are stored directly inside a @ref basic_json type.
  13096. @sa @ref number_float_t -- type for number values (floating-point)
  13097. @sa @ref number_integer_t -- type for number values (integer)
  13098. @since version 2.0.0
  13099. */
  13100. using number_unsigned_t = NumberUnsignedType;
  13101. /*!
  13102. @brief a type for a number (floating-point)
  13103. [RFC 7159](http://rfc7159.net/rfc7159) describes numbers as follows:
  13104. > The representation of numbers is similar to that used in most
  13105. > programming languages. A number is represented in base 10 using decimal
  13106. > digits. It contains an integer component that may be prefixed with an
  13107. > optional minus sign, which may be followed by a fraction part and/or an
  13108. > exponent part. Leading zeros are not allowed. (...) Numeric values that
  13109. > cannot be represented in the grammar below (such as Infinity and NaN)
  13110. > are not permitted.
  13111. This description includes both integer and floating-point numbers.
  13112. However, C++ allows more precise storage if it is known whether the number
  13113. is a signed integer, an unsigned integer or a floating-point number.
  13114. Therefore, three different types, @ref number_integer_t, @ref
  13115. number_unsigned_t and @ref number_float_t are used.
  13116. To store floating-point numbers in C++, a type is defined by the template
  13117. parameter @a NumberFloatType which chooses the type to use.
  13118. #### Default type
  13119. With the default values for @a NumberFloatType (`double`), the default
  13120. value for @a number_float_t is:
  13121. @code {.cpp}
  13122. double
  13123. @endcode
  13124. #### Default behavior
  13125. - The restrictions about leading zeros is not enforced in C++. Instead,
  13126. leading zeros in floating-point literals will be ignored. Internally,
  13127. the value will be stored as decimal number. For instance, the C++
  13128. floating-point literal `01.2` will be serialized to `1.2`. During
  13129. deserialization, leading zeros yield an error.
  13130. - Not-a-number (NaN) values will be serialized to `null`.
  13131. #### Limits
  13132. [RFC 7159](http://rfc7159.net/rfc7159) states:
  13133. > This specification allows implementations to set limits on the range and
  13134. > precision of numbers accepted. Since software that implements IEEE
  13135. > 754-2008 binary64 (double precision) numbers is generally available and
  13136. > widely used, good interoperability can be achieved by implementations
  13137. > that expect no more precision or range than these provide, in the sense
  13138. > that implementations will approximate JSON numbers within the expected
  13139. > precision.
  13140. This implementation does exactly follow this approach, as it uses double
  13141. precision floating-point numbers. Note values smaller than
  13142. `-1.79769313486232e+308` and values greater than `1.79769313486232e+308`
  13143. will be stored as NaN internally and be serialized to `null`.
  13144. #### Storage
  13145. Floating-point number values are stored directly inside a @ref basic_json
  13146. type.
  13147. @sa @ref number_integer_t -- type for number values (integer)
  13148. @sa @ref number_unsigned_t -- type for number values (unsigned integer)
  13149. @since version 1.0.0
  13150. */
  13151. using number_float_t = NumberFloatType;
  13152. /// @}
  13153. private:
  13154. /// helper for exception-safe object creation
  13155. template<typename T, typename... Args>
  13156. JSON_HEDLEY_RETURNS_NON_NULL
  13157. static T* create(Args&& ... args)
  13158. {
  13159. AllocatorType<T> alloc;
  13160. using AllocatorTraits = std::allocator_traits<AllocatorType<T>>;
  13161. auto deleter = [&](T * object)
  13162. {
  13163. AllocatorTraits::deallocate(alloc, object, 1);
  13164. };
  13165. std::unique_ptr<T, decltype(deleter)> object(AllocatorTraits::allocate(alloc, 1), deleter);
  13166. AllocatorTraits::construct(alloc, object.get(), std::forward<Args>(args)...);
  13167. assert(object != nullptr);
  13168. return object.release();
  13169. }
  13170. ////////////////////////
  13171. // JSON value storage //
  13172. ////////////////////////
  13173. /*!
  13174. @brief a JSON value
  13175. The actual storage for a JSON value of the @ref basic_json class. This
  13176. union combines the different storage types for the JSON value types
  13177. defined in @ref value_t.
  13178. JSON type | value_t type | used type
  13179. --------- | --------------- | ------------------------
  13180. object | object | pointer to @ref object_t
  13181. array | array | pointer to @ref array_t
  13182. string | string | pointer to @ref string_t
  13183. boolean | boolean | @ref boolean_t
  13184. number | number_integer | @ref number_integer_t
  13185. number | number_unsigned | @ref number_unsigned_t
  13186. number | number_float | @ref number_float_t
  13187. null | null | *no value is stored*
  13188. @note Variable-length types (objects, arrays, and strings) are stored as
  13189. pointers. The size of the union should not exceed 64 bits if the default
  13190. value types are used.
  13191. @since version 1.0.0
  13192. */
  13193. union json_value
  13194. {
  13195. /// object (stored with pointer to save storage)
  13196. object_t* object;
  13197. /// array (stored with pointer to save storage)
  13198. array_t* array;
  13199. /// string (stored with pointer to save storage)
  13200. string_t* string;
  13201. /// boolean
  13202. boolean_t boolean;
  13203. /// number (integer)
  13204. number_integer_t number_integer;
  13205. /// number (unsigned integer)
  13206. number_unsigned_t number_unsigned;
  13207. /// number (floating-point)
  13208. number_float_t number_float;
  13209. /// default constructor (for null values)
  13210. json_value() = default;
  13211. /// constructor for booleans
  13212. json_value(boolean_t v) noexcept : boolean(v) {}
  13213. /// constructor for numbers (integer)
  13214. json_value(number_integer_t v) noexcept : number_integer(v) {}
  13215. /// constructor for numbers (unsigned)
  13216. json_value(number_unsigned_t v) noexcept : number_unsigned(v) {}
  13217. /// constructor for numbers (floating-point)
  13218. json_value(number_float_t v) noexcept : number_float(v) {}
  13219. /// constructor for empty values of a given type
  13220. json_value(value_t t)
  13221. {
  13222. switch (t)
  13223. {
  13224. case value_t::object:
  13225. {
  13226. object = create<object_t>();
  13227. break;
  13228. }
  13229. case value_t::array:
  13230. {
  13231. array = create<array_t>();
  13232. break;
  13233. }
  13234. case value_t::string:
  13235. {
  13236. string = create<string_t>("");
  13237. break;
  13238. }
  13239. case value_t::boolean:
  13240. {
  13241. boolean = boolean_t(false);
  13242. break;
  13243. }
  13244. case value_t::number_integer:
  13245. {
  13246. number_integer = number_integer_t(0);
  13247. break;
  13248. }
  13249. case value_t::number_unsigned:
  13250. {
  13251. number_unsigned = number_unsigned_t(0);
  13252. break;
  13253. }
  13254. case value_t::number_float:
  13255. {
  13256. number_float = number_float_t(0.0);
  13257. break;
  13258. }
  13259. case value_t::null:
  13260. {
  13261. object = nullptr; // silence warning, see #821
  13262. break;
  13263. }
  13264. default:
  13265. {
  13266. object = nullptr; // silence warning, see #821
  13267. if (JSON_HEDLEY_UNLIKELY(t == value_t::null))
  13268. {
  13269. JSON_THROW(other_error::create(500, "961c151d2e87f2686a955a9be24d316f1362bf21 3.7.0")); // LCOV_EXCL_LINE
  13270. }
  13271. break;
  13272. }
  13273. }
  13274. }
  13275. /// constructor for strings
  13276. json_value(const string_t& value)
  13277. {
  13278. string = create<string_t>(value);
  13279. }
  13280. /// constructor for rvalue strings
  13281. json_value(string_t&& value)
  13282. {
  13283. string = create<string_t>(std::move(value));
  13284. }
  13285. /// constructor for objects
  13286. json_value(const object_t& value)
  13287. {
  13288. object = create<object_t>(value);
  13289. }
  13290. /// constructor for rvalue objects
  13291. json_value(object_t&& value)
  13292. {
  13293. object = create<object_t>(std::move(value));
  13294. }
  13295. /// constructor for arrays
  13296. json_value(const array_t& value)
  13297. {
  13298. array = create<array_t>(value);
  13299. }
  13300. /// constructor for rvalue arrays
  13301. json_value(array_t&& value)
  13302. {
  13303. array = create<array_t>(std::move(value));
  13304. }
  13305. void destroy(value_t t) noexcept
  13306. {
  13307. switch (t)
  13308. {
  13309. case value_t::object:
  13310. {
  13311. AllocatorType<object_t> alloc;
  13312. std::allocator_traits<decltype(alloc)>::destroy(alloc, object);
  13313. std::allocator_traits<decltype(alloc)>::deallocate(alloc, object, 1);
  13314. break;
  13315. }
  13316. case value_t::array:
  13317. {
  13318. AllocatorType<array_t> alloc;
  13319. std::allocator_traits<decltype(alloc)>::destroy(alloc, array);
  13320. std::allocator_traits<decltype(alloc)>::deallocate(alloc, array, 1);
  13321. break;
  13322. }
  13323. case value_t::string:
  13324. {
  13325. AllocatorType<string_t> alloc;
  13326. std::allocator_traits<decltype(alloc)>::destroy(alloc, string);
  13327. std::allocator_traits<decltype(alloc)>::deallocate(alloc, string, 1);
  13328. break;
  13329. }
  13330. default:
  13331. {
  13332. break;
  13333. }
  13334. }
  13335. }
  13336. };
  13337. /*!
  13338. @brief checks the class invariants
  13339. This function asserts the class invariants. It needs to be called at the
  13340. end of every constructor to make sure that created objects respect the
  13341. invariant. Furthermore, it has to be called each time the type of a JSON
  13342. value is changed, because the invariant expresses a relationship between
  13343. @a m_type and @a m_value.
  13344. */
  13345. void assert_invariant() const noexcept
  13346. {
  13347. assert(m_type != value_t::object or m_value.object != nullptr);
  13348. assert(m_type != value_t::array or m_value.array != nullptr);
  13349. assert(m_type != value_t::string or m_value.string != nullptr);
  13350. }
  13351. public:
  13352. //////////////////////////
  13353. // JSON parser callback //
  13354. //////////////////////////
  13355. /*!
  13356. @brief parser event types
  13357. The parser callback distinguishes the following events:
  13358. - `object_start`: the parser read `{` and started to process a JSON object
  13359. - `key`: the parser read a key of a value in an object
  13360. - `object_end`: the parser read `}` and finished processing a JSON object
  13361. - `array_start`: the parser read `[` and started to process a JSON array
  13362. - `array_end`: the parser read `]` and finished processing a JSON array
  13363. - `value`: the parser finished reading a JSON value
  13364. @image html callback_events.png "Example when certain parse events are triggered"
  13365. @sa @ref parser_callback_t for more information and examples
  13366. */
  13367. using parse_event_t = typename parser::parse_event_t;
  13368. /*!
  13369. @brief per-element parser callback type
  13370. With a parser callback function, the result of parsing a JSON text can be
  13371. influenced. When passed to @ref parse, it is called on certain events
  13372. (passed as @ref parse_event_t via parameter @a event) with a set recursion
  13373. depth @a depth and context JSON value @a parsed. The return value of the
  13374. callback function is a boolean indicating whether the element that emitted
  13375. the callback shall be kept or not.
  13376. We distinguish six scenarios (determined by the event type) in which the
  13377. callback function can be called. The following table describes the values
  13378. of the parameters @a depth, @a event, and @a parsed.
  13379. parameter @a event | description | parameter @a depth | parameter @a parsed
  13380. ------------------ | ----------- | ------------------ | -------------------
  13381. 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
  13382. 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
  13383. 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
  13384. 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
  13385. 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
  13386. parse_event_t::value | the parser finished reading a JSON value | depth of the value | the parsed JSON value
  13387. @image html callback_events.png "Example when certain parse events are triggered"
  13388. Discarding a value (i.e., returning `false`) has different effects
  13389. depending on the context in which function was called:
  13390. - Discarded values in structured types are skipped. That is, the parser
  13391. will behave as if the discarded value was never read.
  13392. - In case a value outside a structured type is skipped, it is replaced
  13393. with `null`. This case happens if the top-level element is skipped.
  13394. @param[in] depth the depth of the recursion during parsing
  13395. @param[in] event an event of type parse_event_t indicating the context in
  13396. the callback function has been called
  13397. @param[in,out] parsed the current intermediate parse result; note that
  13398. writing to this value has no effect for parse_event_t::key events
  13399. @return Whether the JSON value which called the function during parsing
  13400. should be kept (`true`) or not (`false`). In the latter case, it is either
  13401. skipped completely or replaced by an empty discarded object.
  13402. @sa @ref parse for examples
  13403. @since version 1.0.0
  13404. */
  13405. using parser_callback_t = typename parser::parser_callback_t;
  13406. //////////////////
  13407. // constructors //
  13408. //////////////////
  13409. /// @name constructors and destructors
  13410. /// Constructors of class @ref basic_json, copy/move constructor, copy
  13411. /// assignment, static functions creating objects, and the destructor.
  13412. /// @{
  13413. /*!
  13414. @brief create an empty value with a given type
  13415. Create an empty JSON value with a given type. The value will be default
  13416. initialized with an empty value which depends on the type:
  13417. Value type | initial value
  13418. ----------- | -------------
  13419. null | `null`
  13420. boolean | `false`
  13421. string | `""`
  13422. number | `0`
  13423. object | `{}`
  13424. array | `[]`
  13425. @param[in] v the type of the value to create
  13426. @complexity Constant.
  13427. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  13428. changes to any JSON value.
  13429. @liveexample{The following code shows the constructor for different @ref
  13430. value_t values,basic_json__value_t}
  13431. @sa @ref clear() -- restores the postcondition of this constructor
  13432. @since version 1.0.0
  13433. */
  13434. basic_json(const value_t v)
  13435. : m_type(v), m_value(v)
  13436. {
  13437. assert_invariant();
  13438. }
  13439. /*!
  13440. @brief create a null object
  13441. Create a `null` JSON value. It either takes a null pointer as parameter
  13442. (explicitly creating `null`) or no parameter (implicitly creating `null`).
  13443. The passed null pointer itself is not read -- it is only used to choose
  13444. the right constructor.
  13445. @complexity Constant.
  13446. @exceptionsafety No-throw guarantee: this constructor never throws
  13447. exceptions.
  13448. @liveexample{The following code shows the constructor with and without a
  13449. null pointer parameter.,basic_json__nullptr_t}
  13450. @since version 1.0.0
  13451. */
  13452. basic_json(std::nullptr_t = nullptr) noexcept
  13453. : basic_json(value_t::null)
  13454. {
  13455. assert_invariant();
  13456. }
  13457. /*!
  13458. @brief create a JSON value
  13459. This is a "catch all" constructor for all compatible JSON types; that is,
  13460. types for which a `to_json()` method exists. The constructor forwards the
  13461. parameter @a val to that method (to `json_serializer<U>::to_json` method
  13462. with `U = uncvref_t<CompatibleType>`, to be exact).
  13463. Template type @a CompatibleType includes, but is not limited to, the
  13464. following types:
  13465. - **arrays**: @ref array_t and all kinds of compatible containers such as
  13466. `std::vector`, `std::deque`, `std::list`, `std::forward_list`,
  13467. `std::array`, `std::valarray`, `std::set`, `std::unordered_set`,
  13468. `std::multiset`, and `std::unordered_multiset` with a `value_type` from
  13469. which a @ref basic_json value can be constructed.
  13470. - **objects**: @ref object_t and all kinds of compatible associative
  13471. containers such as `std::map`, `std::unordered_map`, `std::multimap`,
  13472. and `std::unordered_multimap` with a `key_type` compatible to
  13473. @ref string_t and a `value_type` from which a @ref basic_json value can
  13474. be constructed.
  13475. - **strings**: @ref string_t, string literals, and all compatible string
  13476. containers can be used.
  13477. - **numbers**: @ref number_integer_t, @ref number_unsigned_t,
  13478. @ref number_float_t, and all convertible number types such as `int`,
  13479. `size_t`, `int64_t`, `float` or `double` can be used.
  13480. - **boolean**: @ref boolean_t / `bool` can be used.
  13481. See the examples below.
  13482. @tparam CompatibleType a type such that:
  13483. - @a CompatibleType is not derived from `std::istream`,
  13484. - @a CompatibleType is not @ref basic_json (to avoid hijacking copy/move
  13485. constructors),
  13486. - @a CompatibleType is not a different @ref basic_json type (i.e. with different template arguments)
  13487. - @a CompatibleType is not a @ref basic_json nested type (e.g.,
  13488. @ref json_pointer, @ref iterator, etc ...)
  13489. - @ref @ref json_serializer<U> has a
  13490. `to_json(basic_json_t&, CompatibleType&&)` method
  13491. @tparam U = `uncvref_t<CompatibleType>`
  13492. @param[in] val the value to be forwarded to the respective constructor
  13493. @complexity Usually linear in the size of the passed @a val, also
  13494. depending on the implementation of the called `to_json()`
  13495. method.
  13496. @exceptionsafety Depends on the called constructor. For types directly
  13497. supported by the library (i.e., all types for which no `to_json()` function
  13498. was provided), strong guarantee holds: if an exception is thrown, there are
  13499. no changes to any JSON value.
  13500. @liveexample{The following code shows the constructor with several
  13501. compatible types.,basic_json__CompatibleType}
  13502. @since version 2.1.0
  13503. */
  13504. template <typename CompatibleType,
  13505. typename U = detail::uncvref_t<CompatibleType>,
  13506. detail::enable_if_t<
  13507. not detail::is_basic_json<U>::value and detail::is_compatible_type<basic_json_t, U>::value, int> = 0>
  13508. basic_json(CompatibleType && val) noexcept(noexcept(
  13509. JSONSerializer<U>::to_json(std::declval<basic_json_t&>(),
  13510. std::forward<CompatibleType>(val))))
  13511. {
  13512. JSONSerializer<U>::to_json(*this, std::forward<CompatibleType>(val));
  13513. assert_invariant();
  13514. }
  13515. /*!
  13516. @brief create a JSON value from an existing one
  13517. This is a constructor for existing @ref basic_json types.
  13518. It does not hijack copy/move constructors, since the parameter has different
  13519. template arguments than the current ones.
  13520. The constructor tries to convert the internal @ref m_value of the parameter.
  13521. @tparam BasicJsonType a type such that:
  13522. - @a BasicJsonType is a @ref basic_json type.
  13523. - @a BasicJsonType has different template arguments than @ref basic_json_t.
  13524. @param[in] val the @ref basic_json value to be converted.
  13525. @complexity Usually linear in the size of the passed @a val, also
  13526. depending on the implementation of the called `to_json()`
  13527. method.
  13528. @exceptionsafety Depends on the called constructor. For types directly
  13529. supported by the library (i.e., all types for which no `to_json()` function
  13530. was provided), strong guarantee holds: if an exception is thrown, there are
  13531. no changes to any JSON value.
  13532. @since version 3.2.0
  13533. */
  13534. template <typename BasicJsonType,
  13535. detail::enable_if_t<
  13536. detail::is_basic_json<BasicJsonType>::value and not std::is_same<basic_json, BasicJsonType>::value, int> = 0>
  13537. basic_json(const BasicJsonType& val)
  13538. {
  13539. using other_boolean_t = typename BasicJsonType::boolean_t;
  13540. using other_number_float_t = typename BasicJsonType::number_float_t;
  13541. using other_number_integer_t = typename BasicJsonType::number_integer_t;
  13542. using other_number_unsigned_t = typename BasicJsonType::number_unsigned_t;
  13543. using other_string_t = typename BasicJsonType::string_t;
  13544. using other_object_t = typename BasicJsonType::object_t;
  13545. using other_array_t = typename BasicJsonType::array_t;
  13546. switch (val.type())
  13547. {
  13548. case value_t::boolean:
  13549. JSONSerializer<other_boolean_t>::to_json(*this, val.template get<other_boolean_t>());
  13550. break;
  13551. case value_t::number_float:
  13552. JSONSerializer<other_number_float_t>::to_json(*this, val.template get<other_number_float_t>());
  13553. break;
  13554. case value_t::number_integer:
  13555. JSONSerializer<other_number_integer_t>::to_json(*this, val.template get<other_number_integer_t>());
  13556. break;
  13557. case value_t::number_unsigned:
  13558. JSONSerializer<other_number_unsigned_t>::to_json(*this, val.template get<other_number_unsigned_t>());
  13559. break;
  13560. case value_t::string:
  13561. JSONSerializer<other_string_t>::to_json(*this, val.template get_ref<const other_string_t&>());
  13562. break;
  13563. case value_t::object:
  13564. JSONSerializer<other_object_t>::to_json(*this, val.template get_ref<const other_object_t&>());
  13565. break;
  13566. case value_t::array:
  13567. JSONSerializer<other_array_t>::to_json(*this, val.template get_ref<const other_array_t&>());
  13568. break;
  13569. case value_t::null:
  13570. *this = nullptr;
  13571. break;
  13572. case value_t::discarded:
  13573. m_type = value_t::discarded;
  13574. break;
  13575. default: // LCOV_EXCL_LINE
  13576. assert(false); // LCOV_EXCL_LINE
  13577. }
  13578. assert_invariant();
  13579. }
  13580. /*!
  13581. @brief create a container (array or object) from an initializer list
  13582. Creates a JSON value of type array or object from the passed initializer
  13583. list @a init. In case @a type_deduction is `true` (default), the type of
  13584. the JSON value to be created is deducted from the initializer list @a init
  13585. according to the following rules:
  13586. 1. If the list is empty, an empty JSON object value `{}` is created.
  13587. 2. If the list consists of pairs whose first element is a string, a JSON
  13588. object value is created where the first elements of the pairs are
  13589. treated as keys and the second elements are as values.
  13590. 3. In all other cases, an array is created.
  13591. The rules aim to create the best fit between a C++ initializer list and
  13592. JSON values. The rationale is as follows:
  13593. 1. The empty initializer list is written as `{}` which is exactly an empty
  13594. JSON object.
  13595. 2. C++ has no way of describing mapped types other than to list a list of
  13596. pairs. As JSON requires that keys must be of type string, rule 2 is the
  13597. weakest constraint one can pose on initializer lists to interpret them
  13598. as an object.
  13599. 3. In all other cases, the initializer list could not be interpreted as
  13600. JSON object type, so interpreting it as JSON array type is safe.
  13601. With the rules described above, the following JSON values cannot be
  13602. expressed by an initializer list:
  13603. - the empty array (`[]`): use @ref array(initializer_list_t)
  13604. with an empty initializer list in this case
  13605. - arrays whose elements satisfy rule 2: use @ref
  13606. array(initializer_list_t) with the same initializer list
  13607. in this case
  13608. @note When used without parentheses around an empty initializer list, @ref
  13609. basic_json() is called instead of this function, yielding the JSON null
  13610. value.
  13611. @param[in] init initializer list with JSON values
  13612. @param[in] type_deduction internal parameter; when set to `true`, the type
  13613. of the JSON value is deducted from the initializer list @a init; when set
  13614. to `false`, the type provided via @a manual_type is forced. This mode is
  13615. used by the functions @ref array(initializer_list_t) and
  13616. @ref object(initializer_list_t).
  13617. @param[in] manual_type internal parameter; when @a type_deduction is set
  13618. to `false`, the created JSON value will use the provided type (only @ref
  13619. value_t::array and @ref value_t::object are valid); when @a type_deduction
  13620. is set to `true`, this parameter has no effect
  13621. @throw type_error.301 if @a type_deduction is `false`, @a manual_type is
  13622. `value_t::object`, but @a init contains an element which is not a pair
  13623. whose first element is a string. In this case, the constructor could not
  13624. create an object. If @a type_deduction would have be `true`, an array
  13625. would have been created. See @ref object(initializer_list_t)
  13626. for an example.
  13627. @complexity Linear in the size of the initializer list @a init.
  13628. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  13629. changes to any JSON value.
  13630. @liveexample{The example below shows how JSON values are created from
  13631. initializer lists.,basic_json__list_init_t}
  13632. @sa @ref array(initializer_list_t) -- create a JSON array
  13633. value from an initializer list
  13634. @sa @ref object(initializer_list_t) -- create a JSON object
  13635. value from an initializer list
  13636. @since version 1.0.0
  13637. */
  13638. basic_json(initializer_list_t init,
  13639. bool type_deduction = true,
  13640. value_t manual_type = value_t::array)
  13641. {
  13642. // check if each element is an array with two elements whose first
  13643. // element is a string
  13644. bool is_an_object = std::all_of(init.begin(), init.end(),
  13645. [](const detail::json_ref<basic_json>& element_ref)
  13646. {
  13647. return element_ref->is_array() and element_ref->size() == 2 and (*element_ref)[0].is_string();
  13648. });
  13649. // adjust type if type deduction is not wanted
  13650. if (not type_deduction)
  13651. {
  13652. // if array is wanted, do not create an object though possible
  13653. if (manual_type == value_t::array)
  13654. {
  13655. is_an_object = false;
  13656. }
  13657. // if object is wanted but impossible, throw an exception
  13658. if (JSON_HEDLEY_UNLIKELY(manual_type == value_t::object and not is_an_object))
  13659. {
  13660. JSON_THROW(type_error::create(301, "cannot create object from initializer list"));
  13661. }
  13662. }
  13663. if (is_an_object)
  13664. {
  13665. // the initializer list is a list of pairs -> create object
  13666. m_type = value_t::object;
  13667. m_value = value_t::object;
  13668. std::for_each(init.begin(), init.end(), [this](const detail::json_ref<basic_json>& element_ref)
  13669. {
  13670. auto element = element_ref.moved_or_copied();
  13671. m_value.object->emplace(
  13672. std::move(*((*element.m_value.array)[0].m_value.string)),
  13673. std::move((*element.m_value.array)[1]));
  13674. });
  13675. }
  13676. else
  13677. {
  13678. // the initializer list describes an array -> create array
  13679. m_type = value_t::array;
  13680. m_value.array = create<array_t>(init.begin(), init.end());
  13681. }
  13682. assert_invariant();
  13683. }
  13684. /*!
  13685. @brief explicitly create an array from an initializer list
  13686. Creates a JSON array value from a given initializer list. That is, given a
  13687. list of values `a, b, c`, creates the JSON value `[a, b, c]`. If the
  13688. initializer list is empty, the empty array `[]` is created.
  13689. @note This function is only needed to express two edge cases that cannot
  13690. be realized with the initializer list constructor (@ref
  13691. basic_json(initializer_list_t, bool, value_t)). These cases
  13692. are:
  13693. 1. creating an array whose elements are all pairs whose first element is a
  13694. string -- in this case, the initializer list constructor would create an
  13695. object, taking the first elements as keys
  13696. 2. creating an empty array -- passing the empty initializer list to the
  13697. initializer list constructor yields an empty object
  13698. @param[in] init initializer list with JSON values to create an array from
  13699. (optional)
  13700. @return JSON array value
  13701. @complexity Linear in the size of @a init.
  13702. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  13703. changes to any JSON value.
  13704. @liveexample{The following code shows an example for the `array`
  13705. function.,array}
  13706. @sa @ref basic_json(initializer_list_t, bool, value_t) --
  13707. create a JSON value from an initializer list
  13708. @sa @ref object(initializer_list_t) -- create a JSON object
  13709. value from an initializer list
  13710. @since version 1.0.0
  13711. */
  13712. JSON_HEDLEY_WARN_UNUSED_RESULT
  13713. static basic_json array(initializer_list_t init = {})
  13714. {
  13715. return basic_json(init, false, value_t::array);
  13716. }
  13717. /*!
  13718. @brief explicitly create an object from an initializer list
  13719. Creates a JSON object value from a given initializer list. The initializer
  13720. lists elements must be pairs, and their first elements must be strings. If
  13721. the initializer list is empty, the empty object `{}` is created.
  13722. @note This function is only added for symmetry reasons. In contrast to the
  13723. related function @ref array(initializer_list_t), there are
  13724. no cases which can only be expressed by this function. That is, any
  13725. initializer list @a init can also be passed to the initializer list
  13726. constructor @ref basic_json(initializer_list_t, bool, value_t).
  13727. @param[in] init initializer list to create an object from (optional)
  13728. @return JSON object value
  13729. @throw type_error.301 if @a init is not a list of pairs whose first
  13730. elements are strings. In this case, no object can be created. When such a
  13731. value is passed to @ref basic_json(initializer_list_t, bool, value_t),
  13732. an array would have been created from the passed initializer list @a init.
  13733. See example below.
  13734. @complexity Linear in the size of @a init.
  13735. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  13736. changes to any JSON value.
  13737. @liveexample{The following code shows an example for the `object`
  13738. function.,object}
  13739. @sa @ref basic_json(initializer_list_t, bool, value_t) --
  13740. create a JSON value from an initializer list
  13741. @sa @ref array(initializer_list_t) -- create a JSON array
  13742. value from an initializer list
  13743. @since version 1.0.0
  13744. */
  13745. JSON_HEDLEY_WARN_UNUSED_RESULT
  13746. static basic_json object(initializer_list_t init = {})
  13747. {
  13748. return basic_json(init, false, value_t::object);
  13749. }
  13750. /*!
  13751. @brief construct an array with count copies of given value
  13752. Constructs a JSON array value by creating @a cnt copies of a passed value.
  13753. In case @a cnt is `0`, an empty array is created.
  13754. @param[in] cnt the number of JSON copies of @a val to create
  13755. @param[in] val the JSON value to copy
  13756. @post `std::distance(begin(),end()) == cnt` holds.
  13757. @complexity Linear in @a cnt.
  13758. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  13759. changes to any JSON value.
  13760. @liveexample{The following code shows examples for the @ref
  13761. basic_json(size_type\, const basic_json&)
  13762. constructor.,basic_json__size_type_basic_json}
  13763. @since version 1.0.0
  13764. */
  13765. basic_json(size_type cnt, const basic_json& val)
  13766. : m_type(value_t::array)
  13767. {
  13768. m_value.array = create<array_t>(cnt, val);
  13769. assert_invariant();
  13770. }
  13771. /*!
  13772. @brief construct a JSON container given an iterator range
  13773. Constructs the JSON value with the contents of the range `[first, last)`.
  13774. The semantics depends on the different types a JSON value can have:
  13775. - In case of a null type, invalid_iterator.206 is thrown.
  13776. - In case of other primitive types (number, boolean, or string), @a first
  13777. must be `begin()` and @a last must be `end()`. In this case, the value is
  13778. copied. Otherwise, invalid_iterator.204 is thrown.
  13779. - In case of structured types (array, object), the constructor behaves as
  13780. similar versions for `std::vector` or `std::map`; that is, a JSON array
  13781. or object is constructed from the values in the range.
  13782. @tparam InputIT an input iterator type (@ref iterator or @ref
  13783. const_iterator)
  13784. @param[in] first begin of the range to copy from (included)
  13785. @param[in] last end of the range to copy from (excluded)
  13786. @pre Iterators @a first and @a last must be initialized. **This
  13787. precondition is enforced with an assertion (see warning).** If
  13788. assertions are switched off, a violation of this precondition yields
  13789. undefined behavior.
  13790. @pre Range `[first, last)` is valid. Usually, this precondition cannot be
  13791. checked efficiently. Only certain edge cases are detected; see the
  13792. description of the exceptions below. A violation of this precondition
  13793. yields undefined behavior.
  13794. @warning A precondition is enforced with a runtime assertion that will
  13795. result in calling `std::abort` if this precondition is not met.
  13796. Assertions can be disabled by defining `NDEBUG` at compile time.
  13797. See https://en.cppreference.com/w/cpp/error/assert for more
  13798. information.
  13799. @throw invalid_iterator.201 if iterators @a first and @a last are not
  13800. compatible (i.e., do not belong to the same JSON value). In this case,
  13801. the range `[first, last)` is undefined.
  13802. @throw invalid_iterator.204 if iterators @a first and @a last belong to a
  13803. primitive type (number, boolean, or string), but @a first does not point
  13804. to the first element any more. In this case, the range `[first, last)` is
  13805. undefined. See example code below.
  13806. @throw invalid_iterator.206 if iterators @a first and @a last belong to a
  13807. null value. In this case, the range `[first, last)` is undefined.
  13808. @complexity Linear in distance between @a first and @a last.
  13809. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  13810. changes to any JSON value.
  13811. @liveexample{The example below shows several ways to create JSON values by
  13812. specifying a subrange with iterators.,basic_json__InputIt_InputIt}
  13813. @since version 1.0.0
  13814. */
  13815. template<class InputIT, typename std::enable_if<
  13816. std::is_same<InputIT, typename basic_json_t::iterator>::value or
  13817. std::is_same<InputIT, typename basic_json_t::const_iterator>::value, int>::type = 0>
  13818. basic_json(InputIT first, InputIT last)
  13819. {
  13820. assert(first.m_object != nullptr);
  13821. assert(last.m_object != nullptr);
  13822. // make sure iterator fits the current value
  13823. if (JSON_HEDLEY_UNLIKELY(first.m_object != last.m_object))
  13824. {
  13825. JSON_THROW(invalid_iterator::create(201, "iterators are not compatible"));
  13826. }
  13827. // copy type from first iterator
  13828. m_type = first.m_object->m_type;
  13829. // check if iterator range is complete for primitive values
  13830. switch (m_type)
  13831. {
  13832. case value_t::boolean:
  13833. case value_t::number_float:
  13834. case value_t::number_integer:
  13835. case value_t::number_unsigned:
  13836. case value_t::string:
  13837. {
  13838. if (JSON_HEDLEY_UNLIKELY(not first.m_it.primitive_iterator.is_begin()
  13839. or not last.m_it.primitive_iterator.is_end()))
  13840. {
  13841. JSON_THROW(invalid_iterator::create(204, "iterators out of range"));
  13842. }
  13843. break;
  13844. }
  13845. default:
  13846. break;
  13847. }
  13848. switch (m_type)
  13849. {
  13850. case value_t::number_integer:
  13851. {
  13852. m_value.number_integer = first.m_object->m_value.number_integer;
  13853. break;
  13854. }
  13855. case value_t::number_unsigned:
  13856. {
  13857. m_value.number_unsigned = first.m_object->m_value.number_unsigned;
  13858. break;
  13859. }
  13860. case value_t::number_float:
  13861. {
  13862. m_value.number_float = first.m_object->m_value.number_float;
  13863. break;
  13864. }
  13865. case value_t::boolean:
  13866. {
  13867. m_value.boolean = first.m_object->m_value.boolean;
  13868. break;
  13869. }
  13870. case value_t::string:
  13871. {
  13872. m_value = *first.m_object->m_value.string;
  13873. break;
  13874. }
  13875. case value_t::object:
  13876. {
  13877. m_value.object = create<object_t>(first.m_it.object_iterator,
  13878. last.m_it.object_iterator);
  13879. break;
  13880. }
  13881. case value_t::array:
  13882. {
  13883. m_value.array = create<array_t>(first.m_it.array_iterator,
  13884. last.m_it.array_iterator);
  13885. break;
  13886. }
  13887. default:
  13888. JSON_THROW(invalid_iterator::create(206, "cannot construct with iterators from " +
  13889. std::string(first.m_object->type_name())));
  13890. }
  13891. assert_invariant();
  13892. }
  13893. ///////////////////////////////////////
  13894. // other constructors and destructor //
  13895. ///////////////////////////////////////
  13896. /// @private
  13897. basic_json(const detail::json_ref<basic_json>& ref)
  13898. : basic_json(ref.moved_or_copied())
  13899. {}
  13900. /*!
  13901. @brief copy constructor
  13902. Creates a copy of a given JSON value.
  13903. @param[in] other the JSON value to copy
  13904. @post `*this == other`
  13905. @complexity Linear in the size of @a other.
  13906. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  13907. changes to any JSON value.
  13908. @requirement This function helps `basic_json` satisfying the
  13909. [Container](https://en.cppreference.com/w/cpp/named_req/Container)
  13910. requirements:
  13911. - The complexity is linear.
  13912. - As postcondition, it holds: `other == basic_json(other)`.
  13913. @liveexample{The following code shows an example for the copy
  13914. constructor.,basic_json__basic_json}
  13915. @since version 1.0.0
  13916. */
  13917. basic_json(const basic_json& other)
  13918. : m_type(other.m_type)
  13919. {
  13920. // check of passed value is valid
  13921. other.assert_invariant();
  13922. switch (m_type)
  13923. {
  13924. case value_t::object:
  13925. {
  13926. m_value = *other.m_value.object;
  13927. break;
  13928. }
  13929. case value_t::array:
  13930. {
  13931. m_value = *other.m_value.array;
  13932. break;
  13933. }
  13934. case value_t::string:
  13935. {
  13936. m_value = *other.m_value.string;
  13937. break;
  13938. }
  13939. case value_t::boolean:
  13940. {
  13941. m_value = other.m_value.boolean;
  13942. break;
  13943. }
  13944. case value_t::number_integer:
  13945. {
  13946. m_value = other.m_value.number_integer;
  13947. break;
  13948. }
  13949. case value_t::number_unsigned:
  13950. {
  13951. m_value = other.m_value.number_unsigned;
  13952. break;
  13953. }
  13954. case value_t::number_float:
  13955. {
  13956. m_value = other.m_value.number_float;
  13957. break;
  13958. }
  13959. default:
  13960. break;
  13961. }
  13962. assert_invariant();
  13963. }
  13964. /*!
  13965. @brief move constructor
  13966. Move constructor. Constructs a JSON value with the contents of the given
  13967. value @a other using move semantics. It "steals" the resources from @a
  13968. other and leaves it as JSON null value.
  13969. @param[in,out] other value to move to this object
  13970. @post `*this` has the same value as @a other before the call.
  13971. @post @a other is a JSON null value.
  13972. @complexity Constant.
  13973. @exceptionsafety No-throw guarantee: this constructor never throws
  13974. exceptions.
  13975. @requirement This function helps `basic_json` satisfying the
  13976. [MoveConstructible](https://en.cppreference.com/w/cpp/named_req/MoveConstructible)
  13977. requirements.
  13978. @liveexample{The code below shows the move constructor explicitly called
  13979. via std::move.,basic_json__moveconstructor}
  13980. @since version 1.0.0
  13981. */
  13982. basic_json(basic_json&& other) noexcept
  13983. : m_type(std::move(other.m_type)),
  13984. m_value(std::move(other.m_value))
  13985. {
  13986. // check that passed value is valid
  13987. other.assert_invariant();
  13988. // invalidate payload
  13989. other.m_type = value_t::null;
  13990. other.m_value = {};
  13991. assert_invariant();
  13992. }
  13993. /*!
  13994. @brief copy assignment
  13995. Copy assignment operator. Copies a JSON value via the "copy and swap"
  13996. strategy: It is expressed in terms of the copy constructor, destructor,
  13997. and the `swap()` member function.
  13998. @param[in] other value to copy from
  13999. @complexity Linear.
  14000. @requirement This function helps `basic_json` satisfying the
  14001. [Container](https://en.cppreference.com/w/cpp/named_req/Container)
  14002. requirements:
  14003. - The complexity is linear.
  14004. @liveexample{The code below shows and example for the copy assignment. It
  14005. creates a copy of value `a` which is then swapped with `b`. Finally\, the
  14006. copy of `a` (which is the null value after the swap) is
  14007. destroyed.,basic_json__copyassignment}
  14008. @since version 1.0.0
  14009. */
  14010. basic_json& operator=(basic_json other) noexcept (
  14011. std::is_nothrow_move_constructible<value_t>::value and
  14012. std::is_nothrow_move_assignable<value_t>::value and
  14013. std::is_nothrow_move_constructible<json_value>::value and
  14014. std::is_nothrow_move_assignable<json_value>::value
  14015. )
  14016. {
  14017. // check that passed value is valid
  14018. other.assert_invariant();
  14019. using std::swap;
  14020. swap(m_type, other.m_type);
  14021. swap(m_value, other.m_value);
  14022. assert_invariant();
  14023. return *this;
  14024. }
  14025. /*!
  14026. @brief destructor
  14027. Destroys the JSON value and frees all allocated memory.
  14028. @complexity Linear.
  14029. @requirement This function helps `basic_json` satisfying the
  14030. [Container](https://en.cppreference.com/w/cpp/named_req/Container)
  14031. requirements:
  14032. - The complexity is linear.
  14033. - All stored elements are destroyed and all memory is freed.
  14034. @since version 1.0.0
  14035. */
  14036. ~basic_json() noexcept
  14037. {
  14038. assert_invariant();
  14039. m_value.destroy(m_type);
  14040. }
  14041. /// @}
  14042. public:
  14043. ///////////////////////
  14044. // object inspection //
  14045. ///////////////////////
  14046. /// @name object inspection
  14047. /// Functions to inspect the type of a JSON value.
  14048. /// @{
  14049. /*!
  14050. @brief serialization
  14051. Serialization function for JSON values. The function tries to mimic
  14052. Python's `json.dumps()` function, and currently supports its @a indent
  14053. and @a ensure_ascii parameters.
  14054. @param[in] indent If indent is nonnegative, then array elements and object
  14055. members will be pretty-printed with that indent level. An indent level of
  14056. `0` will only insert newlines. `-1` (the default) selects the most compact
  14057. representation.
  14058. @param[in] indent_char The character to use for indentation if @a indent is
  14059. greater than `0`. The default is ` ` (space).
  14060. @param[in] ensure_ascii If @a ensure_ascii is true, all non-ASCII characters
  14061. in the output are escaped with `\uXXXX` sequences, and the result consists
  14062. of ASCII characters only.
  14063. @param[in] error_handler how to react on decoding errors; there are three
  14064. possible values: `strict` (throws and exception in case a decoding error
  14065. occurs; default), `replace` (replace invalid UTF-8 sequences with U+FFFD),
  14066. and `ignore` (ignore invalid UTF-8 sequences during serialization).
  14067. @return string containing the serialization of the JSON value
  14068. @throw type_error.316 if a string stored inside the JSON value is not
  14069. UTF-8 encoded
  14070. @complexity Linear.
  14071. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  14072. changes in the JSON value.
  14073. @liveexample{The following example shows the effect of different @a indent\,
  14074. @a indent_char\, and @a ensure_ascii parameters to the result of the
  14075. serialization.,dump}
  14076. @see https://docs.python.org/2/library/json.html#json.dump
  14077. @since version 1.0.0; indentation character @a indent_char, option
  14078. @a ensure_ascii and exceptions added in version 3.0.0; error
  14079. handlers added in version 3.4.0.
  14080. */
  14081. string_t dump(const int indent = -1,
  14082. const char indent_char = ' ',
  14083. const bool ensure_ascii = false,
  14084. const error_handler_t error_handler = error_handler_t::strict) const
  14085. {
  14086. string_t result;
  14087. serializer s(detail::output_adapter<char, string_t>(result), indent_char, error_handler);
  14088. if (indent >= 0)
  14089. {
  14090. s.dump(*this, true, ensure_ascii, static_cast<unsigned int>(indent));
  14091. }
  14092. else
  14093. {
  14094. s.dump(*this, false, ensure_ascii, 0);
  14095. }
  14096. return result;
  14097. }
  14098. /*!
  14099. @brief return the type of the JSON value (explicit)
  14100. Return the type of the JSON value as a value from the @ref value_t
  14101. enumeration.
  14102. @return the type of the JSON value
  14103. Value type | return value
  14104. ------------------------- | -------------------------
  14105. null | value_t::null
  14106. boolean | value_t::boolean
  14107. string | value_t::string
  14108. number (integer) | value_t::number_integer
  14109. number (unsigned integer) | value_t::number_unsigned
  14110. number (floating-point) | value_t::number_float
  14111. object | value_t::object
  14112. array | value_t::array
  14113. discarded | value_t::discarded
  14114. @complexity Constant.
  14115. @exceptionsafety No-throw guarantee: this member function never throws
  14116. exceptions.
  14117. @liveexample{The following code exemplifies `type()` for all JSON
  14118. types.,type}
  14119. @sa @ref operator value_t() -- return the type of the JSON value (implicit)
  14120. @sa @ref type_name() -- return the type as string
  14121. @since version 1.0.0
  14122. */
  14123. constexpr value_t type() const noexcept
  14124. {
  14125. return m_type;
  14126. }
  14127. /*!
  14128. @brief return whether type is primitive
  14129. This function returns true if and only if the JSON type is primitive
  14130. (string, number, boolean, or null).
  14131. @return `true` if type is primitive (string, number, boolean, or null),
  14132. `false` otherwise.
  14133. @complexity Constant.
  14134. @exceptionsafety No-throw guarantee: this member function never throws
  14135. exceptions.
  14136. @liveexample{The following code exemplifies `is_primitive()` for all JSON
  14137. types.,is_primitive}
  14138. @sa @ref is_structured() -- returns whether JSON value is structured
  14139. @sa @ref is_null() -- returns whether JSON value is `null`
  14140. @sa @ref is_string() -- returns whether JSON value is a string
  14141. @sa @ref is_boolean() -- returns whether JSON value is a boolean
  14142. @sa @ref is_number() -- returns whether JSON value is a number
  14143. @since version 1.0.0
  14144. */
  14145. constexpr bool is_primitive() const noexcept
  14146. {
  14147. return is_null() or is_string() or is_boolean() or is_number();
  14148. }
  14149. /*!
  14150. @brief return whether type is structured
  14151. This function returns true if and only if the JSON type is structured
  14152. (array or object).
  14153. @return `true` if type is structured (array or object), `false` otherwise.
  14154. @complexity Constant.
  14155. @exceptionsafety No-throw guarantee: this member function never throws
  14156. exceptions.
  14157. @liveexample{The following code exemplifies `is_structured()` for all JSON
  14158. types.,is_structured}
  14159. @sa @ref is_primitive() -- returns whether value is primitive
  14160. @sa @ref is_array() -- returns whether value is an array
  14161. @sa @ref is_object() -- returns whether value is an object
  14162. @since version 1.0.0
  14163. */
  14164. constexpr bool is_structured() const noexcept
  14165. {
  14166. return is_array() or is_object();
  14167. }
  14168. /*!
  14169. @brief return whether value is null
  14170. This function returns true if and only if the JSON value is null.
  14171. @return `true` if type is null, `false` otherwise.
  14172. @complexity Constant.
  14173. @exceptionsafety No-throw guarantee: this member function never throws
  14174. exceptions.
  14175. @liveexample{The following code exemplifies `is_null()` for all JSON
  14176. types.,is_null}
  14177. @since version 1.0.0
  14178. */
  14179. constexpr bool is_null() const noexcept
  14180. {
  14181. return m_type == value_t::null;
  14182. }
  14183. /*!
  14184. @brief return whether value is a boolean
  14185. This function returns true if and only if the JSON value is a boolean.
  14186. @return `true` if type is boolean, `false` otherwise.
  14187. @complexity Constant.
  14188. @exceptionsafety No-throw guarantee: this member function never throws
  14189. exceptions.
  14190. @liveexample{The following code exemplifies `is_boolean()` for all JSON
  14191. types.,is_boolean}
  14192. @since version 1.0.0
  14193. */
  14194. constexpr bool is_boolean() const noexcept
  14195. {
  14196. return m_type == value_t::boolean;
  14197. }
  14198. /*!
  14199. @brief return whether value is a number
  14200. This function returns true if and only if the JSON value is a number. This
  14201. includes both integer (signed and unsigned) and floating-point values.
  14202. @return `true` if type is number (regardless whether integer, unsigned
  14203. integer or floating-type), `false` otherwise.
  14204. @complexity Constant.
  14205. @exceptionsafety No-throw guarantee: this member function never throws
  14206. exceptions.
  14207. @liveexample{The following code exemplifies `is_number()` for all JSON
  14208. types.,is_number}
  14209. @sa @ref is_number_integer() -- check if value is an integer or unsigned
  14210. integer number
  14211. @sa @ref is_number_unsigned() -- check if value is an unsigned integer
  14212. number
  14213. @sa @ref is_number_float() -- check if value is a floating-point number
  14214. @since version 1.0.0
  14215. */
  14216. constexpr bool is_number() const noexcept
  14217. {
  14218. return is_number_integer() or is_number_float();
  14219. }
  14220. /*!
  14221. @brief return whether value is an integer number
  14222. This function returns true if and only if the JSON value is a signed or
  14223. unsigned integer number. This excludes floating-point values.
  14224. @return `true` if type is an integer or unsigned integer number, `false`
  14225. otherwise.
  14226. @complexity Constant.
  14227. @exceptionsafety No-throw guarantee: this member function never throws
  14228. exceptions.
  14229. @liveexample{The following code exemplifies `is_number_integer()` for all
  14230. JSON types.,is_number_integer}
  14231. @sa @ref is_number() -- check if value is a number
  14232. @sa @ref is_number_unsigned() -- check if value is an unsigned integer
  14233. number
  14234. @sa @ref is_number_float() -- check if value is a floating-point number
  14235. @since version 1.0.0
  14236. */
  14237. constexpr bool is_number_integer() const noexcept
  14238. {
  14239. return m_type == value_t::number_integer or m_type == value_t::number_unsigned;
  14240. }
  14241. /*!
  14242. @brief return whether value is an unsigned integer number
  14243. This function returns true if and only if the JSON value is an unsigned
  14244. integer number. This excludes floating-point and signed integer values.
  14245. @return `true` if type is an unsigned integer number, `false` otherwise.
  14246. @complexity Constant.
  14247. @exceptionsafety No-throw guarantee: this member function never throws
  14248. exceptions.
  14249. @liveexample{The following code exemplifies `is_number_unsigned()` for all
  14250. JSON types.,is_number_unsigned}
  14251. @sa @ref is_number() -- check if value is a number
  14252. @sa @ref is_number_integer() -- check if value is an integer or unsigned
  14253. integer number
  14254. @sa @ref is_number_float() -- check if value is a floating-point number
  14255. @since version 2.0.0
  14256. */
  14257. constexpr bool is_number_unsigned() const noexcept
  14258. {
  14259. return m_type == value_t::number_unsigned;
  14260. }
  14261. /*!
  14262. @brief return whether value is a floating-point number
  14263. This function returns true if and only if the JSON value is a
  14264. floating-point number. This excludes signed and unsigned integer values.
  14265. @return `true` if type is a floating-point number, `false` otherwise.
  14266. @complexity Constant.
  14267. @exceptionsafety No-throw guarantee: this member function never throws
  14268. exceptions.
  14269. @liveexample{The following code exemplifies `is_number_float()` for all
  14270. JSON types.,is_number_float}
  14271. @sa @ref is_number() -- check if value is number
  14272. @sa @ref is_number_integer() -- check if value is an integer number
  14273. @sa @ref is_number_unsigned() -- check if value is an unsigned integer
  14274. number
  14275. @since version 1.0.0
  14276. */
  14277. constexpr bool is_number_float() const noexcept
  14278. {
  14279. return m_type == value_t::number_float;
  14280. }
  14281. /*!
  14282. @brief return whether value is an object
  14283. This function returns true if and only if the JSON value is an object.
  14284. @return `true` if type is object, `false` otherwise.
  14285. @complexity Constant.
  14286. @exceptionsafety No-throw guarantee: this member function never throws
  14287. exceptions.
  14288. @liveexample{The following code exemplifies `is_object()` for all JSON
  14289. types.,is_object}
  14290. @since version 1.0.0
  14291. */
  14292. constexpr bool is_object() const noexcept
  14293. {
  14294. return m_type == value_t::object;
  14295. }
  14296. /*!
  14297. @brief return whether value is an array
  14298. This function returns true if and only if the JSON value is an array.
  14299. @return `true` if type is array, `false` otherwise.
  14300. @complexity Constant.
  14301. @exceptionsafety No-throw guarantee: this member function never throws
  14302. exceptions.
  14303. @liveexample{The following code exemplifies `is_array()` for all JSON
  14304. types.,is_array}
  14305. @since version 1.0.0
  14306. */
  14307. constexpr bool is_array() const noexcept
  14308. {
  14309. return m_type == value_t::array;
  14310. }
  14311. /*!
  14312. @brief return whether value is a string
  14313. This function returns true if and only if the JSON value is a string.
  14314. @return `true` if type is string, `false` otherwise.
  14315. @complexity Constant.
  14316. @exceptionsafety No-throw guarantee: this member function never throws
  14317. exceptions.
  14318. @liveexample{The following code exemplifies `is_string()` for all JSON
  14319. types.,is_string}
  14320. @since version 1.0.0
  14321. */
  14322. constexpr bool is_string() const noexcept
  14323. {
  14324. return m_type == value_t::string;
  14325. }
  14326. /*!
  14327. @brief return whether value is discarded
  14328. This function returns true if and only if the JSON value was discarded
  14329. during parsing with a callback function (see @ref parser_callback_t).
  14330. @note This function will always be `false` for JSON values after parsing.
  14331. That is, discarded values can only occur during parsing, but will be
  14332. removed when inside a structured value or replaced by null in other cases.
  14333. @return `true` if type is discarded, `false` otherwise.
  14334. @complexity Constant.
  14335. @exceptionsafety No-throw guarantee: this member function never throws
  14336. exceptions.
  14337. @liveexample{The following code exemplifies `is_discarded()` for all JSON
  14338. types.,is_discarded}
  14339. @since version 1.0.0
  14340. */
  14341. constexpr bool is_discarded() const noexcept
  14342. {
  14343. return m_type == value_t::discarded;
  14344. }
  14345. /*!
  14346. @brief return the type of the JSON value (implicit)
  14347. Implicitly return the type of the JSON value as a value from the @ref
  14348. value_t enumeration.
  14349. @return the type of the JSON value
  14350. @complexity Constant.
  14351. @exceptionsafety No-throw guarantee: this member function never throws
  14352. exceptions.
  14353. @liveexample{The following code exemplifies the @ref value_t operator for
  14354. all JSON types.,operator__value_t}
  14355. @sa @ref type() -- return the type of the JSON value (explicit)
  14356. @sa @ref type_name() -- return the type as string
  14357. @since version 1.0.0
  14358. */
  14359. constexpr operator value_t() const noexcept
  14360. {
  14361. return m_type;
  14362. }
  14363. /// @}
  14364. private:
  14365. //////////////////
  14366. // value access //
  14367. //////////////////
  14368. /// get a boolean (explicit)
  14369. boolean_t get_impl(boolean_t* /*unused*/) const
  14370. {
  14371. if (JSON_HEDLEY_LIKELY(is_boolean()))
  14372. {
  14373. return m_value.boolean;
  14374. }
  14375. JSON_THROW(type_error::create(302, "type must be boolean, but is " + std::string(type_name())));
  14376. }
  14377. /// get a pointer to the value (object)
  14378. object_t* get_impl_ptr(object_t* /*unused*/) noexcept
  14379. {
  14380. return is_object() ? m_value.object : nullptr;
  14381. }
  14382. /// get a pointer to the value (object)
  14383. constexpr const object_t* get_impl_ptr(const object_t* /*unused*/) const noexcept
  14384. {
  14385. return is_object() ? m_value.object : nullptr;
  14386. }
  14387. /// get a pointer to the value (array)
  14388. array_t* get_impl_ptr(array_t* /*unused*/) noexcept
  14389. {
  14390. return is_array() ? m_value.array : nullptr;
  14391. }
  14392. /// get a pointer to the value (array)
  14393. constexpr const array_t* get_impl_ptr(const array_t* /*unused*/) const noexcept
  14394. {
  14395. return is_array() ? m_value.array : nullptr;
  14396. }
  14397. /// get a pointer to the value (string)
  14398. string_t* get_impl_ptr(string_t* /*unused*/) noexcept
  14399. {
  14400. return is_string() ? m_value.string : nullptr;
  14401. }
  14402. /// get a pointer to the value (string)
  14403. constexpr const string_t* get_impl_ptr(const string_t* /*unused*/) const noexcept
  14404. {
  14405. return is_string() ? m_value.string : nullptr;
  14406. }
  14407. /// get a pointer to the value (boolean)
  14408. boolean_t* get_impl_ptr(boolean_t* /*unused*/) noexcept
  14409. {
  14410. return is_boolean() ? &m_value.boolean : nullptr;
  14411. }
  14412. /// get a pointer to the value (boolean)
  14413. constexpr const boolean_t* get_impl_ptr(const boolean_t* /*unused*/) const noexcept
  14414. {
  14415. return is_boolean() ? &m_value.boolean : nullptr;
  14416. }
  14417. /// get a pointer to the value (integer number)
  14418. number_integer_t* get_impl_ptr(number_integer_t* /*unused*/) noexcept
  14419. {
  14420. return is_number_integer() ? &m_value.number_integer : nullptr;
  14421. }
  14422. /// get a pointer to the value (integer number)
  14423. constexpr const number_integer_t* get_impl_ptr(const number_integer_t* /*unused*/) const noexcept
  14424. {
  14425. return is_number_integer() ? &m_value.number_integer : nullptr;
  14426. }
  14427. /// get a pointer to the value (unsigned number)
  14428. number_unsigned_t* get_impl_ptr(number_unsigned_t* /*unused*/) noexcept
  14429. {
  14430. return is_number_unsigned() ? &m_value.number_unsigned : nullptr;
  14431. }
  14432. /// get a pointer to the value (unsigned number)
  14433. constexpr const number_unsigned_t* get_impl_ptr(const number_unsigned_t* /*unused*/) const noexcept
  14434. {
  14435. return is_number_unsigned() ? &m_value.number_unsigned : nullptr;
  14436. }
  14437. /// get a pointer to the value (floating-point number)
  14438. number_float_t* get_impl_ptr(number_float_t* /*unused*/) noexcept
  14439. {
  14440. return is_number_float() ? &m_value.number_float : nullptr;
  14441. }
  14442. /// get a pointer to the value (floating-point number)
  14443. constexpr const number_float_t* get_impl_ptr(const number_float_t* /*unused*/) const noexcept
  14444. {
  14445. return is_number_float() ? &m_value.number_float : nullptr;
  14446. }
  14447. /*!
  14448. @brief helper function to implement get_ref()
  14449. This function helps to implement get_ref() without code duplication for
  14450. const and non-const overloads
  14451. @tparam ThisType will be deduced as `basic_json` or `const basic_json`
  14452. @throw type_error.303 if ReferenceType does not match underlying value
  14453. type of the current JSON
  14454. */
  14455. template<typename ReferenceType, typename ThisType>
  14456. static ReferenceType get_ref_impl(ThisType& obj)
  14457. {
  14458. // delegate the call to get_ptr<>()
  14459. auto ptr = obj.template get_ptr<typename std::add_pointer<ReferenceType>::type>();
  14460. if (JSON_HEDLEY_LIKELY(ptr != nullptr))
  14461. {
  14462. return *ptr;
  14463. }
  14464. JSON_THROW(type_error::create(303, "incompatible ReferenceType for get_ref, actual type is " + std::string(obj.type_name())));
  14465. }
  14466. public:
  14467. /// @name value access
  14468. /// Direct access to the stored value of a JSON value.
  14469. /// @{
  14470. /*!
  14471. @brief get special-case overload
  14472. This overloads avoids a lot of template boilerplate, it can be seen as the
  14473. identity method
  14474. @tparam BasicJsonType == @ref basic_json
  14475. @return a copy of *this
  14476. @complexity Constant.
  14477. @since version 2.1.0
  14478. */
  14479. template<typename BasicJsonType, detail::enable_if_t<
  14480. std::is_same<typename std::remove_const<BasicJsonType>::type, basic_json_t>::value,
  14481. int> = 0>
  14482. basic_json get() const
  14483. {
  14484. return *this;
  14485. }
  14486. /*!
  14487. @brief get special-case overload
  14488. This overloads converts the current @ref basic_json in a different
  14489. @ref basic_json type
  14490. @tparam BasicJsonType == @ref basic_json
  14491. @return a copy of *this, converted into @tparam BasicJsonType
  14492. @complexity Depending on the implementation of the called `from_json()`
  14493. method.
  14494. @since version 3.2.0
  14495. */
  14496. template<typename BasicJsonType, detail::enable_if_t<
  14497. not std::is_same<BasicJsonType, basic_json>::value and
  14498. detail::is_basic_json<BasicJsonType>::value, int> = 0>
  14499. BasicJsonType get() const
  14500. {
  14501. return *this;
  14502. }
  14503. /*!
  14504. @brief get a value (explicit)
  14505. Explicit type conversion between the JSON value and a compatible value
  14506. which is [CopyConstructible](https://en.cppreference.com/w/cpp/named_req/CopyConstructible)
  14507. and [DefaultConstructible](https://en.cppreference.com/w/cpp/named_req/DefaultConstructible).
  14508. The value is converted by calling the @ref json_serializer<ValueType>
  14509. `from_json()` method.
  14510. The function is equivalent to executing
  14511. @code {.cpp}
  14512. ValueType ret;
  14513. JSONSerializer<ValueType>::from_json(*this, ret);
  14514. return ret;
  14515. @endcode
  14516. This overloads is chosen if:
  14517. - @a ValueType is not @ref basic_json,
  14518. - @ref json_serializer<ValueType> has a `from_json()` method of the form
  14519. `void from_json(const basic_json&, ValueType&)`, and
  14520. - @ref json_serializer<ValueType> does not have a `from_json()` method of
  14521. the form `ValueType from_json(const basic_json&)`
  14522. @tparam ValueTypeCV the provided value type
  14523. @tparam ValueType the returned value type
  14524. @return copy of the JSON value, converted to @a ValueType
  14525. @throw what @ref json_serializer<ValueType> `from_json()` method throws
  14526. @liveexample{The example below shows several conversions from JSON values
  14527. to other types. There a few things to note: (1) Floating-point numbers can
  14528. be converted to integers\, (2) A JSON array can be converted to a standard
  14529. `std::vector<short>`\, (3) A JSON object can be converted to C++
  14530. associative containers such as `std::unordered_map<std::string\,
  14531. json>`.,get__ValueType_const}
  14532. @since version 2.1.0
  14533. */
  14534. template<typename ValueTypeCV, typename ValueType = detail::uncvref_t<ValueTypeCV>,
  14535. detail::enable_if_t <
  14536. not detail::is_basic_json<ValueType>::value and
  14537. detail::has_from_json<basic_json_t, ValueType>::value and
  14538. not detail::has_non_default_from_json<basic_json_t, ValueType>::value,
  14539. int> = 0>
  14540. ValueType get() const noexcept(noexcept(
  14541. JSONSerializer<ValueType>::from_json(std::declval<const basic_json_t&>(), std::declval<ValueType&>())))
  14542. {
  14543. // we cannot static_assert on ValueTypeCV being non-const, because
  14544. // there is support for get<const basic_json_t>(), which is why we
  14545. // still need the uncvref
  14546. static_assert(not std::is_reference<ValueTypeCV>::value,
  14547. "get() cannot be used with reference types, you might want to use get_ref()");
  14548. static_assert(std::is_default_constructible<ValueType>::value,
  14549. "types must be DefaultConstructible when used with get()");
  14550. ValueType ret;
  14551. JSONSerializer<ValueType>::from_json(*this, ret);
  14552. return ret;
  14553. }
  14554. /*!
  14555. @brief get a value (explicit); special case
  14556. Explicit type conversion between the JSON value and a compatible value
  14557. which is **not** [CopyConstructible](https://en.cppreference.com/w/cpp/named_req/CopyConstructible)
  14558. and **not** [DefaultConstructible](https://en.cppreference.com/w/cpp/named_req/DefaultConstructible).
  14559. The value is converted by calling the @ref json_serializer<ValueType>
  14560. `from_json()` method.
  14561. The function is equivalent to executing
  14562. @code {.cpp}
  14563. return JSONSerializer<ValueTypeCV>::from_json(*this);
  14564. @endcode
  14565. This overloads is chosen if:
  14566. - @a ValueType is not @ref basic_json and
  14567. - @ref json_serializer<ValueType> has a `from_json()` method of the form
  14568. `ValueType from_json(const basic_json&)`
  14569. @note If @ref json_serializer<ValueType> has both overloads of
  14570. `from_json()`, this one is chosen.
  14571. @tparam ValueTypeCV the provided value type
  14572. @tparam ValueType the returned value type
  14573. @return copy of the JSON value, converted to @a ValueType
  14574. @throw what @ref json_serializer<ValueType> `from_json()` method throws
  14575. @since version 2.1.0
  14576. */
  14577. template<typename ValueTypeCV, typename ValueType = detail::uncvref_t<ValueTypeCV>,
  14578. detail::enable_if_t<not std::is_same<basic_json_t, ValueType>::value and
  14579. detail::has_non_default_from_json<basic_json_t, ValueType>::value,
  14580. int> = 0>
  14581. ValueType get() const noexcept(noexcept(
  14582. JSONSerializer<ValueTypeCV>::from_json(std::declval<const basic_json_t&>())))
  14583. {
  14584. static_assert(not std::is_reference<ValueTypeCV>::value,
  14585. "get() cannot be used with reference types, you might want to use get_ref()");
  14586. return JSONSerializer<ValueTypeCV>::from_json(*this);
  14587. }
  14588. /*!
  14589. @brief get a value (explicit)
  14590. Explicit type conversion between the JSON value and a compatible value.
  14591. The value is filled into the input parameter by calling the @ref json_serializer<ValueType>
  14592. `from_json()` method.
  14593. The function is equivalent to executing
  14594. @code {.cpp}
  14595. ValueType v;
  14596. JSONSerializer<ValueType>::from_json(*this, v);
  14597. @endcode
  14598. This overloads is chosen if:
  14599. - @a ValueType is not @ref basic_json,
  14600. - @ref json_serializer<ValueType> has a `from_json()` method of the form
  14601. `void from_json(const basic_json&, ValueType&)`, and
  14602. @tparam ValueType the input parameter type.
  14603. @return the input parameter, allowing chaining calls.
  14604. @throw what @ref json_serializer<ValueType> `from_json()` method throws
  14605. @liveexample{The example below shows several conversions from JSON values
  14606. to other types. There a few things to note: (1) Floating-point numbers can
  14607. be converted to integers\, (2) A JSON array can be converted to a standard
  14608. `std::vector<short>`\, (3) A JSON object can be converted to C++
  14609. associative containers such as `std::unordered_map<std::string\,
  14610. json>`.,get_to}
  14611. @since version 3.3.0
  14612. */
  14613. template<typename ValueType,
  14614. detail::enable_if_t <
  14615. not detail::is_basic_json<ValueType>::value and
  14616. detail::has_from_json<basic_json_t, ValueType>::value,
  14617. int> = 0>
  14618. ValueType & get_to(ValueType& v) const noexcept(noexcept(
  14619. JSONSerializer<ValueType>::from_json(std::declval<const basic_json_t&>(), v)))
  14620. {
  14621. JSONSerializer<ValueType>::from_json(*this, v);
  14622. return v;
  14623. }
  14624. template <
  14625. typename T, std::size_t N,
  14626. typename Array = T (&)[N],
  14627. detail::enable_if_t <
  14628. detail::has_from_json<basic_json_t, Array>::value, int > = 0 >
  14629. Array get_to(T (&v)[N]) const
  14630. noexcept(noexcept(JSONSerializer<Array>::from_json(
  14631. std::declval<const basic_json_t&>(), v)))
  14632. {
  14633. JSONSerializer<Array>::from_json(*this, v);
  14634. return v;
  14635. }
  14636. /*!
  14637. @brief get a pointer value (implicit)
  14638. Implicit pointer access to the internally stored JSON value. No copies are
  14639. made.
  14640. @warning Writing data to the pointee of the result yields an undefined
  14641. state.
  14642. @tparam PointerType pointer type; must be a pointer to @ref array_t, @ref
  14643. object_t, @ref string_t, @ref boolean_t, @ref number_integer_t,
  14644. @ref number_unsigned_t, or @ref number_float_t. Enforced by a static
  14645. assertion.
  14646. @return pointer to the internally stored JSON value if the requested
  14647. pointer type @a PointerType fits to the JSON value; `nullptr` otherwise
  14648. @complexity Constant.
  14649. @liveexample{The example below shows how pointers to internal values of a
  14650. JSON value can be requested. Note that no type conversions are made and a
  14651. `nullptr` is returned if the value and the requested pointer type does not
  14652. match.,get_ptr}
  14653. @since version 1.0.0
  14654. */
  14655. template<typename PointerType, typename std::enable_if<
  14656. std::is_pointer<PointerType>::value, int>::type = 0>
  14657. auto get_ptr() noexcept -> decltype(std::declval<basic_json_t&>().get_impl_ptr(std::declval<PointerType>()))
  14658. {
  14659. // delegate the call to get_impl_ptr<>()
  14660. return get_impl_ptr(static_cast<PointerType>(nullptr));
  14661. }
  14662. /*!
  14663. @brief get a pointer value (implicit)
  14664. @copydoc get_ptr()
  14665. */
  14666. template<typename PointerType, typename std::enable_if<
  14667. std::is_pointer<PointerType>::value and
  14668. std::is_const<typename std::remove_pointer<PointerType>::type>::value, int>::type = 0>
  14669. constexpr auto get_ptr() const noexcept -> decltype(std::declval<const basic_json_t&>().get_impl_ptr(std::declval<PointerType>()))
  14670. {
  14671. // delegate the call to get_impl_ptr<>() const
  14672. return get_impl_ptr(static_cast<PointerType>(nullptr));
  14673. }
  14674. /*!
  14675. @brief get a pointer value (explicit)
  14676. Explicit pointer access to the internally stored JSON value. No copies are
  14677. made.
  14678. @warning The pointer becomes invalid if the underlying JSON object
  14679. changes.
  14680. @tparam PointerType pointer type; must be a pointer to @ref array_t, @ref
  14681. object_t, @ref string_t, @ref boolean_t, @ref number_integer_t,
  14682. @ref number_unsigned_t, or @ref number_float_t.
  14683. @return pointer to the internally stored JSON value if the requested
  14684. pointer type @a PointerType fits to the JSON value; `nullptr` otherwise
  14685. @complexity Constant.
  14686. @liveexample{The example below shows how pointers to internal values of a
  14687. JSON value can be requested. Note that no type conversions are made and a
  14688. `nullptr` is returned if the value and the requested pointer type does not
  14689. match.,get__PointerType}
  14690. @sa @ref get_ptr() for explicit pointer-member access
  14691. @since version 1.0.0
  14692. */
  14693. template<typename PointerType, typename std::enable_if<
  14694. std::is_pointer<PointerType>::value, int>::type = 0>
  14695. auto get() noexcept -> decltype(std::declval<basic_json_t&>().template get_ptr<PointerType>())
  14696. {
  14697. // delegate the call to get_ptr
  14698. return get_ptr<PointerType>();
  14699. }
  14700. /*!
  14701. @brief get a pointer value (explicit)
  14702. @copydoc get()
  14703. */
  14704. template<typename PointerType, typename std::enable_if<
  14705. std::is_pointer<PointerType>::value, int>::type = 0>
  14706. constexpr auto get() const noexcept -> decltype(std::declval<const basic_json_t&>().template get_ptr<PointerType>())
  14707. {
  14708. // delegate the call to get_ptr
  14709. return get_ptr<PointerType>();
  14710. }
  14711. /*!
  14712. @brief get a reference value (implicit)
  14713. Implicit reference access to the internally stored JSON value. No copies
  14714. are made.
  14715. @warning Writing data to the referee of the result yields an undefined
  14716. state.
  14717. @tparam ReferenceType reference type; must be a reference to @ref array_t,
  14718. @ref object_t, @ref string_t, @ref boolean_t, @ref number_integer_t, or
  14719. @ref number_float_t. Enforced by static assertion.
  14720. @return reference to the internally stored JSON value if the requested
  14721. reference type @a ReferenceType fits to the JSON value; throws
  14722. type_error.303 otherwise
  14723. @throw type_error.303 in case passed type @a ReferenceType is incompatible
  14724. with the stored JSON value; see example below
  14725. @complexity Constant.
  14726. @liveexample{The example shows several calls to `get_ref()`.,get_ref}
  14727. @since version 1.1.0
  14728. */
  14729. template<typename ReferenceType, typename std::enable_if<
  14730. std::is_reference<ReferenceType>::value, int>::type = 0>
  14731. ReferenceType get_ref()
  14732. {
  14733. // delegate call to get_ref_impl
  14734. return get_ref_impl<ReferenceType>(*this);
  14735. }
  14736. /*!
  14737. @brief get a reference value (implicit)
  14738. @copydoc get_ref()
  14739. */
  14740. template<typename ReferenceType, typename std::enable_if<
  14741. std::is_reference<ReferenceType>::value and
  14742. std::is_const<typename std::remove_reference<ReferenceType>::type>::value, int>::type = 0>
  14743. ReferenceType get_ref() const
  14744. {
  14745. // delegate call to get_ref_impl
  14746. return get_ref_impl<ReferenceType>(*this);
  14747. }
  14748. /*!
  14749. @brief get a value (implicit)
  14750. Implicit type conversion between the JSON value and a compatible value.
  14751. The call is realized by calling @ref get() const.
  14752. @tparam ValueType non-pointer type compatible to the JSON value, for
  14753. instance `int` for JSON integer numbers, `bool` for JSON booleans, or
  14754. `std::vector` types for JSON arrays. The character type of @ref string_t
  14755. as well as an initializer list of this type is excluded to avoid
  14756. ambiguities as these types implicitly convert to `std::string`.
  14757. @return copy of the JSON value, converted to type @a ValueType
  14758. @throw type_error.302 in case passed type @a ValueType is incompatible
  14759. to the JSON value type (e.g., the JSON value is of type boolean, but a
  14760. string is requested); see example below
  14761. @complexity Linear in the size of the JSON value.
  14762. @liveexample{The example below shows several conversions from JSON values
  14763. to other types. There a few things to note: (1) Floating-point numbers can
  14764. be converted to integers\, (2) A JSON array can be converted to a standard
  14765. `std::vector<short>`\, (3) A JSON object can be converted to C++
  14766. associative containers such as `std::unordered_map<std::string\,
  14767. json>`.,operator__ValueType}
  14768. @since version 1.0.0
  14769. */
  14770. template < typename ValueType, typename std::enable_if <
  14771. not std::is_pointer<ValueType>::value and
  14772. not std::is_same<ValueType, detail::json_ref<basic_json>>::value and
  14773. not std::is_same<ValueType, typename string_t::value_type>::value and
  14774. not detail::is_basic_json<ValueType>::value
  14775. #ifndef _MSC_VER // fix for issue #167 operator<< ambiguity under VS2015
  14776. and not std::is_same<ValueType, std::initializer_list<typename string_t::value_type>>::value
  14777. #if defined(JSON_HAS_CPP_17) && (defined(__GNUC__) || (defined(_MSC_VER) and _MSC_VER <= 1914))
  14778. and not std::is_same<ValueType, typename std::string_view>::value
  14779. #endif
  14780. #endif
  14781. and detail::is_detected<detail::get_template_function, const basic_json_t&, ValueType>::value
  14782. , int >::type = 0 >
  14783. operator ValueType() const
  14784. {
  14785. // delegate the call to get<>() const
  14786. return get<ValueType>();
  14787. }
  14788. /// @}
  14789. ////////////////////
  14790. // element access //
  14791. ////////////////////
  14792. /// @name element access
  14793. /// Access to the JSON value.
  14794. /// @{
  14795. /*!
  14796. @brief access specified array element with bounds checking
  14797. Returns a reference to the element at specified location @a idx, with
  14798. bounds checking.
  14799. @param[in] idx index of the element to access
  14800. @return reference to the element at index @a idx
  14801. @throw type_error.304 if the JSON value is not an array; in this case,
  14802. calling `at` with an index makes no sense. See example below.
  14803. @throw out_of_range.401 if the index @a idx is out of range of the array;
  14804. that is, `idx >= size()`. See example below.
  14805. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  14806. changes in the JSON value.
  14807. @complexity Constant.
  14808. @since version 1.0.0
  14809. @liveexample{The example below shows how array elements can be read and
  14810. written using `at()`. It also demonstrates the different exceptions that
  14811. can be thrown.,at__size_type}
  14812. */
  14813. reference at(size_type idx)
  14814. {
  14815. // at only works for arrays
  14816. if (JSON_HEDLEY_LIKELY(is_array()))
  14817. {
  14818. JSON_TRY
  14819. {
  14820. return m_value.array->at(idx);
  14821. }
  14822. JSON_CATCH (std::out_of_range&)
  14823. {
  14824. // create better exception explanation
  14825. JSON_THROW(out_of_range::create(401, "array index " + std::to_string(idx) + " is out of range"));
  14826. }
  14827. }
  14828. else
  14829. {
  14830. JSON_THROW(type_error::create(304, "cannot use at() with " + std::string(type_name())));
  14831. }
  14832. }
  14833. /*!
  14834. @brief access specified array element with bounds checking
  14835. Returns a const reference to the element at specified location @a idx,
  14836. with bounds checking.
  14837. @param[in] idx index of the element to access
  14838. @return const reference to the element at index @a idx
  14839. @throw type_error.304 if the JSON value is not an array; in this case,
  14840. calling `at` with an index makes no sense. See example below.
  14841. @throw out_of_range.401 if the index @a idx is out of range of the array;
  14842. that is, `idx >= size()`. See example below.
  14843. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  14844. changes in the JSON value.
  14845. @complexity Constant.
  14846. @since version 1.0.0
  14847. @liveexample{The example below shows how array elements can be read using
  14848. `at()`. It also demonstrates the different exceptions that can be thrown.,
  14849. at__size_type_const}
  14850. */
  14851. const_reference at(size_type idx) const
  14852. {
  14853. // at only works for arrays
  14854. if (JSON_HEDLEY_LIKELY(is_array()))
  14855. {
  14856. JSON_TRY
  14857. {
  14858. return m_value.array->at(idx);
  14859. }
  14860. JSON_CATCH (std::out_of_range&)
  14861. {
  14862. // create better exception explanation
  14863. JSON_THROW(out_of_range::create(401, "array index " + std::to_string(idx) + " is out of range"));
  14864. }
  14865. }
  14866. else
  14867. {
  14868. JSON_THROW(type_error::create(304, "cannot use at() with " + std::string(type_name())));
  14869. }
  14870. }
  14871. /*!
  14872. @brief access specified object element with bounds checking
  14873. Returns a reference to the element at with specified key @a key, with
  14874. bounds checking.
  14875. @param[in] key key of the element to access
  14876. @return reference to the element at key @a key
  14877. @throw type_error.304 if the JSON value is not an object; in this case,
  14878. calling `at` with a key makes no sense. See example below.
  14879. @throw out_of_range.403 if the key @a key is is not stored in the object;
  14880. that is, `find(key) == end()`. See example below.
  14881. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  14882. changes in the JSON value.
  14883. @complexity Logarithmic in the size of the container.
  14884. @sa @ref operator[](const typename object_t::key_type&) for unchecked
  14885. access by reference
  14886. @sa @ref value() for access by value with a default value
  14887. @since version 1.0.0
  14888. @liveexample{The example below shows how object elements can be read and
  14889. written using `at()`. It also demonstrates the different exceptions that
  14890. can be thrown.,at__object_t_key_type}
  14891. */
  14892. reference at(const typename object_t::key_type& key)
  14893. {
  14894. // at only works for objects
  14895. if (JSON_HEDLEY_LIKELY(is_object()))
  14896. {
  14897. JSON_TRY
  14898. {
  14899. return m_value.object->at(key);
  14900. }
  14901. JSON_CATCH (std::out_of_range&)
  14902. {
  14903. // create better exception explanation
  14904. JSON_THROW(out_of_range::create(403, "key '" + key + "' not found"));
  14905. }
  14906. }
  14907. else
  14908. {
  14909. JSON_THROW(type_error::create(304, "cannot use at() with " + std::string(type_name())));
  14910. }
  14911. }
  14912. /*!
  14913. @brief access specified object element with bounds checking
  14914. Returns a const reference to the element at with specified key @a key,
  14915. with bounds checking.
  14916. @param[in] key key of the element to access
  14917. @return const reference to the element at key @a key
  14918. @throw type_error.304 if the JSON value is not an object; in this case,
  14919. calling `at` with a key makes no sense. See example below.
  14920. @throw out_of_range.403 if the key @a key is is not stored in the object;
  14921. that is, `find(key) == end()`. See example below.
  14922. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  14923. changes in the JSON value.
  14924. @complexity Logarithmic in the size of the container.
  14925. @sa @ref operator[](const typename object_t::key_type&) for unchecked
  14926. access by reference
  14927. @sa @ref value() for access by value with a default value
  14928. @since version 1.0.0
  14929. @liveexample{The example below shows how object elements can be read using
  14930. `at()`. It also demonstrates the different exceptions that can be thrown.,
  14931. at__object_t_key_type_const}
  14932. */
  14933. const_reference at(const typename object_t::key_type& key) const
  14934. {
  14935. // at only works for objects
  14936. if (JSON_HEDLEY_LIKELY(is_object()))
  14937. {
  14938. JSON_TRY
  14939. {
  14940. return m_value.object->at(key);
  14941. }
  14942. JSON_CATCH (std::out_of_range&)
  14943. {
  14944. // create better exception explanation
  14945. JSON_THROW(out_of_range::create(403, "key '" + key + "' not found"));
  14946. }
  14947. }
  14948. else
  14949. {
  14950. JSON_THROW(type_error::create(304, "cannot use at() with " + std::string(type_name())));
  14951. }
  14952. }
  14953. /*!
  14954. @brief access specified array element
  14955. Returns a reference to the element at specified location @a idx.
  14956. @note If @a idx is beyond the range of the array (i.e., `idx >= size()`),
  14957. then the array is silently filled up with `null` values to make `idx` a
  14958. valid reference to the last stored element.
  14959. @param[in] idx index of the element to access
  14960. @return reference to the element at index @a idx
  14961. @throw type_error.305 if the JSON value is not an array or null; in that
  14962. cases, using the [] operator with an index makes no sense.
  14963. @complexity Constant if @a idx is in the range of the array. Otherwise
  14964. linear in `idx - size()`.
  14965. @liveexample{The example below shows how array elements can be read and
  14966. written using `[]` operator. Note the addition of `null`
  14967. values.,operatorarray__size_type}
  14968. @since version 1.0.0
  14969. */
  14970. reference operator[](size_type idx)
  14971. {
  14972. // implicitly convert null value to an empty array
  14973. if (is_null())
  14974. {
  14975. m_type = value_t::array;
  14976. m_value.array = create<array_t>();
  14977. assert_invariant();
  14978. }
  14979. // operator[] only works for arrays
  14980. if (JSON_HEDLEY_LIKELY(is_array()))
  14981. {
  14982. // fill up array with null values if given idx is outside range
  14983. if (idx >= m_value.array->size())
  14984. {
  14985. m_value.array->insert(m_value.array->end(),
  14986. idx - m_value.array->size() + 1,
  14987. basic_json());
  14988. }
  14989. return m_value.array->operator[](idx);
  14990. }
  14991. JSON_THROW(type_error::create(305, "cannot use operator[] with a numeric argument with " + std::string(type_name())));
  14992. }
  14993. /*!
  14994. @brief access specified array element
  14995. Returns a const reference to the element at specified location @a idx.
  14996. @param[in] idx index of the element to access
  14997. @return const reference to the element at index @a idx
  14998. @throw type_error.305 if the JSON value is not an array; in that case,
  14999. using the [] operator with an index makes no sense.
  15000. @complexity Constant.
  15001. @liveexample{The example below shows how array elements can be read using
  15002. the `[]` operator.,operatorarray__size_type_const}
  15003. @since version 1.0.0
  15004. */
  15005. const_reference operator[](size_type idx) const
  15006. {
  15007. // const operator[] only works for arrays
  15008. if (JSON_HEDLEY_LIKELY(is_array()))
  15009. {
  15010. return m_value.array->operator[](idx);
  15011. }
  15012. JSON_THROW(type_error::create(305, "cannot use operator[] with a numeric argument with " + std::string(type_name())));
  15013. }
  15014. /*!
  15015. @brief access specified object element
  15016. Returns a reference to the element at with specified key @a key.
  15017. @note If @a key is not found in the object, then it is silently added to
  15018. the object and filled with a `null` value to make `key` a valid reference.
  15019. In case the value was `null` before, it is converted to an object.
  15020. @param[in] key key of the element to access
  15021. @return reference to the element at key @a key
  15022. @throw type_error.305 if the JSON value is not an object or null; in that
  15023. cases, using the [] operator with a key makes no sense.
  15024. @complexity Logarithmic in the size of the container.
  15025. @liveexample{The example below shows how object elements can be read and
  15026. written using the `[]` operator.,operatorarray__key_type}
  15027. @sa @ref at(const typename object_t::key_type&) for access by reference
  15028. with range checking
  15029. @sa @ref value() for access by value with a default value
  15030. @since version 1.0.0
  15031. */
  15032. reference operator[](const typename object_t::key_type& key)
  15033. {
  15034. // implicitly convert null value to an empty object
  15035. if (is_null())
  15036. {
  15037. m_type = value_t::object;
  15038. m_value.object = create<object_t>();
  15039. assert_invariant();
  15040. }
  15041. // operator[] only works for objects
  15042. if (JSON_HEDLEY_LIKELY(is_object()))
  15043. {
  15044. return m_value.object->operator[](key);
  15045. }
  15046. JSON_THROW(type_error::create(305, "cannot use operator[] with a string argument with " + std::string(type_name())));
  15047. }
  15048. /*!
  15049. @brief read-only access specified object element
  15050. Returns a const reference to the element at with specified key @a key. No
  15051. bounds checking is performed.
  15052. @warning If the element with key @a key does not exist, the behavior is
  15053. undefined.
  15054. @param[in] key key of the element to access
  15055. @return const reference to the element at key @a key
  15056. @pre The element with key @a key must exist. **This precondition is
  15057. enforced with an assertion.**
  15058. @throw type_error.305 if the JSON value is not an object; in that case,
  15059. using the [] operator with a key makes no sense.
  15060. @complexity Logarithmic in the size of the container.
  15061. @liveexample{The example below shows how object elements can be read using
  15062. the `[]` operator.,operatorarray__key_type_const}
  15063. @sa @ref at(const typename object_t::key_type&) for access by reference
  15064. with range checking
  15065. @sa @ref value() for access by value with a default value
  15066. @since version 1.0.0
  15067. */
  15068. const_reference operator[](const typename object_t::key_type& key) const
  15069. {
  15070. // const operator[] only works for objects
  15071. if (JSON_HEDLEY_LIKELY(is_object()))
  15072. {
  15073. assert(m_value.object->find(key) != m_value.object->end());
  15074. return m_value.object->find(key)->second;
  15075. }
  15076. JSON_THROW(type_error::create(305, "cannot use operator[] with a string argument with " + std::string(type_name())));
  15077. }
  15078. /*!
  15079. @brief access specified object element
  15080. Returns a reference to the element at with specified key @a key.
  15081. @note If @a key is not found in the object, then it is silently added to
  15082. the object and filled with a `null` value to make `key` a valid reference.
  15083. In case the value was `null` before, it is converted to an object.
  15084. @param[in] key key of the element to access
  15085. @return reference to the element at key @a key
  15086. @throw type_error.305 if the JSON value is not an object or null; in that
  15087. cases, using the [] operator with a key makes no sense.
  15088. @complexity Logarithmic in the size of the container.
  15089. @liveexample{The example below shows how object elements can be read and
  15090. written using the `[]` operator.,operatorarray__key_type}
  15091. @sa @ref at(const typename object_t::key_type&) for access by reference
  15092. with range checking
  15093. @sa @ref value() for access by value with a default value
  15094. @since version 1.1.0
  15095. */
  15096. template<typename T>
  15097. JSON_HEDLEY_NON_NULL(2)
  15098. reference operator[](T* key)
  15099. {
  15100. // implicitly convert null to object
  15101. if (is_null())
  15102. {
  15103. m_type = value_t::object;
  15104. m_value = value_t::object;
  15105. assert_invariant();
  15106. }
  15107. // at only works for objects
  15108. if (JSON_HEDLEY_LIKELY(is_object()))
  15109. {
  15110. return m_value.object->operator[](key);
  15111. }
  15112. JSON_THROW(type_error::create(305, "cannot use operator[] with a string argument with " + std::string(type_name())));
  15113. }
  15114. /*!
  15115. @brief read-only access specified object element
  15116. Returns a const reference to the element at with specified key @a key. No
  15117. bounds checking is performed.
  15118. @warning If the element with key @a key does not exist, the behavior is
  15119. undefined.
  15120. @param[in] key key of the element to access
  15121. @return const reference to the element at key @a key
  15122. @pre The element with key @a key must exist. **This precondition is
  15123. enforced with an assertion.**
  15124. @throw type_error.305 if the JSON value is not an object; in that case,
  15125. using the [] operator with a key makes no sense.
  15126. @complexity Logarithmic in the size of the container.
  15127. @liveexample{The example below shows how object elements can be read using
  15128. the `[]` operator.,operatorarray__key_type_const}
  15129. @sa @ref at(const typename object_t::key_type&) for access by reference
  15130. with range checking
  15131. @sa @ref value() for access by value with a default value
  15132. @since version 1.1.0
  15133. */
  15134. template<typename T>
  15135. JSON_HEDLEY_NON_NULL(2)
  15136. const_reference operator[](T* key) const
  15137. {
  15138. // at only works for objects
  15139. if (JSON_HEDLEY_LIKELY(is_object()))
  15140. {
  15141. assert(m_value.object->find(key) != m_value.object->end());
  15142. return m_value.object->find(key)->second;
  15143. }
  15144. JSON_THROW(type_error::create(305, "cannot use operator[] with a string argument with " + std::string(type_name())));
  15145. }
  15146. /*!
  15147. @brief access specified object element with default value
  15148. Returns either a copy of an object's element at the specified key @a key
  15149. or a given default value if no element with key @a key exists.
  15150. The function is basically equivalent to executing
  15151. @code {.cpp}
  15152. try {
  15153. return at(key);
  15154. } catch(out_of_range) {
  15155. return default_value;
  15156. }
  15157. @endcode
  15158. @note Unlike @ref at(const typename object_t::key_type&), this function
  15159. does not throw if the given key @a key was not found.
  15160. @note Unlike @ref operator[](const typename object_t::key_type& key), this
  15161. function does not implicitly add an element to the position defined by @a
  15162. key. This function is furthermore also applicable to const objects.
  15163. @param[in] key key of the element to access
  15164. @param[in] default_value the value to return if @a key is not found
  15165. @tparam ValueType type compatible to JSON values, for instance `int` for
  15166. JSON integer numbers, `bool` for JSON booleans, or `std::vector` types for
  15167. JSON arrays. Note the type of the expected value at @a key and the default
  15168. value @a default_value must be compatible.
  15169. @return copy of the element at key @a key or @a default_value if @a key
  15170. is not found
  15171. @throw type_error.302 if @a default_value does not match the type of the
  15172. value at @a key
  15173. @throw type_error.306 if the JSON value is not an object; in that case,
  15174. using `value()` with a key makes no sense.
  15175. @complexity Logarithmic in the size of the container.
  15176. @liveexample{The example below shows how object elements can be queried
  15177. with a default value.,basic_json__value}
  15178. @sa @ref at(const typename object_t::key_type&) for access by reference
  15179. with range checking
  15180. @sa @ref operator[](const typename object_t::key_type&) for unchecked
  15181. access by reference
  15182. @since version 1.0.0
  15183. */
  15184. template<class ValueType, typename std::enable_if<
  15185. std::is_convertible<basic_json_t, ValueType>::value, int>::type = 0>
  15186. ValueType value(const typename object_t::key_type& key, const ValueType& default_value) const
  15187. {
  15188. // at only works for objects
  15189. if (JSON_HEDLEY_LIKELY(is_object()))
  15190. {
  15191. // if key is found, return value and given default value otherwise
  15192. const auto it = find(key);
  15193. if (it != end())
  15194. {
  15195. return *it;
  15196. }
  15197. return default_value;
  15198. }
  15199. JSON_THROW(type_error::create(306, "cannot use value() with " + std::string(type_name())));
  15200. }
  15201. /*!
  15202. @brief overload for a default value of type const char*
  15203. @copydoc basic_json::value(const typename object_t::key_type&, const ValueType&) const
  15204. */
  15205. string_t value(const typename object_t::key_type& key, const char* default_value) const
  15206. {
  15207. return value(key, string_t(default_value));
  15208. }
  15209. /*!
  15210. @brief access specified object element via JSON Pointer with default value
  15211. Returns either a copy of an object's element at the specified key @a key
  15212. or a given default value if no element with key @a key exists.
  15213. The function is basically equivalent to executing
  15214. @code {.cpp}
  15215. try {
  15216. return at(ptr);
  15217. } catch(out_of_range) {
  15218. return default_value;
  15219. }
  15220. @endcode
  15221. @note Unlike @ref at(const json_pointer&), this function does not throw
  15222. if the given key @a key was not found.
  15223. @param[in] ptr a JSON pointer to the element to access
  15224. @param[in] default_value the value to return if @a ptr found no value
  15225. @tparam ValueType type compatible to JSON values, for instance `int` for
  15226. JSON integer numbers, `bool` for JSON booleans, or `std::vector` types for
  15227. JSON arrays. Note the type of the expected value at @a key and the default
  15228. value @a default_value must be compatible.
  15229. @return copy of the element at key @a key or @a default_value if @a key
  15230. is not found
  15231. @throw type_error.302 if @a default_value does not match the type of the
  15232. value at @a ptr
  15233. @throw type_error.306 if the JSON value is not an object; in that case,
  15234. using `value()` with a key makes no sense.
  15235. @complexity Logarithmic in the size of the container.
  15236. @liveexample{The example below shows how object elements can be queried
  15237. with a default value.,basic_json__value_ptr}
  15238. @sa @ref operator[](const json_pointer&) for unchecked access by reference
  15239. @since version 2.0.2
  15240. */
  15241. template<class ValueType, typename std::enable_if<
  15242. std::is_convertible<basic_json_t, ValueType>::value, int>::type = 0>
  15243. ValueType value(const json_pointer& ptr, const ValueType& default_value) const
  15244. {
  15245. // at only works for objects
  15246. if (JSON_HEDLEY_LIKELY(is_object()))
  15247. {
  15248. // if pointer resolves a value, return it or use default value
  15249. JSON_TRY
  15250. {
  15251. return ptr.get_checked(this);
  15252. }
  15253. JSON_INTERNAL_CATCH (out_of_range&)
  15254. {
  15255. return default_value;
  15256. }
  15257. }
  15258. JSON_THROW(type_error::create(306, "cannot use value() with " + std::string(type_name())));
  15259. }
  15260. /*!
  15261. @brief overload for a default value of type const char*
  15262. @copydoc basic_json::value(const json_pointer&, ValueType) const
  15263. */
  15264. JSON_HEDLEY_NON_NULL(3)
  15265. string_t value(const json_pointer& ptr, const char* default_value) const
  15266. {
  15267. return value(ptr, string_t(default_value));
  15268. }
  15269. /*!
  15270. @brief access the first element
  15271. Returns a reference to the first element in the container. For a JSON
  15272. container `c`, the expression `c.front()` is equivalent to `*c.begin()`.
  15273. @return In case of a structured type (array or object), a reference to the
  15274. first element is returned. In case of number, string, or boolean values, a
  15275. reference to the value is returned.
  15276. @complexity Constant.
  15277. @pre The JSON value must not be `null` (would throw `std::out_of_range`)
  15278. or an empty array or object (undefined behavior, **guarded by
  15279. assertions**).
  15280. @post The JSON value remains unchanged.
  15281. @throw invalid_iterator.214 when called on `null` value
  15282. @liveexample{The following code shows an example for `front()`.,front}
  15283. @sa @ref back() -- access the last element
  15284. @since version 1.0.0
  15285. */
  15286. reference front()
  15287. {
  15288. return *begin();
  15289. }
  15290. /*!
  15291. @copydoc basic_json::front()
  15292. */
  15293. const_reference front() const
  15294. {
  15295. return *cbegin();
  15296. }
  15297. /*!
  15298. @brief access the last element
  15299. Returns a reference to the last element in the container. For a JSON
  15300. container `c`, the expression `c.back()` is equivalent to
  15301. @code {.cpp}
  15302. auto tmp = c.end();
  15303. --tmp;
  15304. return *tmp;
  15305. @endcode
  15306. @return In case of a structured type (array or object), a reference to the
  15307. last element is returned. In case of number, string, or boolean values, a
  15308. reference to the value is returned.
  15309. @complexity Constant.
  15310. @pre The JSON value must not be `null` (would throw `std::out_of_range`)
  15311. or an empty array or object (undefined behavior, **guarded by
  15312. assertions**).
  15313. @post The JSON value remains unchanged.
  15314. @throw invalid_iterator.214 when called on a `null` value. See example
  15315. below.
  15316. @liveexample{The following code shows an example for `back()`.,back}
  15317. @sa @ref front() -- access the first element
  15318. @since version 1.0.0
  15319. */
  15320. reference back()
  15321. {
  15322. auto tmp = end();
  15323. --tmp;
  15324. return *tmp;
  15325. }
  15326. /*!
  15327. @copydoc basic_json::back()
  15328. */
  15329. const_reference back() const
  15330. {
  15331. auto tmp = cend();
  15332. --tmp;
  15333. return *tmp;
  15334. }
  15335. /*!
  15336. @brief remove element given an iterator
  15337. Removes the element specified by iterator @a pos. The iterator @a pos must
  15338. be valid and dereferenceable. Thus the `end()` iterator (which is valid,
  15339. but is not dereferenceable) cannot be used as a value for @a pos.
  15340. If called on a primitive type other than `null`, the resulting JSON value
  15341. will be `null`.
  15342. @param[in] pos iterator to the element to remove
  15343. @return Iterator following the last removed element. If the iterator @a
  15344. pos refers to the last element, the `end()` iterator is returned.
  15345. @tparam IteratorType an @ref iterator or @ref const_iterator
  15346. @post Invalidates iterators and references at or after the point of the
  15347. erase, including the `end()` iterator.
  15348. @throw type_error.307 if called on a `null` value; example: `"cannot use
  15349. erase() with null"`
  15350. @throw invalid_iterator.202 if called on an iterator which does not belong
  15351. to the current JSON value; example: `"iterator does not fit current
  15352. value"`
  15353. @throw invalid_iterator.205 if called on a primitive type with invalid
  15354. iterator (i.e., any iterator which is not `begin()`); example: `"iterator
  15355. out of range"`
  15356. @complexity The complexity depends on the type:
  15357. - objects: amortized constant
  15358. - arrays: linear in distance between @a pos and the end of the container
  15359. - strings: linear in the length of the string
  15360. - other types: constant
  15361. @liveexample{The example shows the result of `erase()` for different JSON
  15362. types.,erase__IteratorType}
  15363. @sa @ref erase(IteratorType, IteratorType) -- removes the elements in
  15364. the given range
  15365. @sa @ref erase(const typename object_t::key_type&) -- removes the element
  15366. from an object at the given key
  15367. @sa @ref erase(const size_type) -- removes the element from an array at
  15368. the given index
  15369. @since version 1.0.0
  15370. */
  15371. template<class IteratorType, typename std::enable_if<
  15372. std::is_same<IteratorType, typename basic_json_t::iterator>::value or
  15373. std::is_same<IteratorType, typename basic_json_t::const_iterator>::value, int>::type
  15374. = 0>
  15375. IteratorType erase(IteratorType pos)
  15376. {
  15377. // make sure iterator fits the current value
  15378. if (JSON_HEDLEY_UNLIKELY(this != pos.m_object))
  15379. {
  15380. JSON_THROW(invalid_iterator::create(202, "iterator does not fit current value"));
  15381. }
  15382. IteratorType result = end();
  15383. switch (m_type)
  15384. {
  15385. case value_t::boolean:
  15386. case value_t::number_float:
  15387. case value_t::number_integer:
  15388. case value_t::number_unsigned:
  15389. case value_t::string:
  15390. {
  15391. if (JSON_HEDLEY_UNLIKELY(not pos.m_it.primitive_iterator.is_begin()))
  15392. {
  15393. JSON_THROW(invalid_iterator::create(205, "iterator out of range"));
  15394. }
  15395. if (is_string())
  15396. {
  15397. AllocatorType<string_t> alloc;
  15398. std::allocator_traits<decltype(alloc)>::destroy(alloc, m_value.string);
  15399. std::allocator_traits<decltype(alloc)>::deallocate(alloc, m_value.string, 1);
  15400. m_value.string = nullptr;
  15401. }
  15402. m_type = value_t::null;
  15403. assert_invariant();
  15404. break;
  15405. }
  15406. case value_t::object:
  15407. {
  15408. result.m_it.object_iterator = m_value.object->erase(pos.m_it.object_iterator);
  15409. break;
  15410. }
  15411. case value_t::array:
  15412. {
  15413. result.m_it.array_iterator = m_value.array->erase(pos.m_it.array_iterator);
  15414. break;
  15415. }
  15416. default:
  15417. JSON_THROW(type_error::create(307, "cannot use erase() with " + std::string(type_name())));
  15418. }
  15419. return result;
  15420. }
  15421. /*!
  15422. @brief remove elements given an iterator range
  15423. Removes the element specified by the range `[first; last)`. The iterator
  15424. @a first does not need to be dereferenceable if `first == last`: erasing
  15425. an empty range is a no-op.
  15426. If called on a primitive type other than `null`, the resulting JSON value
  15427. will be `null`.
  15428. @param[in] first iterator to the beginning of the range to remove
  15429. @param[in] last iterator past the end of the range to remove
  15430. @return Iterator following the last removed element. If the iterator @a
  15431. second refers to the last element, the `end()` iterator is returned.
  15432. @tparam IteratorType an @ref iterator or @ref const_iterator
  15433. @post Invalidates iterators and references at or after the point of the
  15434. erase, including the `end()` iterator.
  15435. @throw type_error.307 if called on a `null` value; example: `"cannot use
  15436. erase() with null"`
  15437. @throw invalid_iterator.203 if called on iterators which does not belong
  15438. to the current JSON value; example: `"iterators do not fit current value"`
  15439. @throw invalid_iterator.204 if called on a primitive type with invalid
  15440. iterators (i.e., if `first != begin()` and `last != end()`); example:
  15441. `"iterators out of range"`
  15442. @complexity The complexity depends on the type:
  15443. - objects: `log(size()) + std::distance(first, last)`
  15444. - arrays: linear in the distance between @a first and @a last, plus linear
  15445. in the distance between @a last and end of the container
  15446. - strings: linear in the length of the string
  15447. - other types: constant
  15448. @liveexample{The example shows the result of `erase()` for different JSON
  15449. types.,erase__IteratorType_IteratorType}
  15450. @sa @ref erase(IteratorType) -- removes the element at a given position
  15451. @sa @ref erase(const typename object_t::key_type&) -- removes the element
  15452. from an object at the given key
  15453. @sa @ref erase(const size_type) -- removes the element from an array at
  15454. the given index
  15455. @since version 1.0.0
  15456. */
  15457. template<class IteratorType, typename std::enable_if<
  15458. std::is_same<IteratorType, typename basic_json_t::iterator>::value or
  15459. std::is_same<IteratorType, typename basic_json_t::const_iterator>::value, int>::type
  15460. = 0>
  15461. IteratorType erase(IteratorType first, IteratorType last)
  15462. {
  15463. // make sure iterator fits the current value
  15464. if (JSON_HEDLEY_UNLIKELY(this != first.m_object or this != last.m_object))
  15465. {
  15466. JSON_THROW(invalid_iterator::create(203, "iterators do not fit current value"));
  15467. }
  15468. IteratorType result = end();
  15469. switch (m_type)
  15470. {
  15471. case value_t::boolean:
  15472. case value_t::number_float:
  15473. case value_t::number_integer:
  15474. case value_t::number_unsigned:
  15475. case value_t::string:
  15476. {
  15477. if (JSON_HEDLEY_LIKELY(not first.m_it.primitive_iterator.is_begin()
  15478. or not last.m_it.primitive_iterator.is_end()))
  15479. {
  15480. JSON_THROW(invalid_iterator::create(204, "iterators out of range"));
  15481. }
  15482. if (is_string())
  15483. {
  15484. AllocatorType<string_t> alloc;
  15485. std::allocator_traits<decltype(alloc)>::destroy(alloc, m_value.string);
  15486. std::allocator_traits<decltype(alloc)>::deallocate(alloc, m_value.string, 1);
  15487. m_value.string = nullptr;
  15488. }
  15489. m_type = value_t::null;
  15490. assert_invariant();
  15491. break;
  15492. }
  15493. case value_t::object:
  15494. {
  15495. result.m_it.object_iterator = m_value.object->erase(first.m_it.object_iterator,
  15496. last.m_it.object_iterator);
  15497. break;
  15498. }
  15499. case value_t::array:
  15500. {
  15501. result.m_it.array_iterator = m_value.array->erase(first.m_it.array_iterator,
  15502. last.m_it.array_iterator);
  15503. break;
  15504. }
  15505. default:
  15506. JSON_THROW(type_error::create(307, "cannot use erase() with " + std::string(type_name())));
  15507. }
  15508. return result;
  15509. }
  15510. /*!
  15511. @brief remove element from a JSON object given a key
  15512. Removes elements from a JSON object with the key value @a key.
  15513. @param[in] key value of the elements to remove
  15514. @return Number of elements removed. If @a ObjectType is the default
  15515. `std::map` type, the return value will always be `0` (@a key was not
  15516. found) or `1` (@a key was found).
  15517. @post References and iterators to the erased elements are invalidated.
  15518. Other references and iterators are not affected.
  15519. @throw type_error.307 when called on a type other than JSON object;
  15520. example: `"cannot use erase() with null"`
  15521. @complexity `log(size()) + count(key)`
  15522. @liveexample{The example shows the effect of `erase()`.,erase__key_type}
  15523. @sa @ref erase(IteratorType) -- removes the element at a given position
  15524. @sa @ref erase(IteratorType, IteratorType) -- removes the elements in
  15525. the given range
  15526. @sa @ref erase(const size_type) -- removes the element from an array at
  15527. the given index
  15528. @since version 1.0.0
  15529. */
  15530. size_type erase(const typename object_t::key_type& key)
  15531. {
  15532. // this erase only works for objects
  15533. if (JSON_HEDLEY_LIKELY(is_object()))
  15534. {
  15535. return m_value.object->erase(key);
  15536. }
  15537. JSON_THROW(type_error::create(307, "cannot use erase() with " + std::string(type_name())));
  15538. }
  15539. /*!
  15540. @brief remove element from a JSON array given an index
  15541. Removes element from a JSON array at the index @a idx.
  15542. @param[in] idx index of the element to remove
  15543. @throw type_error.307 when called on a type other than JSON object;
  15544. example: `"cannot use erase() with null"`
  15545. @throw out_of_range.401 when `idx >= size()`; example: `"array index 17
  15546. is out of range"`
  15547. @complexity Linear in distance between @a idx and the end of the container.
  15548. @liveexample{The example shows the effect of `erase()`.,erase__size_type}
  15549. @sa @ref erase(IteratorType) -- removes the element at a given position
  15550. @sa @ref erase(IteratorType, IteratorType) -- removes the elements in
  15551. the given range
  15552. @sa @ref erase(const typename object_t::key_type&) -- removes the element
  15553. from an object at the given key
  15554. @since version 1.0.0
  15555. */
  15556. void erase(const size_type idx)
  15557. {
  15558. // this erase only works for arrays
  15559. if (JSON_HEDLEY_LIKELY(is_array()))
  15560. {
  15561. if (JSON_HEDLEY_UNLIKELY(idx >= size()))
  15562. {
  15563. JSON_THROW(out_of_range::create(401, "array index " + std::to_string(idx) + " is out of range"));
  15564. }
  15565. m_value.array->erase(m_value.array->begin() + static_cast<difference_type>(idx));
  15566. }
  15567. else
  15568. {
  15569. JSON_THROW(type_error::create(307, "cannot use erase() with " + std::string(type_name())));
  15570. }
  15571. }
  15572. /// @}
  15573. ////////////
  15574. // lookup //
  15575. ////////////
  15576. /// @name lookup
  15577. /// @{
  15578. /*!
  15579. @brief find an element in a JSON object
  15580. Finds an element in a JSON object with key equivalent to @a key. If the
  15581. element is not found or the JSON value is not an object, end() is
  15582. returned.
  15583. @note This method always returns @ref end() when executed on a JSON type
  15584. that is not an object.
  15585. @param[in] key key value of the element to search for.
  15586. @return Iterator to an element with key equivalent to @a key. If no such
  15587. element is found or the JSON value is not an object, past-the-end (see
  15588. @ref end()) iterator is returned.
  15589. @complexity Logarithmic in the size of the JSON object.
  15590. @liveexample{The example shows how `find()` is used.,find__key_type}
  15591. @sa @ref contains(KeyT&&) const -- checks whether a key exists
  15592. @since version 1.0.0
  15593. */
  15594. template<typename KeyT>
  15595. iterator find(KeyT&& key)
  15596. {
  15597. auto result = end();
  15598. if (is_object())
  15599. {
  15600. result.m_it.object_iterator = m_value.object->find(std::forward<KeyT>(key));
  15601. }
  15602. return result;
  15603. }
  15604. /*!
  15605. @brief find an element in a JSON object
  15606. @copydoc find(KeyT&&)
  15607. */
  15608. template<typename KeyT>
  15609. const_iterator find(KeyT&& key) const
  15610. {
  15611. auto result = cend();
  15612. if (is_object())
  15613. {
  15614. result.m_it.object_iterator = m_value.object->find(std::forward<KeyT>(key));
  15615. }
  15616. return result;
  15617. }
  15618. /*!
  15619. @brief returns the number of occurrences of a key in a JSON object
  15620. Returns the number of elements with key @a key. If ObjectType is the
  15621. default `std::map` type, the return value will always be `0` (@a key was
  15622. not found) or `1` (@a key was found).
  15623. @note This method always returns `0` when executed on a JSON type that is
  15624. not an object.
  15625. @param[in] key key value of the element to count
  15626. @return Number of elements with key @a key. If the JSON value is not an
  15627. object, the return value will be `0`.
  15628. @complexity Logarithmic in the size of the JSON object.
  15629. @liveexample{The example shows how `count()` is used.,count}
  15630. @since version 1.0.0
  15631. */
  15632. template<typename KeyT>
  15633. size_type count(KeyT&& key) const
  15634. {
  15635. // return 0 for all nonobject types
  15636. return is_object() ? m_value.object->count(std::forward<KeyT>(key)) : 0;
  15637. }
  15638. /*!
  15639. @brief check the existence of an element in a JSON object
  15640. Check whether an element exists in a JSON object with key equivalent to
  15641. @a key. If the element is not found or the JSON value is not an object,
  15642. false is returned.
  15643. @note This method always returns false when executed on a JSON type
  15644. that is not an object.
  15645. @param[in] key key value to check its existence.
  15646. @return true if an element with specified @a key exists. If no such
  15647. element with such key is found or the JSON value is not an object,
  15648. false is returned.
  15649. @complexity Logarithmic in the size of the JSON object.
  15650. @liveexample{The following code shows an example for `contains()`.,contains}
  15651. @sa @ref find(KeyT&&) -- returns an iterator to an object element
  15652. @sa @ref contains(const json_pointer&) const -- checks the existence for a JSON pointer
  15653. @since version 3.6.0
  15654. */
  15655. template<typename KeyT, typename std::enable_if<
  15656. not std::is_same<KeyT, json_pointer>::value, int>::type = 0>
  15657. bool contains(KeyT && key) const
  15658. {
  15659. return is_object() and m_value.object->find(std::forward<KeyT>(key)) != m_value.object->end();
  15660. }
  15661. /*!
  15662. @brief check the existence of an element in a JSON object given a JSON pointer
  15663. Check wehther the given JSON pointer @a ptr can be resolved in the current
  15664. JSON value.
  15665. @note This method can be executed on any JSON value type.
  15666. @param[in] ptr JSON pointer to check its existence.
  15667. @return true if the JSON pointer can be resolved to a stored value, false
  15668. otherwise.
  15669. @post If `j.contains(ptr)` returns true, it is safe to call `j[ptr]`.
  15670. @throw parse_error.106 if an array index begins with '0'
  15671. @throw parse_error.109 if an array index was not a number
  15672. @complexity Logarithmic in the size of the JSON object.
  15673. @liveexample{The following code shows an example for `contains()`.,contains_json_pointer}
  15674. @sa @ref contains(KeyT &&) const -- checks the existence of a key
  15675. @since version 3.7.0
  15676. */
  15677. bool contains(const json_pointer& ptr) const
  15678. {
  15679. return ptr.contains(this);
  15680. }
  15681. /// @}
  15682. ///////////////
  15683. // iterators //
  15684. ///////////////
  15685. /// @name iterators
  15686. /// @{
  15687. /*!
  15688. @brief returns an iterator to the first element
  15689. Returns an iterator to the first element.
  15690. @image html range-begin-end.svg "Illustration from cppreference.com"
  15691. @return iterator to the first element
  15692. @complexity Constant.
  15693. @requirement This function helps `basic_json` satisfying the
  15694. [Container](https://en.cppreference.com/w/cpp/named_req/Container)
  15695. requirements:
  15696. - The complexity is constant.
  15697. @liveexample{The following code shows an example for `begin()`.,begin}
  15698. @sa @ref cbegin() -- returns a const iterator to the beginning
  15699. @sa @ref end() -- returns an iterator to the end
  15700. @sa @ref cend() -- returns a const iterator to the end
  15701. @since version 1.0.0
  15702. */
  15703. iterator begin() noexcept
  15704. {
  15705. iterator result(this);
  15706. result.set_begin();
  15707. return result;
  15708. }
  15709. /*!
  15710. @copydoc basic_json::cbegin()
  15711. */
  15712. const_iterator begin() const noexcept
  15713. {
  15714. return cbegin();
  15715. }
  15716. /*!
  15717. @brief returns a const iterator to the first element
  15718. Returns a const iterator to the first element.
  15719. @image html range-begin-end.svg "Illustration from cppreference.com"
  15720. @return const iterator to the first element
  15721. @complexity Constant.
  15722. @requirement This function helps `basic_json` satisfying the
  15723. [Container](https://en.cppreference.com/w/cpp/named_req/Container)
  15724. requirements:
  15725. - The complexity is constant.
  15726. - Has the semantics of `const_cast<const basic_json&>(*this).begin()`.
  15727. @liveexample{The following code shows an example for `cbegin()`.,cbegin}
  15728. @sa @ref begin() -- returns an iterator to the beginning
  15729. @sa @ref end() -- returns an iterator to the end
  15730. @sa @ref cend() -- returns a const iterator to the end
  15731. @since version 1.0.0
  15732. */
  15733. const_iterator cbegin() const noexcept
  15734. {
  15735. const_iterator result(this);
  15736. result.set_begin();
  15737. return result;
  15738. }
  15739. /*!
  15740. @brief returns an iterator to one past the last element
  15741. Returns an iterator to one past the last element.
  15742. @image html range-begin-end.svg "Illustration from cppreference.com"
  15743. @return iterator one past the last element
  15744. @complexity Constant.
  15745. @requirement This function helps `basic_json` satisfying the
  15746. [Container](https://en.cppreference.com/w/cpp/named_req/Container)
  15747. requirements:
  15748. - The complexity is constant.
  15749. @liveexample{The following code shows an example for `end()`.,end}
  15750. @sa @ref cend() -- returns a const iterator to the end
  15751. @sa @ref begin() -- returns an iterator to the beginning
  15752. @sa @ref cbegin() -- returns a const iterator to the beginning
  15753. @since version 1.0.0
  15754. */
  15755. iterator end() noexcept
  15756. {
  15757. iterator result(this);
  15758. result.set_end();
  15759. return result;
  15760. }
  15761. /*!
  15762. @copydoc basic_json::cend()
  15763. */
  15764. const_iterator end() const noexcept
  15765. {
  15766. return cend();
  15767. }
  15768. /*!
  15769. @brief returns a const iterator to one past the last element
  15770. Returns a const iterator to one past the last element.
  15771. @image html range-begin-end.svg "Illustration from cppreference.com"
  15772. @return const iterator one past the last element
  15773. @complexity Constant.
  15774. @requirement This function helps `basic_json` satisfying the
  15775. [Container](https://en.cppreference.com/w/cpp/named_req/Container)
  15776. requirements:
  15777. - The complexity is constant.
  15778. - Has the semantics of `const_cast<const basic_json&>(*this).end()`.
  15779. @liveexample{The following code shows an example for `cend()`.,cend}
  15780. @sa @ref end() -- returns an iterator to the end
  15781. @sa @ref begin() -- returns an iterator to the beginning
  15782. @sa @ref cbegin() -- returns a const iterator to the beginning
  15783. @since version 1.0.0
  15784. */
  15785. const_iterator cend() const noexcept
  15786. {
  15787. const_iterator result(this);
  15788. result.set_end();
  15789. return result;
  15790. }
  15791. /*!
  15792. @brief returns an iterator to the reverse-beginning
  15793. Returns an iterator to the reverse-beginning; that is, the last element.
  15794. @image html range-rbegin-rend.svg "Illustration from cppreference.com"
  15795. @complexity Constant.
  15796. @requirement This function helps `basic_json` satisfying the
  15797. [ReversibleContainer](https://en.cppreference.com/w/cpp/named_req/ReversibleContainer)
  15798. requirements:
  15799. - The complexity is constant.
  15800. - Has the semantics of `reverse_iterator(end())`.
  15801. @liveexample{The following code shows an example for `rbegin()`.,rbegin}
  15802. @sa @ref crbegin() -- returns a const reverse iterator to the beginning
  15803. @sa @ref rend() -- returns a reverse iterator to the end
  15804. @sa @ref crend() -- returns a const reverse iterator to the end
  15805. @since version 1.0.0
  15806. */
  15807. reverse_iterator rbegin() noexcept
  15808. {
  15809. return reverse_iterator(end());
  15810. }
  15811. /*!
  15812. @copydoc basic_json::crbegin()
  15813. */
  15814. const_reverse_iterator rbegin() const noexcept
  15815. {
  15816. return crbegin();
  15817. }
  15818. /*!
  15819. @brief returns an iterator to the reverse-end
  15820. Returns an iterator to the reverse-end; that is, one before the first
  15821. element.
  15822. @image html range-rbegin-rend.svg "Illustration from cppreference.com"
  15823. @complexity Constant.
  15824. @requirement This function helps `basic_json` satisfying the
  15825. [ReversibleContainer](https://en.cppreference.com/w/cpp/named_req/ReversibleContainer)
  15826. requirements:
  15827. - The complexity is constant.
  15828. - Has the semantics of `reverse_iterator(begin())`.
  15829. @liveexample{The following code shows an example for `rend()`.,rend}
  15830. @sa @ref crend() -- returns a const reverse iterator to the end
  15831. @sa @ref rbegin() -- returns a reverse iterator to the beginning
  15832. @sa @ref crbegin() -- returns a const reverse iterator to the beginning
  15833. @since version 1.0.0
  15834. */
  15835. reverse_iterator rend() noexcept
  15836. {
  15837. return reverse_iterator(begin());
  15838. }
  15839. /*!
  15840. @copydoc basic_json::crend()
  15841. */
  15842. const_reverse_iterator rend() const noexcept
  15843. {
  15844. return crend();
  15845. }
  15846. /*!
  15847. @brief returns a const reverse iterator to the last element
  15848. Returns a const iterator to the reverse-beginning; that is, the last
  15849. element.
  15850. @image html range-rbegin-rend.svg "Illustration from cppreference.com"
  15851. @complexity Constant.
  15852. @requirement This function helps `basic_json` satisfying the
  15853. [ReversibleContainer](https://en.cppreference.com/w/cpp/named_req/ReversibleContainer)
  15854. requirements:
  15855. - The complexity is constant.
  15856. - Has the semantics of `const_cast<const basic_json&>(*this).rbegin()`.
  15857. @liveexample{The following code shows an example for `crbegin()`.,crbegin}
  15858. @sa @ref rbegin() -- returns a reverse iterator to the beginning
  15859. @sa @ref rend() -- returns a reverse iterator to the end
  15860. @sa @ref crend() -- returns a const reverse iterator to the end
  15861. @since version 1.0.0
  15862. */
  15863. const_reverse_iterator crbegin() const noexcept
  15864. {
  15865. return const_reverse_iterator(cend());
  15866. }
  15867. /*!
  15868. @brief returns a const reverse iterator to one before the first
  15869. Returns a const reverse iterator to the reverse-end; that is, one before
  15870. the first element.
  15871. @image html range-rbegin-rend.svg "Illustration from cppreference.com"
  15872. @complexity Constant.
  15873. @requirement This function helps `basic_json` satisfying the
  15874. [ReversibleContainer](https://en.cppreference.com/w/cpp/named_req/ReversibleContainer)
  15875. requirements:
  15876. - The complexity is constant.
  15877. - Has the semantics of `const_cast<const basic_json&>(*this).rend()`.
  15878. @liveexample{The following code shows an example for `crend()`.,crend}
  15879. @sa @ref rend() -- returns a reverse iterator to the end
  15880. @sa @ref rbegin() -- returns a reverse iterator to the beginning
  15881. @sa @ref crbegin() -- returns a const reverse iterator to the beginning
  15882. @since version 1.0.0
  15883. */
  15884. const_reverse_iterator crend() const noexcept
  15885. {
  15886. return const_reverse_iterator(cbegin());
  15887. }
  15888. public:
  15889. /*!
  15890. @brief wrapper to access iterator member functions in range-based for
  15891. This function allows to access @ref iterator::key() and @ref
  15892. iterator::value() during range-based for loops. In these loops, a
  15893. reference to the JSON values is returned, so there is no access to the
  15894. underlying iterator.
  15895. For loop without iterator_wrapper:
  15896. @code{cpp}
  15897. for (auto it = j_object.begin(); it != j_object.end(); ++it)
  15898. {
  15899. std::cout << "key: " << it.key() << ", value:" << it.value() << '\n';
  15900. }
  15901. @endcode
  15902. Range-based for loop without iterator proxy:
  15903. @code{cpp}
  15904. for (auto it : j_object)
  15905. {
  15906. // "it" is of type json::reference and has no key() member
  15907. std::cout << "value: " << it << '\n';
  15908. }
  15909. @endcode
  15910. Range-based for loop with iterator proxy:
  15911. @code{cpp}
  15912. for (auto it : json::iterator_wrapper(j_object))
  15913. {
  15914. std::cout << "key: " << it.key() << ", value:" << it.value() << '\n';
  15915. }
  15916. @endcode
  15917. @note When iterating over an array, `key()` will return the index of the
  15918. element as string (see example).
  15919. @param[in] ref reference to a JSON value
  15920. @return iteration proxy object wrapping @a ref with an interface to use in
  15921. range-based for loops
  15922. @liveexample{The following code shows how the wrapper is used,iterator_wrapper}
  15923. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  15924. changes in the JSON value.
  15925. @complexity Constant.
  15926. @note The name of this function is not yet final and may change in the
  15927. future.
  15928. @deprecated This stream operator is deprecated and will be removed in
  15929. future 4.0.0 of the library. Please use @ref items() instead;
  15930. that is, replace `json::iterator_wrapper(j)` with `j.items()`.
  15931. */
  15932. JSON_HEDLEY_DEPRECATED(3.1.0)
  15933. static iteration_proxy<iterator> iterator_wrapper(reference ref) noexcept
  15934. {
  15935. return ref.items();
  15936. }
  15937. /*!
  15938. @copydoc iterator_wrapper(reference)
  15939. */
  15940. JSON_HEDLEY_DEPRECATED(3.1.0)
  15941. static iteration_proxy<const_iterator> iterator_wrapper(const_reference ref) noexcept
  15942. {
  15943. return ref.items();
  15944. }
  15945. /*!
  15946. @brief helper to access iterator member functions in range-based for
  15947. This function allows to access @ref iterator::key() and @ref
  15948. iterator::value() during range-based for loops. In these loops, a
  15949. reference to the JSON values is returned, so there is no access to the
  15950. underlying iterator.
  15951. For loop without `items()` function:
  15952. @code{cpp}
  15953. for (auto it = j_object.begin(); it != j_object.end(); ++it)
  15954. {
  15955. std::cout << "key: " << it.key() << ", value:" << it.value() << '\n';
  15956. }
  15957. @endcode
  15958. Range-based for loop without `items()` function:
  15959. @code{cpp}
  15960. for (auto it : j_object)
  15961. {
  15962. // "it" is of type json::reference and has no key() member
  15963. std::cout << "value: " << it << '\n';
  15964. }
  15965. @endcode
  15966. Range-based for loop with `items()` function:
  15967. @code{cpp}
  15968. for (auto& el : j_object.items())
  15969. {
  15970. std::cout << "key: " << el.key() << ", value:" << el.value() << '\n';
  15971. }
  15972. @endcode
  15973. The `items()` function also allows to use
  15974. [structured bindings](https://en.cppreference.com/w/cpp/language/structured_binding)
  15975. (C++17):
  15976. @code{cpp}
  15977. for (auto& [key, val] : j_object.items())
  15978. {
  15979. std::cout << "key: " << key << ", value:" << val << '\n';
  15980. }
  15981. @endcode
  15982. @note When iterating over an array, `key()` will return the index of the
  15983. element as string (see example). For primitive types (e.g., numbers),
  15984. `key()` returns an empty string.
  15985. @return iteration proxy object wrapping @a ref with an interface to use in
  15986. range-based for loops
  15987. @liveexample{The following code shows how the function is used.,items}
  15988. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  15989. changes in the JSON value.
  15990. @complexity Constant.
  15991. @since version 3.1.0, structured bindings support since 3.5.0.
  15992. */
  15993. iteration_proxy<iterator> items() noexcept
  15994. {
  15995. return iteration_proxy<iterator>(*this);
  15996. }
  15997. /*!
  15998. @copydoc items()
  15999. */
  16000. iteration_proxy<const_iterator> items() const noexcept
  16001. {
  16002. return iteration_proxy<const_iterator>(*this);
  16003. }
  16004. /// @}
  16005. //////////////
  16006. // capacity //
  16007. //////////////
  16008. /// @name capacity
  16009. /// @{
  16010. /*!
  16011. @brief checks whether the container is empty.
  16012. Checks if a JSON value has no elements (i.e. whether its @ref size is `0`).
  16013. @return The return value depends on the different types and is
  16014. defined as follows:
  16015. Value type | return value
  16016. ----------- | -------------
  16017. null | `true`
  16018. boolean | `false`
  16019. string | `false`
  16020. number | `false`
  16021. object | result of function `object_t::empty()`
  16022. array | result of function `array_t::empty()`
  16023. @liveexample{The following code uses `empty()` to check if a JSON
  16024. object contains any elements.,empty}
  16025. @complexity Constant, as long as @ref array_t and @ref object_t satisfy
  16026. the Container concept; that is, their `empty()` functions have constant
  16027. complexity.
  16028. @iterators No changes.
  16029. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  16030. @note This function does not return whether a string stored as JSON value
  16031. is empty - it returns whether the JSON container itself is empty which is
  16032. false in the case of a string.
  16033. @requirement This function helps `basic_json` satisfying the
  16034. [Container](https://en.cppreference.com/w/cpp/named_req/Container)
  16035. requirements:
  16036. - The complexity is constant.
  16037. - Has the semantics of `begin() == end()`.
  16038. @sa @ref size() -- returns the number of elements
  16039. @since version 1.0.0
  16040. */
  16041. bool empty() const noexcept
  16042. {
  16043. switch (m_type)
  16044. {
  16045. case value_t::null:
  16046. {
  16047. // null values are empty
  16048. return true;
  16049. }
  16050. case value_t::array:
  16051. {
  16052. // delegate call to array_t::empty()
  16053. return m_value.array->empty();
  16054. }
  16055. case value_t::object:
  16056. {
  16057. // delegate call to object_t::empty()
  16058. return m_value.object->empty();
  16059. }
  16060. default:
  16061. {
  16062. // all other types are nonempty
  16063. return false;
  16064. }
  16065. }
  16066. }
  16067. /*!
  16068. @brief returns the number of elements
  16069. Returns the number of elements in a JSON value.
  16070. @return The return value depends on the different types and is
  16071. defined as follows:
  16072. Value type | return value
  16073. ----------- | -------------
  16074. null | `0`
  16075. boolean | `1`
  16076. string | `1`
  16077. number | `1`
  16078. object | result of function object_t::size()
  16079. array | result of function array_t::size()
  16080. @liveexample{The following code calls `size()` on the different value
  16081. types.,size}
  16082. @complexity Constant, as long as @ref array_t and @ref object_t satisfy
  16083. the Container concept; that is, their size() functions have constant
  16084. complexity.
  16085. @iterators No changes.
  16086. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  16087. @note This function does not return the length of a string stored as JSON
  16088. value - it returns the number of elements in the JSON value which is 1 in
  16089. the case of a string.
  16090. @requirement This function helps `basic_json` satisfying the
  16091. [Container](https://en.cppreference.com/w/cpp/named_req/Container)
  16092. requirements:
  16093. - The complexity is constant.
  16094. - Has the semantics of `std::distance(begin(), end())`.
  16095. @sa @ref empty() -- checks whether the container is empty
  16096. @sa @ref max_size() -- returns the maximal number of elements
  16097. @since version 1.0.0
  16098. */
  16099. size_type size() const noexcept
  16100. {
  16101. switch (m_type)
  16102. {
  16103. case value_t::null:
  16104. {
  16105. // null values are empty
  16106. return 0;
  16107. }
  16108. case value_t::array:
  16109. {
  16110. // delegate call to array_t::size()
  16111. return m_value.array->size();
  16112. }
  16113. case value_t::object:
  16114. {
  16115. // delegate call to object_t::size()
  16116. return m_value.object->size();
  16117. }
  16118. default:
  16119. {
  16120. // all other types have size 1
  16121. return 1;
  16122. }
  16123. }
  16124. }
  16125. /*!
  16126. @brief returns the maximum possible number of elements
  16127. Returns the maximum number of elements a JSON value is able to hold due to
  16128. system or library implementation limitations, i.e. `std::distance(begin(),
  16129. end())` for the JSON value.
  16130. @return The return value depends on the different types and is
  16131. defined as follows:
  16132. Value type | return value
  16133. ----------- | -------------
  16134. null | `0` (same as `size()`)
  16135. boolean | `1` (same as `size()`)
  16136. string | `1` (same as `size()`)
  16137. number | `1` (same as `size()`)
  16138. object | result of function `object_t::max_size()`
  16139. array | result of function `array_t::max_size()`
  16140. @liveexample{The following code calls `max_size()` on the different value
  16141. types. Note the output is implementation specific.,max_size}
  16142. @complexity Constant, as long as @ref array_t and @ref object_t satisfy
  16143. the Container concept; that is, their `max_size()` functions have constant
  16144. complexity.
  16145. @iterators No changes.
  16146. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  16147. @requirement This function helps `basic_json` satisfying the
  16148. [Container](https://en.cppreference.com/w/cpp/named_req/Container)
  16149. requirements:
  16150. - The complexity is constant.
  16151. - Has the semantics of returning `b.size()` where `b` is the largest
  16152. possible JSON value.
  16153. @sa @ref size() -- returns the number of elements
  16154. @since version 1.0.0
  16155. */
  16156. size_type max_size() const noexcept
  16157. {
  16158. switch (m_type)
  16159. {
  16160. case value_t::array:
  16161. {
  16162. // delegate call to array_t::max_size()
  16163. return m_value.array->max_size();
  16164. }
  16165. case value_t::object:
  16166. {
  16167. // delegate call to object_t::max_size()
  16168. return m_value.object->max_size();
  16169. }
  16170. default:
  16171. {
  16172. // all other types have max_size() == size()
  16173. return size();
  16174. }
  16175. }
  16176. }
  16177. /// @}
  16178. ///////////////
  16179. // modifiers //
  16180. ///////////////
  16181. /// @name modifiers
  16182. /// @{
  16183. /*!
  16184. @brief clears the contents
  16185. Clears the content of a JSON value and resets it to the default value as
  16186. if @ref basic_json(value_t) would have been called with the current value
  16187. type from @ref type():
  16188. Value type | initial value
  16189. ----------- | -------------
  16190. null | `null`
  16191. boolean | `false`
  16192. string | `""`
  16193. number | `0`
  16194. object | `{}`
  16195. array | `[]`
  16196. @post Has the same effect as calling
  16197. @code {.cpp}
  16198. *this = basic_json(type());
  16199. @endcode
  16200. @liveexample{The example below shows the effect of `clear()` to different
  16201. JSON types.,clear}
  16202. @complexity Linear in the size of the JSON value.
  16203. @iterators All iterators, pointers and references related to this container
  16204. are invalidated.
  16205. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  16206. @sa @ref basic_json(value_t) -- constructor that creates an object with the
  16207. same value than calling `clear()`
  16208. @since version 1.0.0
  16209. */
  16210. void clear() noexcept
  16211. {
  16212. switch (m_type)
  16213. {
  16214. case value_t::number_integer:
  16215. {
  16216. m_value.number_integer = 0;
  16217. break;
  16218. }
  16219. case value_t::number_unsigned:
  16220. {
  16221. m_value.number_unsigned = 0;
  16222. break;
  16223. }
  16224. case value_t::number_float:
  16225. {
  16226. m_value.number_float = 0.0;
  16227. break;
  16228. }
  16229. case value_t::boolean:
  16230. {
  16231. m_value.boolean = false;
  16232. break;
  16233. }
  16234. case value_t::string:
  16235. {
  16236. m_value.string->clear();
  16237. break;
  16238. }
  16239. case value_t::array:
  16240. {
  16241. m_value.array->clear();
  16242. break;
  16243. }
  16244. case value_t::object:
  16245. {
  16246. m_value.object->clear();
  16247. break;
  16248. }
  16249. default:
  16250. break;
  16251. }
  16252. }
  16253. /*!
  16254. @brief add an object to an array
  16255. Appends the given element @a val to the end of the JSON value. If the
  16256. function is called on a JSON null value, an empty array is created before
  16257. appending @a val.
  16258. @param[in] val the value to add to the JSON array
  16259. @throw type_error.308 when called on a type other than JSON array or
  16260. null; example: `"cannot use push_back() with number"`
  16261. @complexity Amortized constant.
  16262. @liveexample{The example shows how `push_back()` and `+=` can be used to
  16263. add elements to a JSON array. Note how the `null` value was silently
  16264. converted to a JSON array.,push_back}
  16265. @since version 1.0.0
  16266. */
  16267. void push_back(basic_json&& val)
  16268. {
  16269. // push_back only works for null objects or arrays
  16270. if (JSON_HEDLEY_UNLIKELY(not(is_null() or is_array())))
  16271. {
  16272. JSON_THROW(type_error::create(308, "cannot use push_back() with " + std::string(type_name())));
  16273. }
  16274. // transform null object into an array
  16275. if (is_null())
  16276. {
  16277. m_type = value_t::array;
  16278. m_value = value_t::array;
  16279. assert_invariant();
  16280. }
  16281. // add element to array (move semantics)
  16282. m_value.array->push_back(std::move(val));
  16283. // invalidate object: mark it null so we do not call the destructor
  16284. // cppcheck-suppress accessMoved
  16285. val.m_type = value_t::null;
  16286. }
  16287. /*!
  16288. @brief add an object to an array
  16289. @copydoc push_back(basic_json&&)
  16290. */
  16291. reference operator+=(basic_json&& val)
  16292. {
  16293. push_back(std::move(val));
  16294. return *this;
  16295. }
  16296. /*!
  16297. @brief add an object to an array
  16298. @copydoc push_back(basic_json&&)
  16299. */
  16300. void push_back(const basic_json& val)
  16301. {
  16302. // push_back only works for null objects or arrays
  16303. if (JSON_HEDLEY_UNLIKELY(not(is_null() or is_array())))
  16304. {
  16305. JSON_THROW(type_error::create(308, "cannot use push_back() with " + std::string(type_name())));
  16306. }
  16307. // transform null object into an array
  16308. if (is_null())
  16309. {
  16310. m_type = value_t::array;
  16311. m_value = value_t::array;
  16312. assert_invariant();
  16313. }
  16314. // add element to array
  16315. m_value.array->push_back(val);
  16316. }
  16317. /*!
  16318. @brief add an object to an array
  16319. @copydoc push_back(basic_json&&)
  16320. */
  16321. reference operator+=(const basic_json& val)
  16322. {
  16323. push_back(val);
  16324. return *this;
  16325. }
  16326. /*!
  16327. @brief add an object to an object
  16328. Inserts the given element @a val to the JSON object. If the function is
  16329. called on a JSON null value, an empty object is created before inserting
  16330. @a val.
  16331. @param[in] val the value to add to the JSON object
  16332. @throw type_error.308 when called on a type other than JSON object or
  16333. null; example: `"cannot use push_back() with number"`
  16334. @complexity Logarithmic in the size of the container, O(log(`size()`)).
  16335. @liveexample{The example shows how `push_back()` and `+=` can be used to
  16336. add elements to a JSON object. Note how the `null` value was silently
  16337. converted to a JSON object.,push_back__object_t__value}
  16338. @since version 1.0.0
  16339. */
  16340. void push_back(const typename object_t::value_type& val)
  16341. {
  16342. // push_back only works for null objects or objects
  16343. if (JSON_HEDLEY_UNLIKELY(not(is_null() or is_object())))
  16344. {
  16345. JSON_THROW(type_error::create(308, "cannot use push_back() with " + std::string(type_name())));
  16346. }
  16347. // transform null object into an object
  16348. if (is_null())
  16349. {
  16350. m_type = value_t::object;
  16351. m_value = value_t::object;
  16352. assert_invariant();
  16353. }
  16354. // add element to array
  16355. m_value.object->insert(val);
  16356. }
  16357. /*!
  16358. @brief add an object to an object
  16359. @copydoc push_back(const typename object_t::value_type&)
  16360. */
  16361. reference operator+=(const typename object_t::value_type& val)
  16362. {
  16363. push_back(val);
  16364. return *this;
  16365. }
  16366. /*!
  16367. @brief add an object to an object
  16368. This function allows to use `push_back` with an initializer list. In case
  16369. 1. the current value is an object,
  16370. 2. the initializer list @a init contains only two elements, and
  16371. 3. the first element of @a init is a string,
  16372. @a init is converted into an object element and added using
  16373. @ref push_back(const typename object_t::value_type&). Otherwise, @a init
  16374. is converted to a JSON value and added using @ref push_back(basic_json&&).
  16375. @param[in] init an initializer list
  16376. @complexity Linear in the size of the initializer list @a init.
  16377. @note This function is required to resolve an ambiguous overload error,
  16378. because pairs like `{"key", "value"}` can be both interpreted as
  16379. `object_t::value_type` or `std::initializer_list<basic_json>`, see
  16380. https://github.com/nlohmann/json/issues/235 for more information.
  16381. @liveexample{The example shows how initializer lists are treated as
  16382. objects when possible.,push_back__initializer_list}
  16383. */
  16384. void push_back(initializer_list_t init)
  16385. {
  16386. if (is_object() and init.size() == 2 and (*init.begin())->is_string())
  16387. {
  16388. basic_json&& key = init.begin()->moved_or_copied();
  16389. push_back(typename object_t::value_type(
  16390. std::move(key.get_ref<string_t&>()), (init.begin() + 1)->moved_or_copied()));
  16391. }
  16392. else
  16393. {
  16394. push_back(basic_json(init));
  16395. }
  16396. }
  16397. /*!
  16398. @brief add an object to an object
  16399. @copydoc push_back(initializer_list_t)
  16400. */
  16401. reference operator+=(initializer_list_t init)
  16402. {
  16403. push_back(init);
  16404. return *this;
  16405. }
  16406. /*!
  16407. @brief add an object to an array
  16408. Creates a JSON value from the passed parameters @a args to the end of the
  16409. JSON value. If the function is called on a JSON null value, an empty array
  16410. is created before appending the value created from @a args.
  16411. @param[in] args arguments to forward to a constructor of @ref basic_json
  16412. @tparam Args compatible types to create a @ref basic_json object
  16413. @return reference to the inserted element
  16414. @throw type_error.311 when called on a type other than JSON array or
  16415. null; example: `"cannot use emplace_back() with number"`
  16416. @complexity Amortized constant.
  16417. @liveexample{The example shows how `push_back()` can be used to add
  16418. elements to a JSON array. Note how the `null` value was silently converted
  16419. to a JSON array.,emplace_back}
  16420. @since version 2.0.8, returns reference since 3.7.0
  16421. */
  16422. template<class... Args>
  16423. reference emplace_back(Args&& ... args)
  16424. {
  16425. // emplace_back only works for null objects or arrays
  16426. if (JSON_HEDLEY_UNLIKELY(not(is_null() or is_array())))
  16427. {
  16428. JSON_THROW(type_error::create(311, "cannot use emplace_back() with " + std::string(type_name())));
  16429. }
  16430. // transform null object into an array
  16431. if (is_null())
  16432. {
  16433. m_type = value_t::array;
  16434. m_value = value_t::array;
  16435. assert_invariant();
  16436. }
  16437. // add element to array (perfect forwarding)
  16438. #ifdef JSON_HAS_CPP_17
  16439. return m_value.array->emplace_back(std::forward<Args>(args)...);
  16440. #else
  16441. m_value.array->emplace_back(std::forward<Args>(args)...);
  16442. return m_value.array->back();
  16443. #endif
  16444. }
  16445. /*!
  16446. @brief add an object to an object if key does not exist
  16447. Inserts a new element into a JSON object constructed in-place with the
  16448. given @a args if there is no element with the key in the container. If the
  16449. function is called on a JSON null value, an empty object is created before
  16450. appending the value created from @a args.
  16451. @param[in] args arguments to forward to a constructor of @ref basic_json
  16452. @tparam Args compatible types to create a @ref basic_json object
  16453. @return a pair consisting of an iterator to the inserted element, or the
  16454. already-existing element if no insertion happened, and a bool
  16455. denoting whether the insertion took place.
  16456. @throw type_error.311 when called on a type other than JSON object or
  16457. null; example: `"cannot use emplace() with number"`
  16458. @complexity Logarithmic in the size of the container, O(log(`size()`)).
  16459. @liveexample{The example shows how `emplace()` can be used to add elements
  16460. to a JSON object. Note how the `null` value was silently converted to a
  16461. JSON object. Further note how no value is added if there was already one
  16462. value stored with the same key.,emplace}
  16463. @since version 2.0.8
  16464. */
  16465. template<class... Args>
  16466. std::pair<iterator, bool> emplace(Args&& ... args)
  16467. {
  16468. // emplace only works for null objects or arrays
  16469. if (JSON_HEDLEY_UNLIKELY(not(is_null() or is_object())))
  16470. {
  16471. JSON_THROW(type_error::create(311, "cannot use emplace() with " + std::string(type_name())));
  16472. }
  16473. // transform null object into an object
  16474. if (is_null())
  16475. {
  16476. m_type = value_t::object;
  16477. m_value = value_t::object;
  16478. assert_invariant();
  16479. }
  16480. // add element to array (perfect forwarding)
  16481. auto res = m_value.object->emplace(std::forward<Args>(args)...);
  16482. // create result iterator and set iterator to the result of emplace
  16483. auto it = begin();
  16484. it.m_it.object_iterator = res.first;
  16485. // return pair of iterator and boolean
  16486. return {it, res.second};
  16487. }
  16488. /// Helper for insertion of an iterator
  16489. /// @note: This uses std::distance to support GCC 4.8,
  16490. /// see https://github.com/nlohmann/json/pull/1257
  16491. template<typename... Args>
  16492. iterator insert_iterator(const_iterator pos, Args&& ... args)
  16493. {
  16494. iterator result(this);
  16495. assert(m_value.array != nullptr);
  16496. auto insert_pos = std::distance(m_value.array->begin(), pos.m_it.array_iterator);
  16497. m_value.array->insert(pos.m_it.array_iterator, std::forward<Args>(args)...);
  16498. result.m_it.array_iterator = m_value.array->begin() + insert_pos;
  16499. // This could have been written as:
  16500. // result.m_it.array_iterator = m_value.array->insert(pos.m_it.array_iterator, cnt, val);
  16501. // but the return value of insert is missing in GCC 4.8, so it is written this way instead.
  16502. return result;
  16503. }
  16504. /*!
  16505. @brief inserts element
  16506. Inserts element @a val before iterator @a pos.
  16507. @param[in] pos iterator before which the content will be inserted; may be
  16508. the end() iterator
  16509. @param[in] val element to insert
  16510. @return iterator pointing to the inserted @a val.
  16511. @throw type_error.309 if called on JSON values other than arrays;
  16512. example: `"cannot use insert() with string"`
  16513. @throw invalid_iterator.202 if @a pos is not an iterator of *this;
  16514. example: `"iterator does not fit current value"`
  16515. @complexity Constant plus linear in the distance between @a pos and end of
  16516. the container.
  16517. @liveexample{The example shows how `insert()` is used.,insert}
  16518. @since version 1.0.0
  16519. */
  16520. iterator insert(const_iterator pos, const basic_json& val)
  16521. {
  16522. // insert only works for arrays
  16523. if (JSON_HEDLEY_LIKELY(is_array()))
  16524. {
  16525. // check if iterator pos fits to this JSON value
  16526. if (JSON_HEDLEY_UNLIKELY(pos.m_object != this))
  16527. {
  16528. JSON_THROW(invalid_iterator::create(202, "iterator does not fit current value"));
  16529. }
  16530. // insert to array and return iterator
  16531. return insert_iterator(pos, val);
  16532. }
  16533. JSON_THROW(type_error::create(309, "cannot use insert() with " + std::string(type_name())));
  16534. }
  16535. /*!
  16536. @brief inserts element
  16537. @copydoc insert(const_iterator, const basic_json&)
  16538. */
  16539. iterator insert(const_iterator pos, basic_json&& val)
  16540. {
  16541. return insert(pos, val);
  16542. }
  16543. /*!
  16544. @brief inserts elements
  16545. Inserts @a cnt copies of @a val before iterator @a pos.
  16546. @param[in] pos iterator before which the content will be inserted; may be
  16547. the end() iterator
  16548. @param[in] cnt number of copies of @a val to insert
  16549. @param[in] val element to insert
  16550. @return iterator pointing to the first element inserted, or @a pos if
  16551. `cnt==0`
  16552. @throw type_error.309 if called on JSON values other than arrays; example:
  16553. `"cannot use insert() with string"`
  16554. @throw invalid_iterator.202 if @a pos is not an iterator of *this;
  16555. example: `"iterator does not fit current value"`
  16556. @complexity Linear in @a cnt plus linear in the distance between @a pos
  16557. and end of the container.
  16558. @liveexample{The example shows how `insert()` is used.,insert__count}
  16559. @since version 1.0.0
  16560. */
  16561. iterator insert(const_iterator pos, size_type cnt, const basic_json& val)
  16562. {
  16563. // insert only works for arrays
  16564. if (JSON_HEDLEY_LIKELY(is_array()))
  16565. {
  16566. // check if iterator pos fits to this JSON value
  16567. if (JSON_HEDLEY_UNLIKELY(pos.m_object != this))
  16568. {
  16569. JSON_THROW(invalid_iterator::create(202, "iterator does not fit current value"));
  16570. }
  16571. // insert to array and return iterator
  16572. return insert_iterator(pos, cnt, val);
  16573. }
  16574. JSON_THROW(type_error::create(309, "cannot use insert() with " + std::string(type_name())));
  16575. }
  16576. /*!
  16577. @brief inserts elements
  16578. Inserts elements from range `[first, last)` before iterator @a pos.
  16579. @param[in] pos iterator before which the content will be inserted; may be
  16580. the end() iterator
  16581. @param[in] first begin of the range of elements to insert
  16582. @param[in] last end of the range of elements to insert
  16583. @throw type_error.309 if called on JSON values other than arrays; example:
  16584. `"cannot use insert() with string"`
  16585. @throw invalid_iterator.202 if @a pos is not an iterator of *this;
  16586. example: `"iterator does not fit current value"`
  16587. @throw invalid_iterator.210 if @a first and @a last do not belong to the
  16588. same JSON value; example: `"iterators do not fit"`
  16589. @throw invalid_iterator.211 if @a first or @a last are iterators into
  16590. container for which insert is called; example: `"passed iterators may not
  16591. belong to container"`
  16592. @return iterator pointing to the first element inserted, or @a pos if
  16593. `first==last`
  16594. @complexity Linear in `std::distance(first, last)` plus linear in the
  16595. distance between @a pos and end of the container.
  16596. @liveexample{The example shows how `insert()` is used.,insert__range}
  16597. @since version 1.0.0
  16598. */
  16599. iterator insert(const_iterator pos, const_iterator first, const_iterator last)
  16600. {
  16601. // insert only works for arrays
  16602. if (JSON_HEDLEY_UNLIKELY(not is_array()))
  16603. {
  16604. JSON_THROW(type_error::create(309, "cannot use insert() with " + std::string(type_name())));
  16605. }
  16606. // check if iterator pos fits to this JSON value
  16607. if (JSON_HEDLEY_UNLIKELY(pos.m_object != this))
  16608. {
  16609. JSON_THROW(invalid_iterator::create(202, "iterator does not fit current value"));
  16610. }
  16611. // check if range iterators belong to the same JSON object
  16612. if (JSON_HEDLEY_UNLIKELY(first.m_object != last.m_object))
  16613. {
  16614. JSON_THROW(invalid_iterator::create(210, "iterators do not fit"));
  16615. }
  16616. if (JSON_HEDLEY_UNLIKELY(first.m_object == this))
  16617. {
  16618. JSON_THROW(invalid_iterator::create(211, "passed iterators may not belong to container"));
  16619. }
  16620. // insert to array and return iterator
  16621. return insert_iterator(pos, first.m_it.array_iterator, last.m_it.array_iterator);
  16622. }
  16623. /*!
  16624. @brief inserts elements
  16625. Inserts elements from initializer list @a ilist before iterator @a pos.
  16626. @param[in] pos iterator before which the content will be inserted; may be
  16627. the end() iterator
  16628. @param[in] ilist initializer list to insert the values from
  16629. @throw type_error.309 if called on JSON values other than arrays; example:
  16630. `"cannot use insert() with string"`
  16631. @throw invalid_iterator.202 if @a pos is not an iterator of *this;
  16632. example: `"iterator does not fit current value"`
  16633. @return iterator pointing to the first element inserted, or @a pos if
  16634. `ilist` is empty
  16635. @complexity Linear in `ilist.size()` plus linear in the distance between
  16636. @a pos and end of the container.
  16637. @liveexample{The example shows how `insert()` is used.,insert__ilist}
  16638. @since version 1.0.0
  16639. */
  16640. iterator insert(const_iterator pos, initializer_list_t ilist)
  16641. {
  16642. // insert only works for arrays
  16643. if (JSON_HEDLEY_UNLIKELY(not is_array()))
  16644. {
  16645. JSON_THROW(type_error::create(309, "cannot use insert() with " + std::string(type_name())));
  16646. }
  16647. // check if iterator pos fits to this JSON value
  16648. if (JSON_HEDLEY_UNLIKELY(pos.m_object != this))
  16649. {
  16650. JSON_THROW(invalid_iterator::create(202, "iterator does not fit current value"));
  16651. }
  16652. // insert to array and return iterator
  16653. return insert_iterator(pos, ilist.begin(), ilist.end());
  16654. }
  16655. /*!
  16656. @brief inserts elements
  16657. Inserts elements from range `[first, last)`.
  16658. @param[in] first begin of the range of elements to insert
  16659. @param[in] last end of the range of elements to insert
  16660. @throw type_error.309 if called on JSON values other than objects; example:
  16661. `"cannot use insert() with string"`
  16662. @throw invalid_iterator.202 if iterator @a first or @a last does does not
  16663. point to an object; example: `"iterators first and last must point to
  16664. objects"`
  16665. @throw invalid_iterator.210 if @a first and @a last do not belong to the
  16666. same JSON value; example: `"iterators do not fit"`
  16667. @complexity Logarithmic: `O(N*log(size() + N))`, where `N` is the number
  16668. of elements to insert.
  16669. @liveexample{The example shows how `insert()` is used.,insert__range_object}
  16670. @since version 3.0.0
  16671. */
  16672. void insert(const_iterator first, const_iterator last)
  16673. {
  16674. // insert only works for objects
  16675. if (JSON_HEDLEY_UNLIKELY(not is_object()))
  16676. {
  16677. JSON_THROW(type_error::create(309, "cannot use insert() with " + std::string(type_name())));
  16678. }
  16679. // check if range iterators belong to the same JSON object
  16680. if (JSON_HEDLEY_UNLIKELY(first.m_object != last.m_object))
  16681. {
  16682. JSON_THROW(invalid_iterator::create(210, "iterators do not fit"));
  16683. }
  16684. // passed iterators must belong to objects
  16685. if (JSON_HEDLEY_UNLIKELY(not first.m_object->is_object()))
  16686. {
  16687. JSON_THROW(invalid_iterator::create(202, "iterators first and last must point to objects"));
  16688. }
  16689. m_value.object->insert(first.m_it.object_iterator, last.m_it.object_iterator);
  16690. }
  16691. /*!
  16692. @brief updates a JSON object from another object, overwriting existing keys
  16693. Inserts all values from JSON object @a j and overwrites existing keys.
  16694. @param[in] j JSON object to read values from
  16695. @throw type_error.312 if called on JSON values other than objects; example:
  16696. `"cannot use update() with string"`
  16697. @complexity O(N*log(size() + N)), where N is the number of elements to
  16698. insert.
  16699. @liveexample{The example shows how `update()` is used.,update}
  16700. @sa https://docs.python.org/3.6/library/stdtypes.html#dict.update
  16701. @since version 3.0.0
  16702. */
  16703. void update(const_reference j)
  16704. {
  16705. // implicitly convert null value to an empty object
  16706. if (is_null())
  16707. {
  16708. m_type = value_t::object;
  16709. m_value.object = create<object_t>();
  16710. assert_invariant();
  16711. }
  16712. if (JSON_HEDLEY_UNLIKELY(not is_object()))
  16713. {
  16714. JSON_THROW(type_error::create(312, "cannot use update() with " + std::string(type_name())));
  16715. }
  16716. if (JSON_HEDLEY_UNLIKELY(not j.is_object()))
  16717. {
  16718. JSON_THROW(type_error::create(312, "cannot use update() with " + std::string(j.type_name())));
  16719. }
  16720. for (auto it = j.cbegin(); it != j.cend(); ++it)
  16721. {
  16722. m_value.object->operator[](it.key()) = it.value();
  16723. }
  16724. }
  16725. /*!
  16726. @brief updates a JSON object from another object, overwriting existing keys
  16727. Inserts all values from from range `[first, last)` and overwrites existing
  16728. keys.
  16729. @param[in] first begin of the range of elements to insert
  16730. @param[in] last end of the range of elements to insert
  16731. @throw type_error.312 if called on JSON values other than objects; example:
  16732. `"cannot use update() with string"`
  16733. @throw invalid_iterator.202 if iterator @a first or @a last does does not
  16734. point to an object; example: `"iterators first and last must point to
  16735. objects"`
  16736. @throw invalid_iterator.210 if @a first and @a last do not belong to the
  16737. same JSON value; example: `"iterators do not fit"`
  16738. @complexity O(N*log(size() + N)), where N is the number of elements to
  16739. insert.
  16740. @liveexample{The example shows how `update()` is used__range.,update}
  16741. @sa https://docs.python.org/3.6/library/stdtypes.html#dict.update
  16742. @since version 3.0.0
  16743. */
  16744. void update(const_iterator first, const_iterator last)
  16745. {
  16746. // implicitly convert null value to an empty object
  16747. if (is_null())
  16748. {
  16749. m_type = value_t::object;
  16750. m_value.object = create<object_t>();
  16751. assert_invariant();
  16752. }
  16753. if (JSON_HEDLEY_UNLIKELY(not is_object()))
  16754. {
  16755. JSON_THROW(type_error::create(312, "cannot use update() with " + std::string(type_name())));
  16756. }
  16757. // check if range iterators belong to the same JSON object
  16758. if (JSON_HEDLEY_UNLIKELY(first.m_object != last.m_object))
  16759. {
  16760. JSON_THROW(invalid_iterator::create(210, "iterators do not fit"));
  16761. }
  16762. // passed iterators must belong to objects
  16763. if (JSON_HEDLEY_UNLIKELY(not first.m_object->is_object()
  16764. or not last.m_object->is_object()))
  16765. {
  16766. JSON_THROW(invalid_iterator::create(202, "iterators first and last must point to objects"));
  16767. }
  16768. for (auto it = first; it != last; ++it)
  16769. {
  16770. m_value.object->operator[](it.key()) = it.value();
  16771. }
  16772. }
  16773. /*!
  16774. @brief exchanges the values
  16775. Exchanges the contents of the JSON value with those of @a other. Does not
  16776. invoke any move, copy, or swap operations on individual elements. All
  16777. iterators and references remain valid. The past-the-end iterator is
  16778. invalidated.
  16779. @param[in,out] other JSON value to exchange the contents with
  16780. @complexity Constant.
  16781. @liveexample{The example below shows how JSON values can be swapped with
  16782. `swap()`.,swap__reference}
  16783. @since version 1.0.0
  16784. */
  16785. void swap(reference other) noexcept (
  16786. std::is_nothrow_move_constructible<value_t>::value and
  16787. std::is_nothrow_move_assignable<value_t>::value and
  16788. std::is_nothrow_move_constructible<json_value>::value and
  16789. std::is_nothrow_move_assignable<json_value>::value
  16790. )
  16791. {
  16792. std::swap(m_type, other.m_type);
  16793. std::swap(m_value, other.m_value);
  16794. assert_invariant();
  16795. }
  16796. /*!
  16797. @brief exchanges the values
  16798. Exchanges the contents of a JSON array with those of @a other. Does not
  16799. invoke any move, copy, or swap operations on individual elements. All
  16800. iterators and references remain valid. The past-the-end iterator is
  16801. invalidated.
  16802. @param[in,out] other array to exchange the contents with
  16803. @throw type_error.310 when JSON value is not an array; example: `"cannot
  16804. use swap() with string"`
  16805. @complexity Constant.
  16806. @liveexample{The example below shows how arrays can be swapped with
  16807. `swap()`.,swap__array_t}
  16808. @since version 1.0.0
  16809. */
  16810. void swap(array_t& other)
  16811. {
  16812. // swap only works for arrays
  16813. if (JSON_HEDLEY_LIKELY(is_array()))
  16814. {
  16815. std::swap(*(m_value.array), other);
  16816. }
  16817. else
  16818. {
  16819. JSON_THROW(type_error::create(310, "cannot use swap() with " + std::string(type_name())));
  16820. }
  16821. }
  16822. /*!
  16823. @brief exchanges the values
  16824. Exchanges the contents of a JSON object with those of @a other. Does not
  16825. invoke any move, copy, or swap operations on individual elements. All
  16826. iterators and references remain valid. The past-the-end iterator is
  16827. invalidated.
  16828. @param[in,out] other object to exchange the contents with
  16829. @throw type_error.310 when JSON value is not an object; example:
  16830. `"cannot use swap() with string"`
  16831. @complexity Constant.
  16832. @liveexample{The example below shows how objects can be swapped with
  16833. `swap()`.,swap__object_t}
  16834. @since version 1.0.0
  16835. */
  16836. void swap(object_t& other)
  16837. {
  16838. // swap only works for objects
  16839. if (JSON_HEDLEY_LIKELY(is_object()))
  16840. {
  16841. std::swap(*(m_value.object), other);
  16842. }
  16843. else
  16844. {
  16845. JSON_THROW(type_error::create(310, "cannot use swap() with " + std::string(type_name())));
  16846. }
  16847. }
  16848. /*!
  16849. @brief exchanges the values
  16850. Exchanges the contents of a JSON string with those of @a other. Does not
  16851. invoke any move, copy, or swap operations on individual elements. All
  16852. iterators and references remain valid. The past-the-end iterator is
  16853. invalidated.
  16854. @param[in,out] other string to exchange the contents with
  16855. @throw type_error.310 when JSON value is not a string; example: `"cannot
  16856. use swap() with boolean"`
  16857. @complexity Constant.
  16858. @liveexample{The example below shows how strings can be swapped with
  16859. `swap()`.,swap__string_t}
  16860. @since version 1.0.0
  16861. */
  16862. void swap(string_t& other)
  16863. {
  16864. // swap only works for strings
  16865. if (JSON_HEDLEY_LIKELY(is_string()))
  16866. {
  16867. std::swap(*(m_value.string), other);
  16868. }
  16869. else
  16870. {
  16871. JSON_THROW(type_error::create(310, "cannot use swap() with " + std::string(type_name())));
  16872. }
  16873. }
  16874. /// @}
  16875. public:
  16876. //////////////////////////////////////////
  16877. // lexicographical comparison operators //
  16878. //////////////////////////////////////////
  16879. /// @name lexicographical comparison operators
  16880. /// @{
  16881. /*!
  16882. @brief comparison: equal
  16883. Compares two JSON values for equality according to the following rules:
  16884. - Two JSON values are equal if (1) they are from the same type and (2)
  16885. their stored values are the same according to their respective
  16886. `operator==`.
  16887. - Integer and floating-point numbers are automatically converted before
  16888. comparison. Note than two NaN values are always treated as unequal.
  16889. - Two JSON null values are equal.
  16890. @note Floating-point inside JSON values numbers are compared with
  16891. `json::number_float_t::operator==` which is `double::operator==` by
  16892. default. To compare floating-point while respecting an epsilon, an alternative
  16893. [comparison function](https://github.com/mariokonrad/marnav/blob/master/src/marnav/math/floatingpoint.hpp#L34-#L39)
  16894. could be used, for instance
  16895. @code {.cpp}
  16896. template<typename T, typename = typename std::enable_if<std::is_floating_point<T>::value, T>::type>
  16897. inline bool is_same(T a, T b, T epsilon = std::numeric_limits<T>::epsilon()) noexcept
  16898. {
  16899. return std::abs(a - b) <= epsilon;
  16900. }
  16901. @endcode
  16902. @note NaN values never compare equal to themselves or to other NaN values.
  16903. @param[in] lhs first JSON value to consider
  16904. @param[in] rhs second JSON value to consider
  16905. @return whether the values @a lhs and @a rhs are equal
  16906. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  16907. @complexity Linear.
  16908. @liveexample{The example demonstrates comparing several JSON
  16909. types.,operator__equal}
  16910. @since version 1.0.0
  16911. */
  16912. friend bool operator==(const_reference lhs, const_reference rhs) noexcept
  16913. {
  16914. const auto lhs_type = lhs.type();
  16915. const auto rhs_type = rhs.type();
  16916. if (lhs_type == rhs_type)
  16917. {
  16918. switch (lhs_type)
  16919. {
  16920. case value_t::array:
  16921. return *lhs.m_value.array == *rhs.m_value.array;
  16922. case value_t::object:
  16923. return *lhs.m_value.object == *rhs.m_value.object;
  16924. case value_t::null:
  16925. return true;
  16926. case value_t::string:
  16927. return *lhs.m_value.string == *rhs.m_value.string;
  16928. case value_t::boolean:
  16929. return lhs.m_value.boolean == rhs.m_value.boolean;
  16930. case value_t::number_integer:
  16931. return lhs.m_value.number_integer == rhs.m_value.number_integer;
  16932. case value_t::number_unsigned:
  16933. return lhs.m_value.number_unsigned == rhs.m_value.number_unsigned;
  16934. case value_t::number_float:
  16935. return lhs.m_value.number_float == rhs.m_value.number_float;
  16936. default:
  16937. return false;
  16938. }
  16939. }
  16940. else if (lhs_type == value_t::number_integer and rhs_type == value_t::number_float)
  16941. {
  16942. return static_cast<number_float_t>(lhs.m_value.number_integer) == rhs.m_value.number_float;
  16943. }
  16944. else if (lhs_type == value_t::number_float and rhs_type == value_t::number_integer)
  16945. {
  16946. return lhs.m_value.number_float == static_cast<number_float_t>(rhs.m_value.number_integer);
  16947. }
  16948. else if (lhs_type == value_t::number_unsigned and rhs_type == value_t::number_float)
  16949. {
  16950. return static_cast<number_float_t>(lhs.m_value.number_unsigned) == rhs.m_value.number_float;
  16951. }
  16952. else if (lhs_type == value_t::number_float and rhs_type == value_t::number_unsigned)
  16953. {
  16954. return lhs.m_value.number_float == static_cast<number_float_t>(rhs.m_value.number_unsigned);
  16955. }
  16956. else if (lhs_type == value_t::number_unsigned and rhs_type == value_t::number_integer)
  16957. {
  16958. return static_cast<number_integer_t>(lhs.m_value.number_unsigned) == rhs.m_value.number_integer;
  16959. }
  16960. else if (lhs_type == value_t::number_integer and rhs_type == value_t::number_unsigned)
  16961. {
  16962. return lhs.m_value.number_integer == static_cast<number_integer_t>(rhs.m_value.number_unsigned);
  16963. }
  16964. return false;
  16965. }
  16966. /*!
  16967. @brief comparison: equal
  16968. @copydoc operator==(const_reference, const_reference)
  16969. */
  16970. template<typename ScalarType, typename std::enable_if<
  16971. std::is_scalar<ScalarType>::value, int>::type = 0>
  16972. friend bool operator==(const_reference lhs, const ScalarType rhs) noexcept
  16973. {
  16974. return lhs == basic_json(rhs);
  16975. }
  16976. /*!
  16977. @brief comparison: equal
  16978. @copydoc operator==(const_reference, const_reference)
  16979. */
  16980. template<typename ScalarType, typename std::enable_if<
  16981. std::is_scalar<ScalarType>::value, int>::type = 0>
  16982. friend bool operator==(const ScalarType lhs, const_reference rhs) noexcept
  16983. {
  16984. return basic_json(lhs) == rhs;
  16985. }
  16986. /*!
  16987. @brief comparison: not equal
  16988. Compares two JSON values for inequality by calculating `not (lhs == rhs)`.
  16989. @param[in] lhs first JSON value to consider
  16990. @param[in] rhs second JSON value to consider
  16991. @return whether the values @a lhs and @a rhs are not equal
  16992. @complexity Linear.
  16993. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  16994. @liveexample{The example demonstrates comparing several JSON
  16995. types.,operator__notequal}
  16996. @since version 1.0.0
  16997. */
  16998. friend bool operator!=(const_reference lhs, const_reference rhs) noexcept
  16999. {
  17000. return not (lhs == rhs);
  17001. }
  17002. /*!
  17003. @brief comparison: not equal
  17004. @copydoc operator!=(const_reference, const_reference)
  17005. */
  17006. template<typename ScalarType, typename std::enable_if<
  17007. std::is_scalar<ScalarType>::value, int>::type = 0>
  17008. friend bool operator!=(const_reference lhs, const ScalarType rhs) noexcept
  17009. {
  17010. return lhs != basic_json(rhs);
  17011. }
  17012. /*!
  17013. @brief comparison: not equal
  17014. @copydoc operator!=(const_reference, const_reference)
  17015. */
  17016. template<typename ScalarType, typename std::enable_if<
  17017. std::is_scalar<ScalarType>::value, int>::type = 0>
  17018. friend bool operator!=(const ScalarType lhs, const_reference rhs) noexcept
  17019. {
  17020. return basic_json(lhs) != rhs;
  17021. }
  17022. /*!
  17023. @brief comparison: less than
  17024. Compares whether one JSON value @a lhs is less than another JSON value @a
  17025. rhs according to the following rules:
  17026. - If @a lhs and @a rhs have the same type, the values are compared using
  17027. the default `<` operator.
  17028. - Integer and floating-point numbers are automatically converted before
  17029. comparison
  17030. - In case @a lhs and @a rhs have different types, the values are ignored
  17031. and the order of the types is considered, see
  17032. @ref operator<(const value_t, const value_t).
  17033. @param[in] lhs first JSON value to consider
  17034. @param[in] rhs second JSON value to consider
  17035. @return whether @a lhs is less than @a rhs
  17036. @complexity Linear.
  17037. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  17038. @liveexample{The example demonstrates comparing several JSON
  17039. types.,operator__less}
  17040. @since version 1.0.0
  17041. */
  17042. friend bool operator<(const_reference lhs, const_reference rhs) noexcept
  17043. {
  17044. const auto lhs_type = lhs.type();
  17045. const auto rhs_type = rhs.type();
  17046. if (lhs_type == rhs_type)
  17047. {
  17048. switch (lhs_type)
  17049. {
  17050. case value_t::array:
  17051. // note parentheses are necessary, see
  17052. // https://github.com/nlohmann/json/issues/1530
  17053. return (*lhs.m_value.array) < (*rhs.m_value.array);
  17054. case value_t::object:
  17055. return (*lhs.m_value.object) < (*rhs.m_value.object);
  17056. case value_t::null:
  17057. return false;
  17058. case value_t::string:
  17059. return (*lhs.m_value.string) < (*rhs.m_value.string);
  17060. case value_t::boolean:
  17061. return (lhs.m_value.boolean) < (rhs.m_value.boolean);
  17062. case value_t::number_integer:
  17063. return (lhs.m_value.number_integer) < (rhs.m_value.number_integer);
  17064. case value_t::number_unsigned:
  17065. return (lhs.m_value.number_unsigned) < (rhs.m_value.number_unsigned);
  17066. case value_t::number_float:
  17067. return (lhs.m_value.number_float) < (rhs.m_value.number_float);
  17068. default:
  17069. return false;
  17070. }
  17071. }
  17072. else if (lhs_type == value_t::number_integer and rhs_type == value_t::number_float)
  17073. {
  17074. return static_cast<number_float_t>(lhs.m_value.number_integer) < rhs.m_value.number_float;
  17075. }
  17076. else if (lhs_type == value_t::number_float and rhs_type == value_t::number_integer)
  17077. {
  17078. return lhs.m_value.number_float < static_cast<number_float_t>(rhs.m_value.number_integer);
  17079. }
  17080. else if (lhs_type == value_t::number_unsigned and rhs_type == value_t::number_float)
  17081. {
  17082. return static_cast<number_float_t>(lhs.m_value.number_unsigned) < rhs.m_value.number_float;
  17083. }
  17084. else if (lhs_type == value_t::number_float and rhs_type == value_t::number_unsigned)
  17085. {
  17086. return lhs.m_value.number_float < static_cast<number_float_t>(rhs.m_value.number_unsigned);
  17087. }
  17088. else if (lhs_type == value_t::number_integer and rhs_type == value_t::number_unsigned)
  17089. {
  17090. return lhs.m_value.number_integer < static_cast<number_integer_t>(rhs.m_value.number_unsigned);
  17091. }
  17092. else if (lhs_type == value_t::number_unsigned and rhs_type == value_t::number_integer)
  17093. {
  17094. return static_cast<number_integer_t>(lhs.m_value.number_unsigned) < rhs.m_value.number_integer;
  17095. }
  17096. // We only reach this line if we cannot compare values. In that case,
  17097. // we compare types. Note we have to call the operator explicitly,
  17098. // because MSVC has problems otherwise.
  17099. return operator<(lhs_type, rhs_type);
  17100. }
  17101. /*!
  17102. @brief comparison: less than
  17103. @copydoc operator<(const_reference, const_reference)
  17104. */
  17105. template<typename ScalarType, typename std::enable_if<
  17106. std::is_scalar<ScalarType>::value, int>::type = 0>
  17107. friend bool operator<(const_reference lhs, const ScalarType rhs) noexcept
  17108. {
  17109. return lhs < basic_json(rhs);
  17110. }
  17111. /*!
  17112. @brief comparison: less than
  17113. @copydoc operator<(const_reference, const_reference)
  17114. */
  17115. template<typename ScalarType, typename std::enable_if<
  17116. std::is_scalar<ScalarType>::value, int>::type = 0>
  17117. friend bool operator<(const ScalarType lhs, const_reference rhs) noexcept
  17118. {
  17119. return basic_json(lhs) < rhs;
  17120. }
  17121. /*!
  17122. @brief comparison: less than or equal
  17123. Compares whether one JSON value @a lhs is less than or equal to another
  17124. JSON value by calculating `not (rhs < lhs)`.
  17125. @param[in] lhs first JSON value to consider
  17126. @param[in] rhs second JSON value to consider
  17127. @return whether @a lhs is less than or equal to @a rhs
  17128. @complexity Linear.
  17129. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  17130. @liveexample{The example demonstrates comparing several JSON
  17131. types.,operator__greater}
  17132. @since version 1.0.0
  17133. */
  17134. friend bool operator<=(const_reference lhs, const_reference rhs) noexcept
  17135. {
  17136. return not (rhs < lhs);
  17137. }
  17138. /*!
  17139. @brief comparison: less than or equal
  17140. @copydoc operator<=(const_reference, const_reference)
  17141. */
  17142. template<typename ScalarType, typename std::enable_if<
  17143. std::is_scalar<ScalarType>::value, int>::type = 0>
  17144. friend bool operator<=(const_reference lhs, const ScalarType rhs) noexcept
  17145. {
  17146. return lhs <= basic_json(rhs);
  17147. }
  17148. /*!
  17149. @brief comparison: less than or equal
  17150. @copydoc operator<=(const_reference, const_reference)
  17151. */
  17152. template<typename ScalarType, typename std::enable_if<
  17153. std::is_scalar<ScalarType>::value, int>::type = 0>
  17154. friend bool operator<=(const ScalarType lhs, const_reference rhs) noexcept
  17155. {
  17156. return basic_json(lhs) <= rhs;
  17157. }
  17158. /*!
  17159. @brief comparison: greater than
  17160. Compares whether one JSON value @a lhs is greater than another
  17161. JSON value by calculating `not (lhs <= rhs)`.
  17162. @param[in] lhs first JSON value to consider
  17163. @param[in] rhs second JSON value to consider
  17164. @return whether @a lhs is greater than to @a rhs
  17165. @complexity Linear.
  17166. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  17167. @liveexample{The example demonstrates comparing several JSON
  17168. types.,operator__lessequal}
  17169. @since version 1.0.0
  17170. */
  17171. friend bool operator>(const_reference lhs, const_reference rhs) noexcept
  17172. {
  17173. return not (lhs <= rhs);
  17174. }
  17175. /*!
  17176. @brief comparison: greater than
  17177. @copydoc operator>(const_reference, const_reference)
  17178. */
  17179. template<typename ScalarType, typename std::enable_if<
  17180. std::is_scalar<ScalarType>::value, int>::type = 0>
  17181. friend bool operator>(const_reference lhs, const ScalarType rhs) noexcept
  17182. {
  17183. return lhs > basic_json(rhs);
  17184. }
  17185. /*!
  17186. @brief comparison: greater than
  17187. @copydoc operator>(const_reference, const_reference)
  17188. */
  17189. template<typename ScalarType, typename std::enable_if<
  17190. std::is_scalar<ScalarType>::value, int>::type = 0>
  17191. friend bool operator>(const ScalarType lhs, const_reference rhs) noexcept
  17192. {
  17193. return basic_json(lhs) > rhs;
  17194. }
  17195. /*!
  17196. @brief comparison: greater than or equal
  17197. Compares whether one JSON value @a lhs is greater than or equal to another
  17198. JSON value by calculating `not (lhs < rhs)`.
  17199. @param[in] lhs first JSON value to consider
  17200. @param[in] rhs second JSON value to consider
  17201. @return whether @a lhs is greater than or equal to @a rhs
  17202. @complexity Linear.
  17203. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  17204. @liveexample{The example demonstrates comparing several JSON
  17205. types.,operator__greaterequal}
  17206. @since version 1.0.0
  17207. */
  17208. friend bool operator>=(const_reference lhs, const_reference rhs) noexcept
  17209. {
  17210. return not (lhs < rhs);
  17211. }
  17212. /*!
  17213. @brief comparison: greater than or equal
  17214. @copydoc operator>=(const_reference, const_reference)
  17215. */
  17216. template<typename ScalarType, typename std::enable_if<
  17217. std::is_scalar<ScalarType>::value, int>::type = 0>
  17218. friend bool operator>=(const_reference lhs, const ScalarType rhs) noexcept
  17219. {
  17220. return lhs >= basic_json(rhs);
  17221. }
  17222. /*!
  17223. @brief comparison: greater than or equal
  17224. @copydoc operator>=(const_reference, const_reference)
  17225. */
  17226. template<typename ScalarType, typename std::enable_if<
  17227. std::is_scalar<ScalarType>::value, int>::type = 0>
  17228. friend bool operator>=(const ScalarType lhs, const_reference rhs) noexcept
  17229. {
  17230. return basic_json(lhs) >= rhs;
  17231. }
  17232. /// @}
  17233. ///////////////////
  17234. // serialization //
  17235. ///////////////////
  17236. /// @name serialization
  17237. /// @{
  17238. /*!
  17239. @brief serialize to stream
  17240. Serialize the given JSON value @a j to the output stream @a o. The JSON
  17241. value will be serialized using the @ref dump member function.
  17242. - The indentation of the output can be controlled with the member variable
  17243. `width` of the output stream @a o. For instance, using the manipulator
  17244. `std::setw(4)` on @a o sets the indentation level to `4` and the
  17245. serialization result is the same as calling `dump(4)`.
  17246. - The indentation character can be controlled with the member variable
  17247. `fill` of the output stream @a o. For instance, the manipulator
  17248. `std::setfill('\\t')` sets indentation to use a tab character rather than
  17249. the default space character.
  17250. @param[in,out] o stream to serialize to
  17251. @param[in] j JSON value to serialize
  17252. @return the stream @a o
  17253. @throw type_error.316 if a string stored inside the JSON value is not
  17254. UTF-8 encoded
  17255. @complexity Linear.
  17256. @liveexample{The example below shows the serialization with different
  17257. parameters to `width` to adjust the indentation level.,operator_serialize}
  17258. @since version 1.0.0; indentation character added in version 3.0.0
  17259. */
  17260. friend std::ostream& operator<<(std::ostream& o, const basic_json& j)
  17261. {
  17262. // read width member and use it as indentation parameter if nonzero
  17263. const bool pretty_print = o.width() > 0;
  17264. const auto indentation = pretty_print ? o.width() : 0;
  17265. // reset width to 0 for subsequent calls to this stream
  17266. o.width(0);
  17267. // do the actual serialization
  17268. serializer s(detail::output_adapter<char>(o), o.fill());
  17269. s.dump(j, pretty_print, false, static_cast<unsigned int>(indentation));
  17270. return o;
  17271. }
  17272. /*!
  17273. @brief serialize to stream
  17274. @deprecated This stream operator is deprecated and will be removed in
  17275. future 4.0.0 of the library. Please use
  17276. @ref operator<<(std::ostream&, const basic_json&)
  17277. instead; that is, replace calls like `j >> o;` with `o << j;`.
  17278. @since version 1.0.0; deprecated since version 3.0.0
  17279. */
  17280. JSON_HEDLEY_DEPRECATED(3.0.0)
  17281. friend std::ostream& operator>>(const basic_json& j, std::ostream& o)
  17282. {
  17283. return o << j;
  17284. }
  17285. /// @}
  17286. /////////////////////
  17287. // deserialization //
  17288. /////////////////////
  17289. /// @name deserialization
  17290. /// @{
  17291. /*!
  17292. @brief deserialize from a compatible input
  17293. This function reads from a compatible input. Examples are:
  17294. - an array of 1-byte values
  17295. - strings with character/literal type with size of 1 byte
  17296. - input streams
  17297. - container with contiguous storage of 1-byte values. Compatible container
  17298. types include `std::vector`, `std::string`, `std::array`,
  17299. `std::valarray`, and `std::initializer_list`. Furthermore, C-style
  17300. arrays can be used with `std::begin()`/`std::end()`. User-defined
  17301. containers can be used as long as they implement random-access iterators
  17302. and a contiguous storage.
  17303. @pre Each element of the container has a size of 1 byte. Violating this
  17304. precondition yields undefined behavior. **This precondition is enforced
  17305. with a static assertion.**
  17306. @pre The container storage is contiguous. Violating this precondition
  17307. yields undefined behavior. **This precondition is enforced with an
  17308. assertion.**
  17309. @warning There is no way to enforce all preconditions at compile-time. If
  17310. the function is called with a noncompliant container and with
  17311. assertions switched off, the behavior is undefined and will most
  17312. likely yield segmentation violation.
  17313. @param[in] i input to read from
  17314. @param[in] cb a parser callback function of type @ref parser_callback_t
  17315. which is used to control the deserialization by filtering unwanted values
  17316. (optional)
  17317. @param[in] allow_exceptions whether to throw exceptions in case of a
  17318. parse error (optional, true by default)
  17319. @return deserialized JSON value; in case of a parse error and
  17320. @a allow_exceptions set to `false`, the return value will be
  17321. value_t::discarded.
  17322. @throw parse_error.101 if a parse error occurs; example: `""unexpected end
  17323. of input; expected string literal""`
  17324. @throw parse_error.102 if to_unicode fails or surrogate error
  17325. @throw parse_error.103 if to_unicode fails
  17326. @complexity Linear in the length of the input. The parser is a predictive
  17327. LL(1) parser. The complexity can be higher if the parser callback function
  17328. @a cb has a super-linear complexity.
  17329. @note A UTF-8 byte order mark is silently ignored.
  17330. @liveexample{The example below demonstrates the `parse()` function reading
  17331. from an array.,parse__array__parser_callback_t}
  17332. @liveexample{The example below demonstrates the `parse()` function with
  17333. and without callback function.,parse__string__parser_callback_t}
  17334. @liveexample{The example below demonstrates the `parse()` function with
  17335. and without callback function.,parse__istream__parser_callback_t}
  17336. @liveexample{The example below demonstrates the `parse()` function reading
  17337. from a contiguous container.,parse__contiguouscontainer__parser_callback_t}
  17338. @since version 2.0.3 (contiguous containers)
  17339. */
  17340. JSON_HEDLEY_WARN_UNUSED_RESULT
  17341. static basic_json parse(detail::input_adapter&& i,
  17342. const parser_callback_t cb = nullptr,
  17343. const bool allow_exceptions = true)
  17344. {
  17345. basic_json result;
  17346. parser(i, cb, allow_exceptions).parse(true, result);
  17347. return result;
  17348. }
  17349. static bool accept(detail::input_adapter&& i)
  17350. {
  17351. return parser(i).accept(true);
  17352. }
  17353. /*!
  17354. @brief generate SAX events
  17355. The SAX event lister must follow the interface of @ref json_sax.
  17356. This function reads from a compatible input. Examples are:
  17357. - an array of 1-byte values
  17358. - strings with character/literal type with size of 1 byte
  17359. - input streams
  17360. - container with contiguous storage of 1-byte values. Compatible container
  17361. types include `std::vector`, `std::string`, `std::array`,
  17362. `std::valarray`, and `std::initializer_list`. Furthermore, C-style
  17363. arrays can be used with `std::begin()`/`std::end()`. User-defined
  17364. containers can be used as long as they implement random-access iterators
  17365. and a contiguous storage.
  17366. @pre Each element of the container has a size of 1 byte. Violating this
  17367. precondition yields undefined behavior. **This precondition is enforced
  17368. with a static assertion.**
  17369. @pre The container storage is contiguous. Violating this precondition
  17370. yields undefined behavior. **This precondition is enforced with an
  17371. assertion.**
  17372. @warning There is no way to enforce all preconditions at compile-time. If
  17373. the function is called with a noncompliant container and with
  17374. assertions switched off, the behavior is undefined and will most
  17375. likely yield segmentation violation.
  17376. @param[in] i input to read from
  17377. @param[in,out] sax SAX event listener
  17378. @param[in] format the format to parse (JSON, CBOR, MessagePack, or UBJSON)
  17379. @param[in] strict whether the input has to be consumed completely
  17380. @return return value of the last processed SAX event
  17381. @throw parse_error.101 if a parse error occurs; example: `""unexpected end
  17382. of input; expected string literal""`
  17383. @throw parse_error.102 if to_unicode fails or surrogate error
  17384. @throw parse_error.103 if to_unicode fails
  17385. @complexity Linear in the length of the input. The parser is a predictive
  17386. LL(1) parser. The complexity can be higher if the SAX consumer @a sax has
  17387. a super-linear complexity.
  17388. @note A UTF-8 byte order mark is silently ignored.
  17389. @liveexample{The example below demonstrates the `sax_parse()` function
  17390. reading from string and processing the events with a user-defined SAX
  17391. event consumer.,sax_parse}
  17392. @since version 3.2.0
  17393. */
  17394. template <typename SAX>
  17395. JSON_HEDLEY_NON_NULL(2)
  17396. static bool sax_parse(detail::input_adapter&& i, SAX* sax,
  17397. input_format_t format = input_format_t::json,
  17398. const bool strict = true)
  17399. {
  17400. assert(sax);
  17401. return format == input_format_t::json
  17402. ? parser(std::move(i)).sax_parse(sax, strict)
  17403. : detail::binary_reader<basic_json, SAX>(std::move(i)).sax_parse(format, sax, strict);
  17404. }
  17405. /*!
  17406. @brief deserialize from an iterator range with contiguous storage
  17407. This function reads from an iterator range of a container with contiguous
  17408. storage of 1-byte values. Compatible container types include
  17409. `std::vector`, `std::string`, `std::array`, `std::valarray`, and
  17410. `std::initializer_list`. Furthermore, C-style arrays can be used with
  17411. `std::begin()`/`std::end()`. User-defined containers can be used as long
  17412. as they implement random-access iterators and a contiguous storage.
  17413. @pre The iterator range is contiguous. Violating this precondition yields
  17414. undefined behavior. **This precondition is enforced with an assertion.**
  17415. @pre Each element in the range has a size of 1 byte. Violating this
  17416. precondition yields undefined behavior. **This precondition is enforced
  17417. with a static assertion.**
  17418. @warning There is no way to enforce all preconditions at compile-time. If
  17419. the function is called with noncompliant iterators and with
  17420. assertions switched off, the behavior is undefined and will most
  17421. likely yield segmentation violation.
  17422. @tparam IteratorType iterator of container with contiguous storage
  17423. @param[in] first begin of the range to parse (included)
  17424. @param[in] last end of the range to parse (excluded)
  17425. @param[in] cb a parser callback function of type @ref parser_callback_t
  17426. which is used to control the deserialization by filtering unwanted values
  17427. (optional)
  17428. @param[in] allow_exceptions whether to throw exceptions in case of a
  17429. parse error (optional, true by default)
  17430. @return deserialized JSON value; in case of a parse error and
  17431. @a allow_exceptions set to `false`, the return value will be
  17432. value_t::discarded.
  17433. @throw parse_error.101 in case of an unexpected token
  17434. @throw parse_error.102 if to_unicode fails or surrogate error
  17435. @throw parse_error.103 if to_unicode fails
  17436. @complexity Linear in the length of the input. The parser is a predictive
  17437. LL(1) parser. The complexity can be higher if the parser callback function
  17438. @a cb has a super-linear complexity.
  17439. @note A UTF-8 byte order mark is silently ignored.
  17440. @liveexample{The example below demonstrates the `parse()` function reading
  17441. from an iterator range.,parse__iteratortype__parser_callback_t}
  17442. @since version 2.0.3
  17443. */
  17444. template<class IteratorType, typename std::enable_if<
  17445. std::is_base_of<
  17446. std::random_access_iterator_tag,
  17447. typename std::iterator_traits<IteratorType>::iterator_category>::value, int>::type = 0>
  17448. static basic_json parse(IteratorType first, IteratorType last,
  17449. const parser_callback_t cb = nullptr,
  17450. const bool allow_exceptions = true)
  17451. {
  17452. basic_json result;
  17453. parser(detail::input_adapter(first, last), cb, allow_exceptions).parse(true, result);
  17454. return result;
  17455. }
  17456. template<class IteratorType, typename std::enable_if<
  17457. std::is_base_of<
  17458. std::random_access_iterator_tag,
  17459. typename std::iterator_traits<IteratorType>::iterator_category>::value, int>::type = 0>
  17460. static bool accept(IteratorType first, IteratorType last)
  17461. {
  17462. return parser(detail::input_adapter(first, last)).accept(true);
  17463. }
  17464. template<class IteratorType, class SAX, typename std::enable_if<
  17465. std::is_base_of<
  17466. std::random_access_iterator_tag,
  17467. typename std::iterator_traits<IteratorType>::iterator_category>::value, int>::type = 0>
  17468. JSON_HEDLEY_NON_NULL(3)
  17469. static bool sax_parse(IteratorType first, IteratorType last, SAX* sax)
  17470. {
  17471. return parser(detail::input_adapter(first, last)).sax_parse(sax);
  17472. }
  17473. /*!
  17474. @brief deserialize from stream
  17475. @deprecated This stream operator is deprecated and will be removed in
  17476. version 4.0.0 of the library. Please use
  17477. @ref operator>>(std::istream&, basic_json&)
  17478. instead; that is, replace calls like `j << i;` with `i >> j;`.
  17479. @since version 1.0.0; deprecated since version 3.0.0
  17480. */
  17481. JSON_HEDLEY_DEPRECATED(3.0.0)
  17482. friend std::istream& operator<<(basic_json& j, std::istream& i)
  17483. {
  17484. return operator>>(i, j);
  17485. }
  17486. /*!
  17487. @brief deserialize from stream
  17488. Deserializes an input stream to a JSON value.
  17489. @param[in,out] i input stream to read a serialized JSON value from
  17490. @param[in,out] j JSON value to write the deserialized input to
  17491. @throw parse_error.101 in case of an unexpected token
  17492. @throw parse_error.102 if to_unicode fails or surrogate error
  17493. @throw parse_error.103 if to_unicode fails
  17494. @complexity Linear in the length of the input. The parser is a predictive
  17495. LL(1) parser.
  17496. @note A UTF-8 byte order mark is silently ignored.
  17497. @liveexample{The example below shows how a JSON value is constructed by
  17498. reading a serialization from a stream.,operator_deserialize}
  17499. @sa parse(std::istream&, const parser_callback_t) for a variant with a
  17500. parser callback function to filter values while parsing
  17501. @since version 1.0.0
  17502. */
  17503. friend std::istream& operator>>(std::istream& i, basic_json& j)
  17504. {
  17505. parser(detail::input_adapter(i)).parse(false, j);
  17506. return i;
  17507. }
  17508. /// @}
  17509. ///////////////////////////
  17510. // convenience functions //
  17511. ///////////////////////////
  17512. /*!
  17513. @brief return the type as string
  17514. Returns the type name as string to be used in error messages - usually to
  17515. indicate that a function was called on a wrong JSON type.
  17516. @return a string representation of a the @a m_type member:
  17517. Value type | return value
  17518. ----------- | -------------
  17519. null | `"null"`
  17520. boolean | `"boolean"`
  17521. string | `"string"`
  17522. number | `"number"` (for all number types)
  17523. object | `"object"`
  17524. array | `"array"`
  17525. discarded | `"discarded"`
  17526. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  17527. @complexity Constant.
  17528. @liveexample{The following code exemplifies `type_name()` for all JSON
  17529. types.,type_name}
  17530. @sa @ref type() -- return the type of the JSON value
  17531. @sa @ref operator value_t() -- return the type of the JSON value (implicit)
  17532. @since version 1.0.0, public since 2.1.0, `const char*` and `noexcept`
  17533. since 3.0.0
  17534. */
  17535. JSON_HEDLEY_RETURNS_NON_NULL
  17536. const char* type_name() const noexcept
  17537. {
  17538. {
  17539. switch (m_type)
  17540. {
  17541. case value_t::null:
  17542. return "null";
  17543. case value_t::object:
  17544. return "object";
  17545. case value_t::array:
  17546. return "array";
  17547. case value_t::string:
  17548. return "string";
  17549. case value_t::boolean:
  17550. return "boolean";
  17551. case value_t::discarded:
  17552. return "discarded";
  17553. default:
  17554. return "number";
  17555. }
  17556. }
  17557. }
  17558. private:
  17559. //////////////////////
  17560. // member variables //
  17561. //////////////////////
  17562. /// the type of the current element
  17563. value_t m_type = value_t::null;
  17564. /// the value of the current element
  17565. json_value m_value = {};
  17566. //////////////////////////////////////////
  17567. // binary serialization/deserialization //
  17568. //////////////////////////////////////////
  17569. /// @name binary serialization/deserialization support
  17570. /// @{
  17571. public:
  17572. /*!
  17573. @brief create a CBOR serialization of a given JSON value
  17574. Serializes a given JSON value @a j to a byte vector using the CBOR (Concise
  17575. Binary Object Representation) serialization format. CBOR is a binary
  17576. serialization format which aims to be more compact than JSON itself, yet
  17577. more efficient to parse.
  17578. The library uses the following mapping from JSON values types to
  17579. CBOR types according to the CBOR specification (RFC 7049):
  17580. JSON value type | value/range | CBOR type | first byte
  17581. --------------- | ------------------------------------------ | ---------------------------------- | ---------------
  17582. null | `null` | Null | 0xF6
  17583. boolean | `true` | True | 0xF5
  17584. boolean | `false` | False | 0xF4
  17585. number_integer | -9223372036854775808..-2147483649 | Negative integer (8 bytes follow) | 0x3B
  17586. number_integer | -2147483648..-32769 | Negative integer (4 bytes follow) | 0x3A
  17587. number_integer | -32768..-129 | Negative integer (2 bytes follow) | 0x39
  17588. number_integer | -128..-25 | Negative integer (1 byte follow) | 0x38
  17589. number_integer | -24..-1 | Negative integer | 0x20..0x37
  17590. number_integer | 0..23 | Integer | 0x00..0x17
  17591. number_integer | 24..255 | Unsigned integer (1 byte follow) | 0x18
  17592. number_integer | 256..65535 | Unsigned integer (2 bytes follow) | 0x19
  17593. number_integer | 65536..4294967295 | Unsigned integer (4 bytes follow) | 0x1A
  17594. number_integer | 4294967296..18446744073709551615 | Unsigned integer (8 bytes follow) | 0x1B
  17595. number_unsigned | 0..23 | Integer | 0x00..0x17
  17596. number_unsigned | 24..255 | Unsigned integer (1 byte follow) | 0x18
  17597. number_unsigned | 256..65535 | Unsigned integer (2 bytes follow) | 0x19
  17598. number_unsigned | 65536..4294967295 | Unsigned integer (4 bytes follow) | 0x1A
  17599. number_unsigned | 4294967296..18446744073709551615 | Unsigned integer (8 bytes follow) | 0x1B
  17600. number_float | *any value* | Double-Precision Float | 0xFB
  17601. string | *length*: 0..23 | UTF-8 string | 0x60..0x77
  17602. string | *length*: 23..255 | UTF-8 string (1 byte follow) | 0x78
  17603. string | *length*: 256..65535 | UTF-8 string (2 bytes follow) | 0x79
  17604. string | *length*: 65536..4294967295 | UTF-8 string (4 bytes follow) | 0x7A
  17605. string | *length*: 4294967296..18446744073709551615 | UTF-8 string (8 bytes follow) | 0x7B
  17606. array | *size*: 0..23 | array | 0x80..0x97
  17607. array | *size*: 23..255 | array (1 byte follow) | 0x98
  17608. array | *size*: 256..65535 | array (2 bytes follow) | 0x99
  17609. array | *size*: 65536..4294967295 | array (4 bytes follow) | 0x9A
  17610. array | *size*: 4294967296..18446744073709551615 | array (8 bytes follow) | 0x9B
  17611. object | *size*: 0..23 | map | 0xA0..0xB7
  17612. object | *size*: 23..255 | map (1 byte follow) | 0xB8
  17613. object | *size*: 256..65535 | map (2 bytes follow) | 0xB9
  17614. object | *size*: 65536..4294967295 | map (4 bytes follow) | 0xBA
  17615. object | *size*: 4294967296..18446744073709551615 | map (8 bytes follow) | 0xBB
  17616. @note The mapping is **complete** in the sense that any JSON value type
  17617. can be converted to a CBOR value.
  17618. @note If NaN or Infinity are stored inside a JSON number, they are
  17619. serialized properly. This behavior differs from the @ref dump()
  17620. function which serializes NaN or Infinity to `null`.
  17621. @note The following CBOR types are not used in the conversion:
  17622. - byte strings (0x40..0x5F)
  17623. - UTF-8 strings terminated by "break" (0x7F)
  17624. - arrays terminated by "break" (0x9F)
  17625. - maps terminated by "break" (0xBF)
  17626. - date/time (0xC0..0xC1)
  17627. - bignum (0xC2..0xC3)
  17628. - decimal fraction (0xC4)
  17629. - bigfloat (0xC5)
  17630. - tagged items (0xC6..0xD4, 0xD8..0xDB)
  17631. - expected conversions (0xD5..0xD7)
  17632. - simple values (0xE0..0xF3, 0xF8)
  17633. - undefined (0xF7)
  17634. - half and single-precision floats (0xF9-0xFA)
  17635. - break (0xFF)
  17636. @param[in] j JSON value to serialize
  17637. @return MessagePack serialization as byte vector
  17638. @complexity Linear in the size of the JSON value @a j.
  17639. @liveexample{The example shows the serialization of a JSON value to a byte
  17640. vector in CBOR format.,to_cbor}
  17641. @sa http://cbor.io
  17642. @sa @ref from_cbor(detail::input_adapter&&, const bool, const bool) for the
  17643. analogous deserialization
  17644. @sa @ref to_msgpack(const basic_json&) for the related MessagePack format
  17645. @sa @ref to_ubjson(const basic_json&, const bool, const bool) for the
  17646. related UBJSON format
  17647. @since version 2.0.9
  17648. */
  17649. static std::vector<uint8_t> to_cbor(const basic_json& j)
  17650. {
  17651. std::vector<uint8_t> result;
  17652. to_cbor(j, result);
  17653. return result;
  17654. }
  17655. static void to_cbor(const basic_json& j, detail::output_adapter<uint8_t> o)
  17656. {
  17657. binary_writer<uint8_t>(o).write_cbor(j);
  17658. }
  17659. static void to_cbor(const basic_json& j, detail::output_adapter<char> o)
  17660. {
  17661. binary_writer<char>(o).write_cbor(j);
  17662. }
  17663. /*!
  17664. @brief create a MessagePack serialization of a given JSON value
  17665. Serializes a given JSON value @a j to a byte vector using the MessagePack
  17666. serialization format. MessagePack is a binary serialization format which
  17667. aims to be more compact than JSON itself, yet more efficient to parse.
  17668. The library uses the following mapping from JSON values types to
  17669. MessagePack types according to the MessagePack specification:
  17670. JSON value type | value/range | MessagePack type | first byte
  17671. --------------- | --------------------------------- | ---------------- | ----------
  17672. null | `null` | nil | 0xC0
  17673. boolean | `true` | true | 0xC3
  17674. boolean | `false` | false | 0xC2
  17675. number_integer | -9223372036854775808..-2147483649 | int64 | 0xD3
  17676. number_integer | -2147483648..-32769 | int32 | 0xD2
  17677. number_integer | -32768..-129 | int16 | 0xD1
  17678. number_integer | -128..-33 | int8 | 0xD0
  17679. number_integer | -32..-1 | negative fixint | 0xE0..0xFF
  17680. number_integer | 0..127 | positive fixint | 0x00..0x7F
  17681. number_integer | 128..255 | uint 8 | 0xCC
  17682. number_integer | 256..65535 | uint 16 | 0xCD
  17683. number_integer | 65536..4294967295 | uint 32 | 0xCE
  17684. number_integer | 4294967296..18446744073709551615 | uint 64 | 0xCF
  17685. number_unsigned | 0..127 | positive fixint | 0x00..0x7F
  17686. number_unsigned | 128..255 | uint 8 | 0xCC
  17687. number_unsigned | 256..65535 | uint 16 | 0xCD
  17688. number_unsigned | 65536..4294967295 | uint 32 | 0xCE
  17689. number_unsigned | 4294967296..18446744073709551615 | uint 64 | 0xCF
  17690. number_float | *any value* | float 64 | 0xCB
  17691. string | *length*: 0..31 | fixstr | 0xA0..0xBF
  17692. string | *length*: 32..255 | str 8 | 0xD9
  17693. string | *length*: 256..65535 | str 16 | 0xDA
  17694. string | *length*: 65536..4294967295 | str 32 | 0xDB
  17695. array | *size*: 0..15 | fixarray | 0x90..0x9F
  17696. array | *size*: 16..65535 | array 16 | 0xDC
  17697. array | *size*: 65536..4294967295 | array 32 | 0xDD
  17698. object | *size*: 0..15 | fix map | 0x80..0x8F
  17699. object | *size*: 16..65535 | map 16 | 0xDE
  17700. object | *size*: 65536..4294967295 | map 32 | 0xDF
  17701. @note The mapping is **complete** in the sense that any JSON value type
  17702. can be converted to a MessagePack value.
  17703. @note The following values can **not** be converted to a MessagePack value:
  17704. - strings with more than 4294967295 bytes
  17705. - arrays with more than 4294967295 elements
  17706. - objects with more than 4294967295 elements
  17707. @note The following MessagePack types are not used in the conversion:
  17708. - bin 8 - bin 32 (0xC4..0xC6)
  17709. - ext 8 - ext 32 (0xC7..0xC9)
  17710. - float 32 (0xCA)
  17711. - fixext 1 - fixext 16 (0xD4..0xD8)
  17712. @note Any MessagePack output created @ref to_msgpack can be successfully
  17713. parsed by @ref from_msgpack.
  17714. @note If NaN or Infinity are stored inside a JSON number, they are
  17715. serialized properly. This behavior differs from the @ref dump()
  17716. function which serializes NaN or Infinity to `null`.
  17717. @param[in] j JSON value to serialize
  17718. @return MessagePack serialization as byte vector
  17719. @complexity Linear in the size of the JSON value @a j.
  17720. @liveexample{The example shows the serialization of a JSON value to a byte
  17721. vector in MessagePack format.,to_msgpack}
  17722. @sa http://msgpack.org
  17723. @sa @ref from_msgpack for the analogous deserialization
  17724. @sa @ref to_cbor(const basic_json& for the related CBOR format
  17725. @sa @ref to_ubjson(const basic_json&, const bool, const bool) for the
  17726. related UBJSON format
  17727. @since version 2.0.9
  17728. */
  17729. static std::vector<uint8_t> to_msgpack(const basic_json& j)
  17730. {
  17731. std::vector<uint8_t> result;
  17732. to_msgpack(j, result);
  17733. return result;
  17734. }
  17735. static void to_msgpack(const basic_json& j, detail::output_adapter<uint8_t> o)
  17736. {
  17737. binary_writer<uint8_t>(o).write_msgpack(j);
  17738. }
  17739. static void to_msgpack(const basic_json& j, detail::output_adapter<char> o)
  17740. {
  17741. binary_writer<char>(o).write_msgpack(j);
  17742. }
  17743. /*!
  17744. @brief create a UBJSON serialization of a given JSON value
  17745. Serializes a given JSON value @a j to a byte vector using the UBJSON
  17746. (Universal Binary JSON) serialization format. UBJSON aims to be more compact
  17747. than JSON itself, yet more efficient to parse.
  17748. The library uses the following mapping from JSON values types to
  17749. UBJSON types according to the UBJSON specification:
  17750. JSON value type | value/range | UBJSON type | marker
  17751. --------------- | --------------------------------- | ----------- | ------
  17752. null | `null` | null | `Z`
  17753. boolean | `true` | true | `T`
  17754. boolean | `false` | false | `F`
  17755. number_integer | -9223372036854775808..-2147483649 | int64 | `L`
  17756. number_integer | -2147483648..-32769 | int32 | `l`
  17757. number_integer | -32768..-129 | int16 | `I`
  17758. number_integer | -128..127 | int8 | `i`
  17759. number_integer | 128..255 | uint8 | `U`
  17760. number_integer | 256..32767 | int16 | `I`
  17761. number_integer | 32768..2147483647 | int32 | `l`
  17762. number_integer | 2147483648..9223372036854775807 | int64 | `L`
  17763. number_unsigned | 0..127 | int8 | `i`
  17764. number_unsigned | 128..255 | uint8 | `U`
  17765. number_unsigned | 256..32767 | int16 | `I`
  17766. number_unsigned | 32768..2147483647 | int32 | `l`
  17767. number_unsigned | 2147483648..9223372036854775807 | int64 | `L`
  17768. number_float | *any value* | float64 | `D`
  17769. string | *with shortest length indicator* | string | `S`
  17770. array | *see notes on optimized format* | array | `[`
  17771. object | *see notes on optimized format* | map | `{`
  17772. @note The mapping is **complete** in the sense that any JSON value type
  17773. can be converted to a UBJSON value.
  17774. @note The following values can **not** be converted to a UBJSON value:
  17775. - strings with more than 9223372036854775807 bytes (theoretical)
  17776. - unsigned integer numbers above 9223372036854775807
  17777. @note The following markers are not used in the conversion:
  17778. - `Z`: no-op values are not created.
  17779. - `C`: single-byte strings are serialized with `S` markers.
  17780. @note Any UBJSON output created @ref to_ubjson can be successfully parsed
  17781. by @ref from_ubjson.
  17782. @note If NaN or Infinity are stored inside a JSON number, they are
  17783. serialized properly. This behavior differs from the @ref dump()
  17784. function which serializes NaN or Infinity to `null`.
  17785. @note The optimized formats for containers are supported: Parameter
  17786. @a use_size adds size information to the beginning of a container and
  17787. removes the closing marker. Parameter @a use_type further checks
  17788. whether all elements of a container have the same type and adds the
  17789. type marker to the beginning of the container. The @a use_type
  17790. parameter must only be used together with @a use_size = true. Note
  17791. that @a use_size = true alone may result in larger representations -
  17792. the benefit of this parameter is that the receiving side is
  17793. immediately informed on the number of elements of the container.
  17794. @param[in] j JSON value to serialize
  17795. @param[in] use_size whether to add size annotations to container types
  17796. @param[in] use_type whether to add type annotations to container types
  17797. (must be combined with @a use_size = true)
  17798. @return UBJSON serialization as byte vector
  17799. @complexity Linear in the size of the JSON value @a j.
  17800. @liveexample{The example shows the serialization of a JSON value to a byte
  17801. vector in UBJSON format.,to_ubjson}
  17802. @sa http://ubjson.org
  17803. @sa @ref from_ubjson(detail::input_adapter&&, const bool, const bool) for the
  17804. analogous deserialization
  17805. @sa @ref to_cbor(const basic_json& for the related CBOR format
  17806. @sa @ref to_msgpack(const basic_json&) for the related MessagePack format
  17807. @since version 3.1.0
  17808. */
  17809. static std::vector<uint8_t> to_ubjson(const basic_json& j,
  17810. const bool use_size = false,
  17811. const bool use_type = false)
  17812. {
  17813. std::vector<uint8_t> result;
  17814. to_ubjson(j, result, use_size, use_type);
  17815. return result;
  17816. }
  17817. static void to_ubjson(const basic_json& j, detail::output_adapter<uint8_t> o,
  17818. const bool use_size = false, const bool use_type = false)
  17819. {
  17820. binary_writer<uint8_t>(o).write_ubjson(j, use_size, use_type);
  17821. }
  17822. static void to_ubjson(const basic_json& j, detail::output_adapter<char> o,
  17823. const bool use_size = false, const bool use_type = false)
  17824. {
  17825. binary_writer<char>(o).write_ubjson(j, use_size, use_type);
  17826. }
  17827. /*!
  17828. @brief Serializes the given JSON object `j` to BSON and returns a vector
  17829. containing the corresponding BSON-representation.
  17830. BSON (Binary JSON) is a binary format in which zero or more ordered key/value pairs are
  17831. stored as a single entity (a so-called document).
  17832. The library uses the following mapping from JSON values types to BSON types:
  17833. JSON value type | value/range | BSON type | marker
  17834. --------------- | --------------------------------- | ----------- | ------
  17835. null | `null` | null | 0x0A
  17836. boolean | `true`, `false` | boolean | 0x08
  17837. number_integer | -9223372036854775808..-2147483649 | int64 | 0x12
  17838. number_integer | -2147483648..2147483647 | int32 | 0x10
  17839. number_integer | 2147483648..9223372036854775807 | int64 | 0x12
  17840. number_unsigned | 0..2147483647 | int32 | 0x10
  17841. number_unsigned | 2147483648..9223372036854775807 | int64 | 0x12
  17842. number_unsigned | 9223372036854775808..18446744073709551615| -- | --
  17843. number_float | *any value* | double | 0x01
  17844. string | *any value* | string | 0x02
  17845. array | *any value* | document | 0x04
  17846. object | *any value* | document | 0x03
  17847. @warning The mapping is **incomplete**, since only JSON-objects (and things
  17848. contained therein) can be serialized to BSON.
  17849. Also, integers larger than 9223372036854775807 cannot be serialized to BSON,
  17850. and the keys may not contain U+0000, since they are serialized a
  17851. zero-terminated c-strings.
  17852. @throw out_of_range.407 if `j.is_number_unsigned() && j.get<std::uint64_t>() > 9223372036854775807`
  17853. @throw out_of_range.409 if a key in `j` contains a NULL (U+0000)
  17854. @throw type_error.317 if `!j.is_object()`
  17855. @pre The input `j` is required to be an object: `j.is_object() == true`.
  17856. @note Any BSON output created via @ref to_bson can be successfully parsed
  17857. by @ref from_bson.
  17858. @param[in] j JSON value to serialize
  17859. @return BSON serialization as byte vector
  17860. @complexity Linear in the size of the JSON value @a j.
  17861. @liveexample{The example shows the serialization of a JSON value to a byte
  17862. vector in BSON format.,to_bson}
  17863. @sa http://bsonspec.org/spec.html
  17864. @sa @ref from_bson(detail::input_adapter&&, const bool strict) for the
  17865. analogous deserialization
  17866. @sa @ref to_ubjson(const basic_json&, const bool, const bool) for the
  17867. related UBJSON format
  17868. @sa @ref to_cbor(const basic_json&) for the related CBOR format
  17869. @sa @ref to_msgpack(const basic_json&) for the related MessagePack format
  17870. */
  17871. static std::vector<uint8_t> to_bson(const basic_json& j)
  17872. {
  17873. std::vector<uint8_t> result;
  17874. to_bson(j, result);
  17875. return result;
  17876. }
  17877. /*!
  17878. @brief Serializes the given JSON object `j` to BSON and forwards the
  17879. corresponding BSON-representation to the given output_adapter `o`.
  17880. @param j The JSON object to convert to BSON.
  17881. @param o The output adapter that receives the binary BSON representation.
  17882. @pre The input `j` shall be an object: `j.is_object() == true`
  17883. @sa @ref to_bson(const basic_json&)
  17884. */
  17885. static void to_bson(const basic_json& j, detail::output_adapter<uint8_t> o)
  17886. {
  17887. binary_writer<uint8_t>(o).write_bson(j);
  17888. }
  17889. /*!
  17890. @copydoc to_bson(const basic_json&, detail::output_adapter<uint8_t>)
  17891. */
  17892. static void to_bson(const basic_json& j, detail::output_adapter<char> o)
  17893. {
  17894. binary_writer<char>(o).write_bson(j);
  17895. }
  17896. /*!
  17897. @brief create a JSON value from an input in CBOR format
  17898. Deserializes a given input @a i to a JSON value using the CBOR (Concise
  17899. Binary Object Representation) serialization format.
  17900. The library maps CBOR types to JSON value types as follows:
  17901. CBOR type | JSON value type | first byte
  17902. ---------------------- | --------------- | ----------
  17903. Integer | number_unsigned | 0x00..0x17
  17904. Unsigned integer | number_unsigned | 0x18
  17905. Unsigned integer | number_unsigned | 0x19
  17906. Unsigned integer | number_unsigned | 0x1A
  17907. Unsigned integer | number_unsigned | 0x1B
  17908. Negative integer | number_integer | 0x20..0x37
  17909. Negative integer | number_integer | 0x38
  17910. Negative integer | number_integer | 0x39
  17911. Negative integer | number_integer | 0x3A
  17912. Negative integer | number_integer | 0x3B
  17913. Negative integer | number_integer | 0x40..0x57
  17914. UTF-8 string | string | 0x60..0x77
  17915. UTF-8 string | string | 0x78
  17916. UTF-8 string | string | 0x79
  17917. UTF-8 string | string | 0x7A
  17918. UTF-8 string | string | 0x7B
  17919. UTF-8 string | string | 0x7F
  17920. array | array | 0x80..0x97
  17921. array | array | 0x98
  17922. array | array | 0x99
  17923. array | array | 0x9A
  17924. array | array | 0x9B
  17925. array | array | 0x9F
  17926. map | object | 0xA0..0xB7
  17927. map | object | 0xB8
  17928. map | object | 0xB9
  17929. map | object | 0xBA
  17930. map | object | 0xBB
  17931. map | object | 0xBF
  17932. False | `false` | 0xF4
  17933. True | `true` | 0xF5
  17934. Null | `null` | 0xF6
  17935. Half-Precision Float | number_float | 0xF9
  17936. Single-Precision Float | number_float | 0xFA
  17937. Double-Precision Float | number_float | 0xFB
  17938. @warning The mapping is **incomplete** in the sense that not all CBOR
  17939. types can be converted to a JSON value. The following CBOR types
  17940. are not supported and will yield parse errors (parse_error.112):
  17941. - byte strings (0x40..0x5F)
  17942. - date/time (0xC0..0xC1)
  17943. - bignum (0xC2..0xC3)
  17944. - decimal fraction (0xC4)
  17945. - bigfloat (0xC5)
  17946. - tagged items (0xC6..0xD4, 0xD8..0xDB)
  17947. - expected conversions (0xD5..0xD7)
  17948. - simple values (0xE0..0xF3, 0xF8)
  17949. - undefined (0xF7)
  17950. @warning CBOR allows map keys of any type, whereas JSON only allows
  17951. strings as keys in object values. Therefore, CBOR maps with keys
  17952. other than UTF-8 strings are rejected (parse_error.113).
  17953. @note Any CBOR output created @ref to_cbor can be successfully parsed by
  17954. @ref from_cbor.
  17955. @param[in] i an input in CBOR format convertible to an input adapter
  17956. @param[in] strict whether to expect the input to be consumed until EOF
  17957. (true by default)
  17958. @param[in] allow_exceptions whether to throw exceptions in case of a
  17959. parse error (optional, true by default)
  17960. @return deserialized JSON value; in case of a parse error and
  17961. @a allow_exceptions set to `false`, the return value will be
  17962. value_t::discarded.
  17963. @throw parse_error.110 if the given input ends prematurely or the end of
  17964. file was not reached when @a strict was set to true
  17965. @throw parse_error.112 if unsupported features from CBOR were
  17966. used in the given input @a v or if the input is not valid CBOR
  17967. @throw parse_error.113 if a string was expected as map key, but not found
  17968. @complexity Linear in the size of the input @a i.
  17969. @liveexample{The example shows the deserialization of a byte vector in CBOR
  17970. format to a JSON value.,from_cbor}
  17971. @sa http://cbor.io
  17972. @sa @ref to_cbor(const basic_json&) for the analogous serialization
  17973. @sa @ref from_msgpack(detail::input_adapter&&, const bool, const bool) for the
  17974. related MessagePack format
  17975. @sa @ref from_ubjson(detail::input_adapter&&, const bool, const bool) for the
  17976. related UBJSON format
  17977. @since version 2.0.9; parameter @a start_index since 2.1.1; changed to
  17978. consume input adapters, removed start_index parameter, and added
  17979. @a strict parameter since 3.0.0; added @a allow_exceptions parameter
  17980. since 3.2.0
  17981. */
  17982. JSON_HEDLEY_WARN_UNUSED_RESULT
  17983. static basic_json from_cbor(detail::input_adapter&& i,
  17984. const bool strict = true,
  17985. const bool allow_exceptions = true)
  17986. {
  17987. basic_json result;
  17988. detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
  17989. const bool res = binary_reader(detail::input_adapter(i)).sax_parse(input_format_t::cbor, &sdp, strict);
  17990. return res ? result : basic_json(value_t::discarded);
  17991. }
  17992. /*!
  17993. @copydoc from_cbor(detail::input_adapter&&, const bool, const bool)
  17994. */
  17995. template<typename A1, typename A2,
  17996. detail::enable_if_t<std::is_constructible<detail::input_adapter, A1, A2>::value, int> = 0>
  17997. JSON_HEDLEY_WARN_UNUSED_RESULT
  17998. static basic_json from_cbor(A1 && a1, A2 && a2,
  17999. const bool strict = true,
  18000. const bool allow_exceptions = true)
  18001. {
  18002. basic_json result;
  18003. detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
  18004. const bool res = binary_reader(detail::input_adapter(std::forward<A1>(a1), std::forward<A2>(a2))).sax_parse(input_format_t::cbor, &sdp, strict);
  18005. return res ? result : basic_json(value_t::discarded);
  18006. }
  18007. /*!
  18008. @brief create a JSON value from an input in MessagePack format
  18009. Deserializes a given input @a i to a JSON value using the MessagePack
  18010. serialization format.
  18011. The library maps MessagePack types to JSON value types as follows:
  18012. MessagePack type | JSON value type | first byte
  18013. ---------------- | --------------- | ----------
  18014. positive fixint | number_unsigned | 0x00..0x7F
  18015. fixmap | object | 0x80..0x8F
  18016. fixarray | array | 0x90..0x9F
  18017. fixstr | string | 0xA0..0xBF
  18018. nil | `null` | 0xC0
  18019. false | `false` | 0xC2
  18020. true | `true` | 0xC3
  18021. float 32 | number_float | 0xCA
  18022. float 64 | number_float | 0xCB
  18023. uint 8 | number_unsigned | 0xCC
  18024. uint 16 | number_unsigned | 0xCD
  18025. uint 32 | number_unsigned | 0xCE
  18026. uint 64 | number_unsigned | 0xCF
  18027. int 8 | number_integer | 0xD0
  18028. int 16 | number_integer | 0xD1
  18029. int 32 | number_integer | 0xD2
  18030. int 64 | number_integer | 0xD3
  18031. str 8 | string | 0xD9
  18032. str 16 | string | 0xDA
  18033. str 32 | string | 0xDB
  18034. array 16 | array | 0xDC
  18035. array 32 | array | 0xDD
  18036. map 16 | object | 0xDE
  18037. map 32 | object | 0xDF
  18038. negative fixint | number_integer | 0xE0-0xFF
  18039. @warning The mapping is **incomplete** in the sense that not all
  18040. MessagePack types can be converted to a JSON value. The following
  18041. MessagePack types are not supported and will yield parse errors:
  18042. - bin 8 - bin 32 (0xC4..0xC6)
  18043. - ext 8 - ext 32 (0xC7..0xC9)
  18044. - fixext 1 - fixext 16 (0xD4..0xD8)
  18045. @note Any MessagePack output created @ref to_msgpack can be successfully
  18046. parsed by @ref from_msgpack.
  18047. @param[in] i an input in MessagePack format convertible to an input
  18048. adapter
  18049. @param[in] strict whether to expect the input to be consumed until EOF
  18050. (true by default)
  18051. @param[in] allow_exceptions whether to throw exceptions in case of a
  18052. parse error (optional, true by default)
  18053. @return deserialized JSON value; in case of a parse error and
  18054. @a allow_exceptions set to `false`, the return value will be
  18055. value_t::discarded.
  18056. @throw parse_error.110 if the given input ends prematurely or the end of
  18057. file was not reached when @a strict was set to true
  18058. @throw parse_error.112 if unsupported features from MessagePack were
  18059. used in the given input @a i or if the input is not valid MessagePack
  18060. @throw parse_error.113 if a string was expected as map key, but not found
  18061. @complexity Linear in the size of the input @a i.
  18062. @liveexample{The example shows the deserialization of a byte vector in
  18063. MessagePack format to a JSON value.,from_msgpack}
  18064. @sa http://msgpack.org
  18065. @sa @ref to_msgpack(const basic_json&) for the analogous serialization
  18066. @sa @ref from_cbor(detail::input_adapter&&, const bool, const bool) for the
  18067. related CBOR format
  18068. @sa @ref from_ubjson(detail::input_adapter&&, const bool, const bool) for
  18069. the related UBJSON format
  18070. @sa @ref from_bson(detail::input_adapter&&, const bool, const bool) for
  18071. the related BSON format
  18072. @since version 2.0.9; parameter @a start_index since 2.1.1; changed to
  18073. consume input adapters, removed start_index parameter, and added
  18074. @a strict parameter since 3.0.0; added @a allow_exceptions parameter
  18075. since 3.2.0
  18076. */
  18077. JSON_HEDLEY_WARN_UNUSED_RESULT
  18078. static basic_json from_msgpack(detail::input_adapter&& i,
  18079. const bool strict = true,
  18080. const bool allow_exceptions = true)
  18081. {
  18082. basic_json result;
  18083. detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
  18084. const bool res = binary_reader(detail::input_adapter(i)).sax_parse(input_format_t::msgpack, &sdp, strict);
  18085. return res ? result : basic_json(value_t::discarded);
  18086. }
  18087. /*!
  18088. @copydoc from_msgpack(detail::input_adapter&&, const bool, const bool)
  18089. */
  18090. template<typename A1, typename A2,
  18091. detail::enable_if_t<std::is_constructible<detail::input_adapter, A1, A2>::value, int> = 0>
  18092. JSON_HEDLEY_WARN_UNUSED_RESULT
  18093. static basic_json from_msgpack(A1 && a1, A2 && a2,
  18094. const bool strict = true,
  18095. const bool allow_exceptions = true)
  18096. {
  18097. basic_json result;
  18098. detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
  18099. const bool res = binary_reader(detail::input_adapter(std::forward<A1>(a1), std::forward<A2>(a2))).sax_parse(input_format_t::msgpack, &sdp, strict);
  18100. return res ? result : basic_json(value_t::discarded);
  18101. }
  18102. /*!
  18103. @brief create a JSON value from an input in UBJSON format
  18104. Deserializes a given input @a i to a JSON value using the UBJSON (Universal
  18105. Binary JSON) serialization format.
  18106. The library maps UBJSON types to JSON value types as follows:
  18107. UBJSON type | JSON value type | marker
  18108. ----------- | --------------------------------------- | ------
  18109. no-op | *no value, next value is read* | `N`
  18110. null | `null` | `Z`
  18111. false | `false` | `F`
  18112. true | `true` | `T`
  18113. float32 | number_float | `d`
  18114. float64 | number_float | `D`
  18115. uint8 | number_unsigned | `U`
  18116. int8 | number_integer | `i`
  18117. int16 | number_integer | `I`
  18118. int32 | number_integer | `l`
  18119. int64 | number_integer | `L`
  18120. string | string | `S`
  18121. char | string | `C`
  18122. array | array (optimized values are supported) | `[`
  18123. object | object (optimized values are supported) | `{`
  18124. @note The mapping is **complete** in the sense that any UBJSON value can
  18125. be converted to a JSON value.
  18126. @param[in] i an input in UBJSON format convertible to an input adapter
  18127. @param[in] strict whether to expect the input to be consumed until EOF
  18128. (true by default)
  18129. @param[in] allow_exceptions whether to throw exceptions in case of a
  18130. parse error (optional, true by default)
  18131. @return deserialized JSON value; in case of a parse error and
  18132. @a allow_exceptions set to `false`, the return value will be
  18133. value_t::discarded.
  18134. @throw parse_error.110 if the given input ends prematurely or the end of
  18135. file was not reached when @a strict was set to true
  18136. @throw parse_error.112 if a parse error occurs
  18137. @throw parse_error.113 if a string could not be parsed successfully
  18138. @complexity Linear in the size of the input @a i.
  18139. @liveexample{The example shows the deserialization of a byte vector in
  18140. UBJSON format to a JSON value.,from_ubjson}
  18141. @sa http://ubjson.org
  18142. @sa @ref to_ubjson(const basic_json&, const bool, const bool) for the
  18143. analogous serialization
  18144. @sa @ref from_cbor(detail::input_adapter&&, const bool, const bool) for the
  18145. related CBOR format
  18146. @sa @ref from_msgpack(detail::input_adapter&&, const bool, const bool) for
  18147. the related MessagePack format
  18148. @sa @ref from_bson(detail::input_adapter&&, const bool, const bool) for
  18149. the related BSON format
  18150. @since version 3.1.0; added @a allow_exceptions parameter since 3.2.0
  18151. */
  18152. JSON_HEDLEY_WARN_UNUSED_RESULT
  18153. static basic_json from_ubjson(detail::input_adapter&& i,
  18154. const bool strict = true,
  18155. const bool allow_exceptions = true)
  18156. {
  18157. basic_json result;
  18158. detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
  18159. const bool res = binary_reader(detail::input_adapter(i)).sax_parse(input_format_t::ubjson, &sdp, strict);
  18160. return res ? result : basic_json(value_t::discarded);
  18161. }
  18162. /*!
  18163. @copydoc from_ubjson(detail::input_adapter&&, const bool, const bool)
  18164. */
  18165. template<typename A1, typename A2,
  18166. detail::enable_if_t<std::is_constructible<detail::input_adapter, A1, A2>::value, int> = 0>
  18167. JSON_HEDLEY_WARN_UNUSED_RESULT
  18168. static basic_json from_ubjson(A1 && a1, A2 && a2,
  18169. const bool strict = true,
  18170. const bool allow_exceptions = true)
  18171. {
  18172. basic_json result;
  18173. detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
  18174. const bool res = binary_reader(detail::input_adapter(std::forward<A1>(a1), std::forward<A2>(a2))).sax_parse(input_format_t::ubjson, &sdp, strict);
  18175. return res ? result : basic_json(value_t::discarded);
  18176. }
  18177. /*!
  18178. @brief Create a JSON value from an input in BSON format
  18179. Deserializes a given input @a i to a JSON value using the BSON (Binary JSON)
  18180. serialization format.
  18181. The library maps BSON record types to JSON value types as follows:
  18182. BSON type | BSON marker byte | JSON value type
  18183. --------------- | ---------------- | ---------------------------
  18184. double | 0x01 | number_float
  18185. string | 0x02 | string
  18186. document | 0x03 | object
  18187. array | 0x04 | array
  18188. binary | 0x05 | still unsupported
  18189. undefined | 0x06 | still unsupported
  18190. ObjectId | 0x07 | still unsupported
  18191. boolean | 0x08 | boolean
  18192. UTC Date-Time | 0x09 | still unsupported
  18193. null | 0x0A | null
  18194. Regular Expr. | 0x0B | still unsupported
  18195. DB Pointer | 0x0C | still unsupported
  18196. JavaScript Code | 0x0D | still unsupported
  18197. Symbol | 0x0E | still unsupported
  18198. JavaScript Code | 0x0F | still unsupported
  18199. int32 | 0x10 | number_integer
  18200. Timestamp | 0x11 | still unsupported
  18201. 128-bit decimal float | 0x13 | still unsupported
  18202. Max Key | 0x7F | still unsupported
  18203. Min Key | 0xFF | still unsupported
  18204. @warning The mapping is **incomplete**. The unsupported mappings
  18205. are indicated in the table above.
  18206. @param[in] i an input in BSON format convertible to an input adapter
  18207. @param[in] strict whether to expect the input to be consumed until EOF
  18208. (true by default)
  18209. @param[in] allow_exceptions whether to throw exceptions in case of a
  18210. parse error (optional, true by default)
  18211. @return deserialized JSON value; in case of a parse error and
  18212. @a allow_exceptions set to `false`, the return value will be
  18213. value_t::discarded.
  18214. @throw parse_error.114 if an unsupported BSON record type is encountered
  18215. @complexity Linear in the size of the input @a i.
  18216. @liveexample{The example shows the deserialization of a byte vector in
  18217. BSON format to a JSON value.,from_bson}
  18218. @sa http://bsonspec.org/spec.html
  18219. @sa @ref to_bson(const basic_json&) for the analogous serialization
  18220. @sa @ref from_cbor(detail::input_adapter&&, const bool, const bool) for the
  18221. related CBOR format
  18222. @sa @ref from_msgpack(detail::input_adapter&&, const bool, const bool) for
  18223. the related MessagePack format
  18224. @sa @ref from_ubjson(detail::input_adapter&&, const bool, const bool) for the
  18225. related UBJSON format
  18226. */
  18227. JSON_HEDLEY_WARN_UNUSED_RESULT
  18228. static basic_json from_bson(detail::input_adapter&& i,
  18229. const bool strict = true,
  18230. const bool allow_exceptions = true)
  18231. {
  18232. basic_json result;
  18233. detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
  18234. const bool res = binary_reader(detail::input_adapter(i)).sax_parse(input_format_t::bson, &sdp, strict);
  18235. return res ? result : basic_json(value_t::discarded);
  18236. }
  18237. /*!
  18238. @copydoc from_bson(detail::input_adapter&&, const bool, const bool)
  18239. */
  18240. template<typename A1, typename A2,
  18241. detail::enable_if_t<std::is_constructible<detail::input_adapter, A1, A2>::value, int> = 0>
  18242. JSON_HEDLEY_WARN_UNUSED_RESULT
  18243. static basic_json from_bson(A1 && a1, A2 && a2,
  18244. const bool strict = true,
  18245. const bool allow_exceptions = true)
  18246. {
  18247. basic_json result;
  18248. detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
  18249. const bool res = binary_reader(detail::input_adapter(std::forward<A1>(a1), std::forward<A2>(a2))).sax_parse(input_format_t::bson, &sdp, strict);
  18250. return res ? result : basic_json(value_t::discarded);
  18251. }
  18252. /// @}
  18253. //////////////////////////
  18254. // JSON Pointer support //
  18255. //////////////////////////
  18256. /// @name JSON Pointer functions
  18257. /// @{
  18258. /*!
  18259. @brief access specified element via JSON Pointer
  18260. Uses a JSON pointer to retrieve a reference to the respective JSON value.
  18261. No bound checking is performed. Similar to @ref operator[](const typename
  18262. object_t::key_type&), `null` values are created in arrays and objects if
  18263. necessary.
  18264. In particular:
  18265. - If the JSON pointer points to an object key that does not exist, it
  18266. is created an filled with a `null` value before a reference to it
  18267. is returned.
  18268. - If the JSON pointer points to an array index that does not exist, it
  18269. is created an filled with a `null` value before a reference to it
  18270. is returned. All indices between the current maximum and the given
  18271. index are also filled with `null`.
  18272. - The special value `-` is treated as a synonym for the index past the
  18273. end.
  18274. @param[in] ptr a JSON pointer
  18275. @return reference to the element pointed to by @a ptr
  18276. @complexity Constant.
  18277. @throw parse_error.106 if an array index begins with '0'
  18278. @throw parse_error.109 if an array index was not a number
  18279. @throw out_of_range.404 if the JSON pointer can not be resolved
  18280. @liveexample{The behavior is shown in the example.,operatorjson_pointer}
  18281. @since version 2.0.0
  18282. */
  18283. reference operator[](const json_pointer& ptr)
  18284. {
  18285. return ptr.get_unchecked(this);
  18286. }
  18287. /*!
  18288. @brief access specified element via JSON Pointer
  18289. Uses a JSON pointer to retrieve a reference to the respective JSON value.
  18290. No bound checking is performed. The function does not change the JSON
  18291. value; no `null` values are created. In particular, the the special value
  18292. `-` yields an exception.
  18293. @param[in] ptr JSON pointer to the desired element
  18294. @return const reference to the element pointed to by @a ptr
  18295. @complexity Constant.
  18296. @throw parse_error.106 if an array index begins with '0'
  18297. @throw parse_error.109 if an array index was not a number
  18298. @throw out_of_range.402 if the array index '-' is used
  18299. @throw out_of_range.404 if the JSON pointer can not be resolved
  18300. @liveexample{The behavior is shown in the example.,operatorjson_pointer_const}
  18301. @since version 2.0.0
  18302. */
  18303. const_reference operator[](const json_pointer& ptr) const
  18304. {
  18305. return ptr.get_unchecked(this);
  18306. }
  18307. /*!
  18308. @brief access specified element via JSON Pointer
  18309. Returns a reference to the element at with specified JSON pointer @a ptr,
  18310. with bounds checking.
  18311. @param[in] ptr JSON pointer to the desired element
  18312. @return reference to the element pointed to by @a ptr
  18313. @throw parse_error.106 if an array index in the passed JSON pointer @a ptr
  18314. begins with '0'. See example below.
  18315. @throw parse_error.109 if an array index in the passed JSON pointer @a ptr
  18316. is not a number. See example below.
  18317. @throw out_of_range.401 if an array index in the passed JSON pointer @a ptr
  18318. is out of range. See example below.
  18319. @throw out_of_range.402 if the array index '-' is used in the passed JSON
  18320. pointer @a ptr. As `at` provides checked access (and no elements are
  18321. implicitly inserted), the index '-' is always invalid. See example below.
  18322. @throw out_of_range.403 if the JSON pointer describes a key of an object
  18323. which cannot be found. See example below.
  18324. @throw out_of_range.404 if the JSON pointer @a ptr can not be resolved.
  18325. See example below.
  18326. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  18327. changes in the JSON value.
  18328. @complexity Constant.
  18329. @since version 2.0.0
  18330. @liveexample{The behavior is shown in the example.,at_json_pointer}
  18331. */
  18332. reference at(const json_pointer& ptr)
  18333. {
  18334. return ptr.get_checked(this);
  18335. }
  18336. /*!
  18337. @brief access specified element via JSON Pointer
  18338. Returns a const reference to the element at with specified JSON pointer @a
  18339. ptr, with bounds checking.
  18340. @param[in] ptr JSON pointer to the desired element
  18341. @return reference to the element pointed to by @a ptr
  18342. @throw parse_error.106 if an array index in the passed JSON pointer @a ptr
  18343. begins with '0'. See example below.
  18344. @throw parse_error.109 if an array index in the passed JSON pointer @a ptr
  18345. is not a number. See example below.
  18346. @throw out_of_range.401 if an array index in the passed JSON pointer @a ptr
  18347. is out of range. See example below.
  18348. @throw out_of_range.402 if the array index '-' is used in the passed JSON
  18349. pointer @a ptr. As `at` provides checked access (and no elements are
  18350. implicitly inserted), the index '-' is always invalid. See example below.
  18351. @throw out_of_range.403 if the JSON pointer describes a key of an object
  18352. which cannot be found. See example below.
  18353. @throw out_of_range.404 if the JSON pointer @a ptr can not be resolved.
  18354. See example below.
  18355. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  18356. changes in the JSON value.
  18357. @complexity Constant.
  18358. @since version 2.0.0
  18359. @liveexample{The behavior is shown in the example.,at_json_pointer_const}
  18360. */
  18361. const_reference at(const json_pointer& ptr) const
  18362. {
  18363. return ptr.get_checked(this);
  18364. }
  18365. /*!
  18366. @brief return flattened JSON value
  18367. The function creates a JSON object whose keys are JSON pointers (see [RFC
  18368. 6901](https://tools.ietf.org/html/rfc6901)) and whose values are all
  18369. primitive. The original JSON value can be restored using the @ref
  18370. unflatten() function.
  18371. @return an object that maps JSON pointers to primitive values
  18372. @note Empty objects and arrays are flattened to `null` and will not be
  18373. reconstructed correctly by the @ref unflatten() function.
  18374. @complexity Linear in the size the JSON value.
  18375. @liveexample{The following code shows how a JSON object is flattened to an
  18376. object whose keys consist of JSON pointers.,flatten}
  18377. @sa @ref unflatten() for the reverse function
  18378. @since version 2.0.0
  18379. */
  18380. basic_json flatten() const
  18381. {
  18382. basic_json result(value_t::object);
  18383. json_pointer::flatten("", *this, result);
  18384. return result;
  18385. }
  18386. /*!
  18387. @brief unflatten a previously flattened JSON value
  18388. The function restores the arbitrary nesting of a JSON value that has been
  18389. flattened before using the @ref flatten() function. The JSON value must
  18390. meet certain constraints:
  18391. 1. The value must be an object.
  18392. 2. The keys must be JSON pointers (see
  18393. [RFC 6901](https://tools.ietf.org/html/rfc6901))
  18394. 3. The mapped values must be primitive JSON types.
  18395. @return the original JSON from a flattened version
  18396. @note Empty objects and arrays are flattened by @ref flatten() to `null`
  18397. values and can not unflattened to their original type. Apart from
  18398. this example, for a JSON value `j`, the following is always true:
  18399. `j == j.flatten().unflatten()`.
  18400. @complexity Linear in the size the JSON value.
  18401. @throw type_error.314 if value is not an object
  18402. @throw type_error.315 if object values are not primitive
  18403. @liveexample{The following code shows how a flattened JSON object is
  18404. unflattened into the original nested JSON object.,unflatten}
  18405. @sa @ref flatten() for the reverse function
  18406. @since version 2.0.0
  18407. */
  18408. basic_json unflatten() const
  18409. {
  18410. return json_pointer::unflatten(*this);
  18411. }
  18412. /// @}
  18413. //////////////////////////
  18414. // JSON Patch functions //
  18415. //////////////////////////
  18416. /// @name JSON Patch functions
  18417. /// @{
  18418. /*!
  18419. @brief applies a JSON patch
  18420. [JSON Patch](http://jsonpatch.com) defines a JSON document structure for
  18421. expressing a sequence of operations to apply to a JSON) document. With
  18422. this function, a JSON Patch is applied to the current JSON value by
  18423. executing all operations from the patch.
  18424. @param[in] json_patch JSON patch document
  18425. @return patched document
  18426. @note The application of a patch is atomic: Either all operations succeed
  18427. and the patched document is returned or an exception is thrown. In
  18428. any case, the original value is not changed: the patch is applied
  18429. to a copy of the value.
  18430. @throw parse_error.104 if the JSON patch does not consist of an array of
  18431. objects
  18432. @throw parse_error.105 if the JSON patch is malformed (e.g., mandatory
  18433. attributes are missing); example: `"operation add must have member path"`
  18434. @throw out_of_range.401 if an array index is out of range.
  18435. @throw out_of_range.403 if a JSON pointer inside the patch could not be
  18436. resolved successfully in the current JSON value; example: `"key baz not
  18437. found"`
  18438. @throw out_of_range.405 if JSON pointer has no parent ("add", "remove",
  18439. "move")
  18440. @throw other_error.501 if "test" operation was unsuccessful
  18441. @complexity Linear in the size of the JSON value and the length of the
  18442. JSON patch. As usually only a fraction of the JSON value is affected by
  18443. the patch, the complexity can usually be neglected.
  18444. @liveexample{The following code shows how a JSON patch is applied to a
  18445. value.,patch}
  18446. @sa @ref diff -- create a JSON patch by comparing two JSON values
  18447. @sa [RFC 6902 (JSON Patch)](https://tools.ietf.org/html/rfc6902)
  18448. @sa [RFC 6901 (JSON Pointer)](https://tools.ietf.org/html/rfc6901)
  18449. @since version 2.0.0
  18450. */
  18451. basic_json patch(const basic_json& json_patch) const
  18452. {
  18453. // make a working copy to apply the patch to
  18454. basic_json result = *this;
  18455. // the valid JSON Patch operations
  18456. enum class patch_operations {add, remove, replace, move, copy, test, invalid};
  18457. const auto get_op = [](const std::string & op)
  18458. {
  18459. if (op == "add")
  18460. {
  18461. return patch_operations::add;
  18462. }
  18463. if (op == "remove")
  18464. {
  18465. return patch_operations::remove;
  18466. }
  18467. if (op == "replace")
  18468. {
  18469. return patch_operations::replace;
  18470. }
  18471. if (op == "move")
  18472. {
  18473. return patch_operations::move;
  18474. }
  18475. if (op == "copy")
  18476. {
  18477. return patch_operations::copy;
  18478. }
  18479. if (op == "test")
  18480. {
  18481. return patch_operations::test;
  18482. }
  18483. return patch_operations::invalid;
  18484. };
  18485. // wrapper for "add" operation; add value at ptr
  18486. const auto operation_add = [&result](json_pointer & ptr, basic_json val)
  18487. {
  18488. // adding to the root of the target document means replacing it
  18489. if (ptr.empty())
  18490. {
  18491. result = val;
  18492. return;
  18493. }
  18494. // make sure the top element of the pointer exists
  18495. json_pointer top_pointer = ptr.top();
  18496. if (top_pointer != ptr)
  18497. {
  18498. result.at(top_pointer);
  18499. }
  18500. // get reference to parent of JSON pointer ptr
  18501. const auto last_path = ptr.back();
  18502. ptr.pop_back();
  18503. basic_json& parent = result[ptr];
  18504. switch (parent.m_type)
  18505. {
  18506. case value_t::null:
  18507. case value_t::object:
  18508. {
  18509. // use operator[] to add value
  18510. parent[last_path] = val;
  18511. break;
  18512. }
  18513. case value_t::array:
  18514. {
  18515. if (last_path == "-")
  18516. {
  18517. // special case: append to back
  18518. parent.push_back(val);
  18519. }
  18520. else
  18521. {
  18522. const auto idx = json_pointer::array_index(last_path);
  18523. if (JSON_HEDLEY_UNLIKELY(static_cast<size_type>(idx) > parent.size()))
  18524. {
  18525. // avoid undefined behavior
  18526. JSON_THROW(out_of_range::create(401, "array index " + std::to_string(idx) + " is out of range"));
  18527. }
  18528. // default case: insert add offset
  18529. parent.insert(parent.begin() + static_cast<difference_type>(idx), val);
  18530. }
  18531. break;
  18532. }
  18533. // if there exists a parent it cannot be primitive
  18534. default: // LCOV_EXCL_LINE
  18535. assert(false); // LCOV_EXCL_LINE
  18536. }
  18537. };
  18538. // wrapper for "remove" operation; remove value at ptr
  18539. const auto operation_remove = [&result](json_pointer & ptr)
  18540. {
  18541. // get reference to parent of JSON pointer ptr
  18542. const auto last_path = ptr.back();
  18543. ptr.pop_back();
  18544. basic_json& parent = result.at(ptr);
  18545. // remove child
  18546. if (parent.is_object())
  18547. {
  18548. // perform range check
  18549. auto it = parent.find(last_path);
  18550. if (JSON_HEDLEY_LIKELY(it != parent.end()))
  18551. {
  18552. parent.erase(it);
  18553. }
  18554. else
  18555. {
  18556. JSON_THROW(out_of_range::create(403, "key '" + last_path + "' not found"));
  18557. }
  18558. }
  18559. else if (parent.is_array())
  18560. {
  18561. // note erase performs range check
  18562. parent.erase(static_cast<size_type>(json_pointer::array_index(last_path)));
  18563. }
  18564. };
  18565. // type check: top level value must be an array
  18566. if (JSON_HEDLEY_UNLIKELY(not json_patch.is_array()))
  18567. {
  18568. JSON_THROW(parse_error::create(104, 0, "JSON patch must be an array of objects"));
  18569. }
  18570. // iterate and apply the operations
  18571. for (const auto& val : json_patch)
  18572. {
  18573. // wrapper to get a value for an operation
  18574. const auto get_value = [&val](const std::string & op,
  18575. const std::string & member,
  18576. bool string_type) -> basic_json &
  18577. {
  18578. // find value
  18579. auto it = val.m_value.object->find(member);
  18580. // context-sensitive error message
  18581. const auto error_msg = (op == "op") ? "operation" : "operation '" + op + "'";
  18582. // check if desired value is present
  18583. if (JSON_HEDLEY_UNLIKELY(it == val.m_value.object->end()))
  18584. {
  18585. JSON_THROW(parse_error::create(105, 0, error_msg + " must have member '" + member + "'"));
  18586. }
  18587. // check if result is of type string
  18588. if (JSON_HEDLEY_UNLIKELY(string_type and not it->second.is_string()))
  18589. {
  18590. JSON_THROW(parse_error::create(105, 0, error_msg + " must have string member '" + member + "'"));
  18591. }
  18592. // no error: return value
  18593. return it->second;
  18594. };
  18595. // type check: every element of the array must be an object
  18596. if (JSON_HEDLEY_UNLIKELY(not val.is_object()))
  18597. {
  18598. JSON_THROW(parse_error::create(104, 0, "JSON patch must be an array of objects"));
  18599. }
  18600. // collect mandatory members
  18601. const std::string op = get_value("op", "op", true);
  18602. const std::string path = get_value(op, "path", true);
  18603. json_pointer ptr(path);
  18604. switch (get_op(op))
  18605. {
  18606. case patch_operations::add:
  18607. {
  18608. operation_add(ptr, get_value("add", "value", false));
  18609. break;
  18610. }
  18611. case patch_operations::remove:
  18612. {
  18613. operation_remove(ptr);
  18614. break;
  18615. }
  18616. case patch_operations::replace:
  18617. {
  18618. // the "path" location must exist - use at()
  18619. result.at(ptr) = get_value("replace", "value", false);
  18620. break;
  18621. }
  18622. case patch_operations::move:
  18623. {
  18624. const std::string from_path = get_value("move", "from", true);
  18625. json_pointer from_ptr(from_path);
  18626. // the "from" location must exist - use at()
  18627. basic_json v = result.at(from_ptr);
  18628. // The move operation is functionally identical to a
  18629. // "remove" operation on the "from" location, followed
  18630. // immediately by an "add" operation at the target
  18631. // location with the value that was just removed.
  18632. operation_remove(from_ptr);
  18633. operation_add(ptr, v);
  18634. break;
  18635. }
  18636. case patch_operations::copy:
  18637. {
  18638. const std::string from_path = get_value("copy", "from", true);
  18639. const json_pointer from_ptr(from_path);
  18640. // the "from" location must exist - use at()
  18641. basic_json v = result.at(from_ptr);
  18642. // The copy is functionally identical to an "add"
  18643. // operation at the target location using the value
  18644. // specified in the "from" member.
  18645. operation_add(ptr, v);
  18646. break;
  18647. }
  18648. case patch_operations::test:
  18649. {
  18650. bool success = false;
  18651. JSON_TRY
  18652. {
  18653. // check if "value" matches the one at "path"
  18654. // the "path" location must exist - use at()
  18655. success = (result.at(ptr) == get_value("test", "value", false));
  18656. }
  18657. JSON_INTERNAL_CATCH (out_of_range&)
  18658. {
  18659. // ignore out of range errors: success remains false
  18660. }
  18661. // throw an exception if test fails
  18662. if (JSON_HEDLEY_UNLIKELY(not success))
  18663. {
  18664. JSON_THROW(other_error::create(501, "unsuccessful: " + val.dump()));
  18665. }
  18666. break;
  18667. }
  18668. default:
  18669. {
  18670. // op must be "add", "remove", "replace", "move", "copy", or
  18671. // "test"
  18672. JSON_THROW(parse_error::create(105, 0, "operation value '" + op + "' is invalid"));
  18673. }
  18674. }
  18675. }
  18676. return result;
  18677. }
  18678. /*!
  18679. @brief creates a diff as a JSON patch
  18680. Creates a [JSON Patch](http://jsonpatch.com) so that value @a source can
  18681. be changed into the value @a target by calling @ref patch function.
  18682. @invariant For two JSON values @a source and @a target, the following code
  18683. yields always `true`:
  18684. @code {.cpp}
  18685. source.patch(diff(source, target)) == target;
  18686. @endcode
  18687. @note Currently, only `remove`, `add`, and `replace` operations are
  18688. generated.
  18689. @param[in] source JSON value to compare from
  18690. @param[in] target JSON value to compare against
  18691. @param[in] path helper value to create JSON pointers
  18692. @return a JSON patch to convert the @a source to @a target
  18693. @complexity Linear in the lengths of @a source and @a target.
  18694. @liveexample{The following code shows how a JSON patch is created as a
  18695. diff for two JSON values.,diff}
  18696. @sa @ref patch -- apply a JSON patch
  18697. @sa @ref merge_patch -- apply a JSON Merge Patch
  18698. @sa [RFC 6902 (JSON Patch)](https://tools.ietf.org/html/rfc6902)
  18699. @since version 2.0.0
  18700. */
  18701. JSON_HEDLEY_WARN_UNUSED_RESULT
  18702. static basic_json diff(const basic_json& source, const basic_json& target,
  18703. const std::string& path = "")
  18704. {
  18705. // the patch
  18706. basic_json result(value_t::array);
  18707. // if the values are the same, return empty patch
  18708. if (source == target)
  18709. {
  18710. return result;
  18711. }
  18712. if (source.type() != target.type())
  18713. {
  18714. // different types: replace value
  18715. result.push_back(
  18716. {
  18717. {"op", "replace"}, {"path", path}, {"value", target}
  18718. });
  18719. return result;
  18720. }
  18721. switch (source.type())
  18722. {
  18723. case value_t::array:
  18724. {
  18725. // first pass: traverse common elements
  18726. std::size_t i = 0;
  18727. while (i < source.size() and i < target.size())
  18728. {
  18729. // recursive call to compare array values at index i
  18730. auto temp_diff = diff(source[i], target[i], path + "/" + std::to_string(i));
  18731. result.insert(result.end(), temp_diff.begin(), temp_diff.end());
  18732. ++i;
  18733. }
  18734. // i now reached the end of at least one array
  18735. // in a second pass, traverse the remaining elements
  18736. // remove my remaining elements
  18737. const auto end_index = static_cast<difference_type>(result.size());
  18738. while (i < source.size())
  18739. {
  18740. // add operations in reverse order to avoid invalid
  18741. // indices
  18742. result.insert(result.begin() + end_index, object(
  18743. {
  18744. {"op", "remove"},
  18745. {"path", path + "/" + std::to_string(i)}
  18746. }));
  18747. ++i;
  18748. }
  18749. // add other remaining elements
  18750. while (i < target.size())
  18751. {
  18752. result.push_back(
  18753. {
  18754. {"op", "add"},
  18755. {"path", path + "/" + std::to_string(i)},
  18756. {"value", target[i]}
  18757. });
  18758. ++i;
  18759. }
  18760. break;
  18761. }
  18762. case value_t::object:
  18763. {
  18764. // first pass: traverse this object's elements
  18765. for (auto it = source.cbegin(); it != source.cend(); ++it)
  18766. {
  18767. // escape the key name to be used in a JSON patch
  18768. const auto key = json_pointer::escape(it.key());
  18769. if (target.find(it.key()) != target.end())
  18770. {
  18771. // recursive call to compare object values at key it
  18772. auto temp_diff = diff(it.value(), target[it.key()], path + "/" + key);
  18773. result.insert(result.end(), temp_diff.begin(), temp_diff.end());
  18774. }
  18775. else
  18776. {
  18777. // found a key that is not in o -> remove it
  18778. result.push_back(object(
  18779. {
  18780. {"op", "remove"}, {"path", path + "/" + key}
  18781. }));
  18782. }
  18783. }
  18784. // second pass: traverse other object's elements
  18785. for (auto it = target.cbegin(); it != target.cend(); ++it)
  18786. {
  18787. if (source.find(it.key()) == source.end())
  18788. {
  18789. // found a key that is not in this -> add it
  18790. const auto key = json_pointer::escape(it.key());
  18791. result.push_back(
  18792. {
  18793. {"op", "add"}, {"path", path + "/" + key},
  18794. {"value", it.value()}
  18795. });
  18796. }
  18797. }
  18798. break;
  18799. }
  18800. default:
  18801. {
  18802. // both primitive type: replace value
  18803. result.push_back(
  18804. {
  18805. {"op", "replace"}, {"path", path}, {"value", target}
  18806. });
  18807. break;
  18808. }
  18809. }
  18810. return result;
  18811. }
  18812. /// @}
  18813. ////////////////////////////////
  18814. // JSON Merge Patch functions //
  18815. ////////////////////////////////
  18816. /// @name JSON Merge Patch functions
  18817. /// @{
  18818. /*!
  18819. @brief applies a JSON Merge Patch
  18820. The merge patch format is primarily intended for use with the HTTP PATCH
  18821. method as a means of describing a set of modifications to a target
  18822. resource's content. This function applies a merge patch to the current
  18823. JSON value.
  18824. The function implements the following algorithm from Section 2 of
  18825. [RFC 7396 (JSON Merge Patch)](https://tools.ietf.org/html/rfc7396):
  18826. ```
  18827. define MergePatch(Target, Patch):
  18828. if Patch is an Object:
  18829. if Target is not an Object:
  18830. Target = {} // Ignore the contents and set it to an empty Object
  18831. for each Name/Value pair in Patch:
  18832. if Value is null:
  18833. if Name exists in Target:
  18834. remove the Name/Value pair from Target
  18835. else:
  18836. Target[Name] = MergePatch(Target[Name], Value)
  18837. return Target
  18838. else:
  18839. return Patch
  18840. ```
  18841. Thereby, `Target` is the current object; that is, the patch is applied to
  18842. the current value.
  18843. @param[in] apply_patch the patch to apply
  18844. @complexity Linear in the lengths of @a patch.
  18845. @liveexample{The following code shows how a JSON Merge Patch is applied to
  18846. a JSON document.,merge_patch}
  18847. @sa @ref patch -- apply a JSON patch
  18848. @sa [RFC 7396 (JSON Merge Patch)](https://tools.ietf.org/html/rfc7396)
  18849. @since version 3.0.0
  18850. */
  18851. void merge_patch(const basic_json& apply_patch)
  18852. {
  18853. if (apply_patch.is_object())
  18854. {
  18855. if (not is_object())
  18856. {
  18857. *this = object();
  18858. }
  18859. for (auto it = apply_patch.begin(); it != apply_patch.end(); ++it)
  18860. {
  18861. if (it.value().is_null())
  18862. {
  18863. erase(it.key());
  18864. }
  18865. else
  18866. {
  18867. operator[](it.key()).merge_patch(it.value());
  18868. }
  18869. }
  18870. }
  18871. else
  18872. {
  18873. *this = apply_patch;
  18874. }
  18875. }
  18876. /// @}
  18877. };
  18878. /*!
  18879. @brief user-defined to_string function for JSON values
  18880. This function implements a user-defined to_string for JSON objects.
  18881. @param[in] j a JSON object
  18882. @return a std::string object
  18883. */
  18884. NLOHMANN_BASIC_JSON_TPL_DECLARATION
  18885. std::string to_string(const NLOHMANN_BASIC_JSON_TPL& j)
  18886. {
  18887. return j.dump();
  18888. }
  18889. } // namespace nlohmann
  18890. ///////////////////////
  18891. // nonmember support //
  18892. ///////////////////////
  18893. // specialization of std::swap, and std::hash
  18894. namespace std
  18895. {
  18896. /// hash value for JSON objects
  18897. template<>
  18898. struct hash<nlohmann::json>
  18899. {
  18900. /*!
  18901. @brief return a hash value for a JSON object
  18902. @since version 1.0.0
  18903. */
  18904. std::size_t operator()(const nlohmann::json& j) const
  18905. {
  18906. // a naive hashing via the string representation
  18907. const auto& h = hash<nlohmann::json::string_t>();
  18908. return h(j.dump());
  18909. }
  18910. };
  18911. /// specialization for std::less<value_t>
  18912. /// @note: do not remove the space after '<',
  18913. /// see https://github.com/nlohmann/json/pull/679
  18914. template<>
  18915. struct less< ::nlohmann::detail::value_t>
  18916. {
  18917. /*!
  18918. @brief compare two value_t enum values
  18919. @since version 3.0.0
  18920. */
  18921. bool operator()(nlohmann::detail::value_t lhs,
  18922. nlohmann::detail::value_t rhs) const noexcept
  18923. {
  18924. return nlohmann::detail::operator<(lhs, rhs);
  18925. }
  18926. };
  18927. /*!
  18928. @brief exchanges the values of two JSON objects
  18929. @since version 1.0.0
  18930. */
  18931. template<>
  18932. inline void swap<nlohmann::json>(nlohmann::json& j1, nlohmann::json& j2) noexcept(
  18933. is_nothrow_move_constructible<nlohmann::json>::value and
  18934. is_nothrow_move_assignable<nlohmann::json>::value
  18935. )
  18936. {
  18937. j1.swap(j2);
  18938. }
  18939. } // namespace std
  18940. /*!
  18941. @brief user-defined string literal for JSON values
  18942. This operator implements a user-defined string literal for JSON objects. It
  18943. can be used by adding `"_json"` to a string literal and returns a JSON object
  18944. if no parse error occurred.
  18945. @param[in] s a string representation of a JSON object
  18946. @param[in] n the length of string @a s
  18947. @return a JSON object
  18948. @since version 1.0.0
  18949. */
  18950. JSON_HEDLEY_NON_NULL(1)
  18951. inline nlohmann::json operator "" _json(const char* s, std::size_t n)
  18952. {
  18953. return nlohmann::json::parse(s, s + n);
  18954. }
  18955. /*!
  18956. @brief user-defined string literal for JSON pointer
  18957. This operator implements a user-defined string literal for JSON Pointers. It
  18958. can be used by adding `"_json_pointer"` to a string literal and returns a JSON pointer
  18959. object if no parse error occurred.
  18960. @param[in] s a string representation of a JSON Pointer
  18961. @param[in] n the length of string @a s
  18962. @return a JSON pointer object
  18963. @since version 2.0.0
  18964. */
  18965. JSON_HEDLEY_NON_NULL(1)
  18966. inline nlohmann::json::json_pointer operator "" _json_pointer(const char* s, std::size_t n)
  18967. {
  18968. return nlohmann::json::json_pointer(std::string(s, n));
  18969. }
  18970. // #include <nlohmann/detail/macro_unscope.hpp>
  18971. // restore GCC/clang diagnostic settings
  18972. #if defined(__clang__) || defined(__GNUC__) || defined(__GNUG__)
  18973. #pragma GCC diagnostic pop
  18974. #endif
  18975. #if defined(__clang__)
  18976. #pragma GCC diagnostic pop
  18977. #endif
  18978. // clean up
  18979. #undef JSON_INTERNAL_CATCH
  18980. #undef JSON_CATCH
  18981. #undef JSON_THROW
  18982. #undef JSON_TRY
  18983. #undef JSON_HAS_CPP_14
  18984. #undef JSON_HAS_CPP_17
  18985. #undef NLOHMANN_BASIC_JSON_TPL_DECLARATION
  18986. #undef NLOHMANN_BASIC_JSON_TPL
  18987. // #include <nlohmann/thirdparty/hedley/hedley_undef.hpp>
  18988. #undef JSON_HEDLEY_ALWAYS_INLINE
  18989. #undef JSON_HEDLEY_ARM_VERSION
  18990. #undef JSON_HEDLEY_ARM_VERSION_CHECK
  18991. #undef JSON_HEDLEY_ARRAY_PARAM
  18992. #undef JSON_HEDLEY_ASSUME
  18993. #undef JSON_HEDLEY_BEGIN_C_DECLS
  18994. #undef JSON_HEDLEY_CLANG_HAS_ATTRIBUTE
  18995. #undef JSON_HEDLEY_CLANG_HAS_BUILTIN
  18996. #undef JSON_HEDLEY_CLANG_HAS_CPP_ATTRIBUTE
  18997. #undef JSON_HEDLEY_CLANG_HAS_DECLSPEC_DECLSPEC_ATTRIBUTE
  18998. #undef JSON_HEDLEY_CLANG_HAS_EXTENSION
  18999. #undef JSON_HEDLEY_CLANG_HAS_FEATURE
  19000. #undef JSON_HEDLEY_CLANG_HAS_WARNING
  19001. #undef JSON_HEDLEY_COMPCERT_VERSION
  19002. #undef JSON_HEDLEY_COMPCERT_VERSION_CHECK
  19003. #undef JSON_HEDLEY_CONCAT
  19004. #undef JSON_HEDLEY_CONCAT_EX
  19005. #undef JSON_HEDLEY_CONST
  19006. #undef JSON_HEDLEY_CONSTEXPR
  19007. #undef JSON_HEDLEY_CONST_CAST
  19008. #undef JSON_HEDLEY_CPP_CAST
  19009. #undef JSON_HEDLEY_CRAY_VERSION
  19010. #undef JSON_HEDLEY_CRAY_VERSION_CHECK
  19011. #undef JSON_HEDLEY_C_DECL
  19012. #undef JSON_HEDLEY_DEPRECATED
  19013. #undef JSON_HEDLEY_DEPRECATED_FOR
  19014. #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL
  19015. #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED
  19016. #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS
  19017. #undef JSON_HEDLEY_DIAGNOSTIC_POP
  19018. #undef JSON_HEDLEY_DIAGNOSTIC_PUSH
  19019. #undef JSON_HEDLEY_DMC_VERSION
  19020. #undef JSON_HEDLEY_DMC_VERSION_CHECK
  19021. #undef JSON_HEDLEY_EMSCRIPTEN_VERSION
  19022. #undef JSON_HEDLEY_EMSCRIPTEN_VERSION_CHECK
  19023. #undef JSON_HEDLEY_END_C_DECLS
  19024. #undef JSON_HEDLEY_FALL_THROUGH
  19025. #undef JSON_HEDLEY_FLAGS
  19026. #undef JSON_HEDLEY_FLAGS_CAST
  19027. #undef JSON_HEDLEY_GCC_HAS_ATTRIBUTE
  19028. #undef JSON_HEDLEY_GCC_HAS_BUILTIN
  19029. #undef JSON_HEDLEY_GCC_HAS_CPP_ATTRIBUTE
  19030. #undef JSON_HEDLEY_GCC_HAS_DECLSPEC_ATTRIBUTE
  19031. #undef JSON_HEDLEY_GCC_HAS_EXTENSION
  19032. #undef JSON_HEDLEY_GCC_HAS_FEATURE
  19033. #undef JSON_HEDLEY_GCC_HAS_WARNING
  19034. #undef JSON_HEDLEY_GCC_NOT_CLANG_VERSION_CHECK
  19035. #undef JSON_HEDLEY_GCC_VERSION
  19036. #undef JSON_HEDLEY_GCC_VERSION_CHECK
  19037. #undef JSON_HEDLEY_GNUC_HAS_ATTRIBUTE
  19038. #undef JSON_HEDLEY_GNUC_HAS_BUILTIN
  19039. #undef JSON_HEDLEY_GNUC_HAS_CPP_ATTRIBUTE
  19040. #undef JSON_HEDLEY_GNUC_HAS_DECLSPEC_ATTRIBUTE
  19041. #undef JSON_HEDLEY_GNUC_HAS_EXTENSION
  19042. #undef JSON_HEDLEY_GNUC_HAS_FEATURE
  19043. #undef JSON_HEDLEY_GNUC_HAS_WARNING
  19044. #undef JSON_HEDLEY_GNUC_VERSION
  19045. #undef JSON_HEDLEY_GNUC_VERSION_CHECK
  19046. #undef JSON_HEDLEY_HAS_ATTRIBUTE
  19047. #undef JSON_HEDLEY_HAS_BUILTIN
  19048. #undef JSON_HEDLEY_HAS_CPP_ATTRIBUTE
  19049. #undef JSON_HEDLEY_HAS_DECLSPEC_ATTRIBUTE
  19050. #undef JSON_HEDLEY_HAS_EXTENSION
  19051. #undef JSON_HEDLEY_HAS_FEATURE
  19052. #undef JSON_HEDLEY_HAS_WARNING
  19053. #undef JSON_HEDLEY_IAR_VERSION
  19054. #undef JSON_HEDLEY_IAR_VERSION_CHECK
  19055. #undef JSON_HEDLEY_IBM_VERSION
  19056. #undef JSON_HEDLEY_IBM_VERSION_CHECK
  19057. #undef JSON_HEDLEY_IMPORT
  19058. #undef JSON_HEDLEY_INLINE
  19059. #undef JSON_HEDLEY_INTEL_VERSION
  19060. #undef JSON_HEDLEY_INTEL_VERSION_CHECK
  19061. #undef JSON_HEDLEY_IS_CONSTANT
  19062. #undef JSON_HEDLEY_LIKELY
  19063. #undef JSON_HEDLEY_MALLOC
  19064. #undef JSON_HEDLEY_MESSAGE
  19065. #undef JSON_HEDLEY_MSVC_VERSION
  19066. #undef JSON_HEDLEY_MSVC_VERSION_CHECK
  19067. #undef JSON_HEDLEY_NEVER_INLINE
  19068. #undef JSON_HEDLEY_NON_NULL
  19069. #undef JSON_HEDLEY_NO_RETURN
  19070. #undef JSON_HEDLEY_NO_THROW
  19071. #undef JSON_HEDLEY_PELLES_VERSION
  19072. #undef JSON_HEDLEY_PELLES_VERSION_CHECK
  19073. #undef JSON_HEDLEY_PGI_VERSION
  19074. #undef JSON_HEDLEY_PGI_VERSION_CHECK
  19075. #undef JSON_HEDLEY_PREDICT
  19076. #undef JSON_HEDLEY_PRINTF_FORMAT
  19077. #undef JSON_HEDLEY_PRIVATE
  19078. #undef JSON_HEDLEY_PUBLIC
  19079. #undef JSON_HEDLEY_PURE
  19080. #undef JSON_HEDLEY_REINTERPRET_CAST
  19081. #undef JSON_HEDLEY_REQUIRE
  19082. #undef JSON_HEDLEY_REQUIRE_CONSTEXPR
  19083. #undef JSON_HEDLEY_REQUIRE_MSG
  19084. #undef JSON_HEDLEY_RESTRICT
  19085. #undef JSON_HEDLEY_RETURNS_NON_NULL
  19086. #undef JSON_HEDLEY_SENTINEL
  19087. #undef JSON_HEDLEY_STATIC_ASSERT
  19088. #undef JSON_HEDLEY_STATIC_CAST
  19089. #undef JSON_HEDLEY_STRINGIFY
  19090. #undef JSON_HEDLEY_STRINGIFY_EX
  19091. #undef JSON_HEDLEY_SUNPRO_VERSION
  19092. #undef JSON_HEDLEY_SUNPRO_VERSION_CHECK
  19093. #undef JSON_HEDLEY_TINYC_VERSION
  19094. #undef JSON_HEDLEY_TINYC_VERSION_CHECK
  19095. #undef JSON_HEDLEY_TI_VERSION
  19096. #undef JSON_HEDLEY_TI_VERSION_CHECK
  19097. #undef JSON_HEDLEY_UNAVAILABLE
  19098. #undef JSON_HEDLEY_UNLIKELY
  19099. #undef JSON_HEDLEY_UNPREDICTABLE
  19100. #undef JSON_HEDLEY_UNREACHABLE
  19101. #undef JSON_HEDLEY_UNREACHABLE_RETURN
  19102. #undef JSON_HEDLEY_VERSION
  19103. #undef JSON_HEDLEY_VERSION_DECODE_MAJOR
  19104. #undef JSON_HEDLEY_VERSION_DECODE_MINOR
  19105. #undef JSON_HEDLEY_VERSION_DECODE_REVISION
  19106. #undef JSON_HEDLEY_VERSION_ENCODE
  19107. #undef JSON_HEDLEY_WARNING
  19108. #undef JSON_HEDLEY_WARN_UNUSED_RESULT
  19109. #endif // INCLUDE_NLOHMANN_JSON_HPP_