json.hpp 850 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461
  1. /*
  2. __ _____ _____ _____
  3. __| | __| | | | JSON for Modern C++
  4. | | |__ | | | | | | version 3.7.3
  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 3
  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 < 13)
  100. #if defined(JSON_HEDLEY_VERSION)
  101. #undef JSON_HEDLEY_VERSION
  102. #endif
  103. #define JSON_HEDLEY_VERSION 13
  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_CONCAT3_EX)
  121. #undef JSON_HEDLEY_CONCAT3_EX
  122. #endif
  123. #define JSON_HEDLEY_CONCAT3_EX(a,b,c) a##b##c
  124. #if defined(JSON_HEDLEY_CONCAT3)
  125. #undef JSON_HEDLEY_CONCAT3
  126. #endif
  127. #define JSON_HEDLEY_CONCAT3(a,b,c) JSON_HEDLEY_CONCAT3_EX(a,b,c)
  128. #if defined(JSON_HEDLEY_VERSION_ENCODE)
  129. #undef JSON_HEDLEY_VERSION_ENCODE
  130. #endif
  131. #define JSON_HEDLEY_VERSION_ENCODE(major,minor,revision) (((major) * 1000000) + ((minor) * 1000) + (revision))
  132. #if defined(JSON_HEDLEY_VERSION_DECODE_MAJOR)
  133. #undef JSON_HEDLEY_VERSION_DECODE_MAJOR
  134. #endif
  135. #define JSON_HEDLEY_VERSION_DECODE_MAJOR(version) ((version) / 1000000)
  136. #if defined(JSON_HEDLEY_VERSION_DECODE_MINOR)
  137. #undef JSON_HEDLEY_VERSION_DECODE_MINOR
  138. #endif
  139. #define JSON_HEDLEY_VERSION_DECODE_MINOR(version) (((version) % 1000000) / 1000)
  140. #if defined(JSON_HEDLEY_VERSION_DECODE_REVISION)
  141. #undef JSON_HEDLEY_VERSION_DECODE_REVISION
  142. #endif
  143. #define JSON_HEDLEY_VERSION_DECODE_REVISION(version) ((version) % 1000)
  144. #if defined(JSON_HEDLEY_GNUC_VERSION)
  145. #undef JSON_HEDLEY_GNUC_VERSION
  146. #endif
  147. #if defined(__GNUC__) && defined(__GNUC_PATCHLEVEL__)
  148. #define JSON_HEDLEY_GNUC_VERSION JSON_HEDLEY_VERSION_ENCODE(__GNUC__, __GNUC_MINOR__, __GNUC_PATCHLEVEL__)
  149. #elif defined(__GNUC__)
  150. #define JSON_HEDLEY_GNUC_VERSION JSON_HEDLEY_VERSION_ENCODE(__GNUC__, __GNUC_MINOR__, 0)
  151. #endif
  152. #if defined(JSON_HEDLEY_GNUC_VERSION_CHECK)
  153. #undef JSON_HEDLEY_GNUC_VERSION_CHECK
  154. #endif
  155. #if defined(JSON_HEDLEY_GNUC_VERSION)
  156. #define JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_GNUC_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
  157. #else
  158. #define JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch) (0)
  159. #endif
  160. #if defined(JSON_HEDLEY_MSVC_VERSION)
  161. #undef JSON_HEDLEY_MSVC_VERSION
  162. #endif
  163. #if defined(_MSC_FULL_VER) && (_MSC_FULL_VER >= 140000000)
  164. #define JSON_HEDLEY_MSVC_VERSION JSON_HEDLEY_VERSION_ENCODE(_MSC_FULL_VER / 10000000, (_MSC_FULL_VER % 10000000) / 100000, (_MSC_FULL_VER % 100000) / 100)
  165. #elif defined(_MSC_FULL_VER)
  166. #define JSON_HEDLEY_MSVC_VERSION JSON_HEDLEY_VERSION_ENCODE(_MSC_FULL_VER / 1000000, (_MSC_FULL_VER % 1000000) / 10000, (_MSC_FULL_VER % 10000) / 10)
  167. #elif defined(_MSC_VER)
  168. #define JSON_HEDLEY_MSVC_VERSION JSON_HEDLEY_VERSION_ENCODE(_MSC_VER / 100, _MSC_VER % 100, 0)
  169. #endif
  170. #if defined(JSON_HEDLEY_MSVC_VERSION_CHECK)
  171. #undef JSON_HEDLEY_MSVC_VERSION_CHECK
  172. #endif
  173. #if !defined(_MSC_VER)
  174. #define JSON_HEDLEY_MSVC_VERSION_CHECK(major,minor,patch) (0)
  175. #elif defined(_MSC_VER) && (_MSC_VER >= 1400)
  176. #define JSON_HEDLEY_MSVC_VERSION_CHECK(major,minor,patch) (_MSC_FULL_VER >= ((major * 10000000) + (minor * 100000) + (patch)))
  177. #elif defined(_MSC_VER) && (_MSC_VER >= 1200)
  178. #define JSON_HEDLEY_MSVC_VERSION_CHECK(major,minor,patch) (_MSC_FULL_VER >= ((major * 1000000) + (minor * 10000) + (patch)))
  179. #else
  180. #define JSON_HEDLEY_MSVC_VERSION_CHECK(major,minor,patch) (_MSC_VER >= ((major * 100) + (minor)))
  181. #endif
  182. #if defined(JSON_HEDLEY_INTEL_VERSION)
  183. #undef JSON_HEDLEY_INTEL_VERSION
  184. #endif
  185. #if defined(__INTEL_COMPILER) && defined(__INTEL_COMPILER_UPDATE)
  186. #define JSON_HEDLEY_INTEL_VERSION JSON_HEDLEY_VERSION_ENCODE(__INTEL_COMPILER / 100, __INTEL_COMPILER % 100, __INTEL_COMPILER_UPDATE)
  187. #elif defined(__INTEL_COMPILER)
  188. #define JSON_HEDLEY_INTEL_VERSION JSON_HEDLEY_VERSION_ENCODE(__INTEL_COMPILER / 100, __INTEL_COMPILER % 100, 0)
  189. #endif
  190. #if defined(JSON_HEDLEY_INTEL_VERSION_CHECK)
  191. #undef JSON_HEDLEY_INTEL_VERSION_CHECK
  192. #endif
  193. #if defined(JSON_HEDLEY_INTEL_VERSION)
  194. #define JSON_HEDLEY_INTEL_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_INTEL_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
  195. #else
  196. #define JSON_HEDLEY_INTEL_VERSION_CHECK(major,minor,patch) (0)
  197. #endif
  198. #if defined(JSON_HEDLEY_PGI_VERSION)
  199. #undef JSON_HEDLEY_PGI_VERSION
  200. #endif
  201. #if defined(__PGI) && defined(__PGIC__) && defined(__PGIC_MINOR__) && defined(__PGIC_PATCHLEVEL__)
  202. #define JSON_HEDLEY_PGI_VERSION JSON_HEDLEY_VERSION_ENCODE(__PGIC__, __PGIC_MINOR__, __PGIC_PATCHLEVEL__)
  203. #endif
  204. #if defined(JSON_HEDLEY_PGI_VERSION_CHECK)
  205. #undef JSON_HEDLEY_PGI_VERSION_CHECK
  206. #endif
  207. #if defined(JSON_HEDLEY_PGI_VERSION)
  208. #define JSON_HEDLEY_PGI_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_PGI_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
  209. #else
  210. #define JSON_HEDLEY_PGI_VERSION_CHECK(major,minor,patch) (0)
  211. #endif
  212. #if defined(JSON_HEDLEY_SUNPRO_VERSION)
  213. #undef JSON_HEDLEY_SUNPRO_VERSION
  214. #endif
  215. #if defined(__SUNPRO_C) && (__SUNPRO_C > 0x1000)
  216. #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)
  217. #elif defined(__SUNPRO_C)
  218. #define JSON_HEDLEY_SUNPRO_VERSION JSON_HEDLEY_VERSION_ENCODE((__SUNPRO_C >> 8) & 0xf, (__SUNPRO_C >> 4) & 0xf, (__SUNPRO_C) & 0xf)
  219. #elif defined(__SUNPRO_CC) && (__SUNPRO_CC > 0x1000)
  220. #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)
  221. #elif defined(__SUNPRO_CC)
  222. #define JSON_HEDLEY_SUNPRO_VERSION JSON_HEDLEY_VERSION_ENCODE((__SUNPRO_CC >> 8) & 0xf, (__SUNPRO_CC >> 4) & 0xf, (__SUNPRO_CC) & 0xf)
  223. #endif
  224. #if defined(JSON_HEDLEY_SUNPRO_VERSION_CHECK)
  225. #undef JSON_HEDLEY_SUNPRO_VERSION_CHECK
  226. #endif
  227. #if defined(JSON_HEDLEY_SUNPRO_VERSION)
  228. #define JSON_HEDLEY_SUNPRO_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_SUNPRO_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
  229. #else
  230. #define JSON_HEDLEY_SUNPRO_VERSION_CHECK(major,minor,patch) (0)
  231. #endif
  232. #if defined(JSON_HEDLEY_EMSCRIPTEN_VERSION)
  233. #undef JSON_HEDLEY_EMSCRIPTEN_VERSION
  234. #endif
  235. #if defined(__EMSCRIPTEN__)
  236. #define JSON_HEDLEY_EMSCRIPTEN_VERSION JSON_HEDLEY_VERSION_ENCODE(__EMSCRIPTEN_major__, __EMSCRIPTEN_minor__, __EMSCRIPTEN_tiny__)
  237. #endif
  238. #if defined(JSON_HEDLEY_EMSCRIPTEN_VERSION_CHECK)
  239. #undef JSON_HEDLEY_EMSCRIPTEN_VERSION_CHECK
  240. #endif
  241. #if defined(JSON_HEDLEY_EMSCRIPTEN_VERSION)
  242. #define JSON_HEDLEY_EMSCRIPTEN_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_EMSCRIPTEN_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
  243. #else
  244. #define JSON_HEDLEY_EMSCRIPTEN_VERSION_CHECK(major,minor,patch) (0)
  245. #endif
  246. #if defined(JSON_HEDLEY_ARM_VERSION)
  247. #undef JSON_HEDLEY_ARM_VERSION
  248. #endif
  249. #if defined(__CC_ARM) && defined(__ARMCOMPILER_VERSION)
  250. #define JSON_HEDLEY_ARM_VERSION JSON_HEDLEY_VERSION_ENCODE(__ARMCOMPILER_VERSION / 1000000, (__ARMCOMPILER_VERSION % 1000000) / 10000, (__ARMCOMPILER_VERSION % 10000) / 100)
  251. #elif defined(__CC_ARM) && defined(__ARMCC_VERSION)
  252. #define JSON_HEDLEY_ARM_VERSION JSON_HEDLEY_VERSION_ENCODE(__ARMCC_VERSION / 1000000, (__ARMCC_VERSION % 1000000) / 10000, (__ARMCC_VERSION % 10000) / 100)
  253. #endif
  254. #if defined(JSON_HEDLEY_ARM_VERSION_CHECK)
  255. #undef JSON_HEDLEY_ARM_VERSION_CHECK
  256. #endif
  257. #if defined(JSON_HEDLEY_ARM_VERSION)
  258. #define JSON_HEDLEY_ARM_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_ARM_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
  259. #else
  260. #define JSON_HEDLEY_ARM_VERSION_CHECK(major,minor,patch) (0)
  261. #endif
  262. #if defined(JSON_HEDLEY_IBM_VERSION)
  263. #undef JSON_HEDLEY_IBM_VERSION
  264. #endif
  265. #if defined(__ibmxl__)
  266. #define JSON_HEDLEY_IBM_VERSION JSON_HEDLEY_VERSION_ENCODE(__ibmxl_version__, __ibmxl_release__, __ibmxl_modification__)
  267. #elif defined(__xlC__) && defined(__xlC_ver__)
  268. #define JSON_HEDLEY_IBM_VERSION JSON_HEDLEY_VERSION_ENCODE(__xlC__ >> 8, __xlC__ & 0xff, (__xlC_ver__ >> 8) & 0xff)
  269. #elif defined(__xlC__)
  270. #define JSON_HEDLEY_IBM_VERSION JSON_HEDLEY_VERSION_ENCODE(__xlC__ >> 8, __xlC__ & 0xff, 0)
  271. #endif
  272. #if defined(JSON_HEDLEY_IBM_VERSION_CHECK)
  273. #undef JSON_HEDLEY_IBM_VERSION_CHECK
  274. #endif
  275. #if defined(JSON_HEDLEY_IBM_VERSION)
  276. #define JSON_HEDLEY_IBM_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_IBM_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
  277. #else
  278. #define JSON_HEDLEY_IBM_VERSION_CHECK(major,minor,patch) (0)
  279. #endif
  280. #if defined(JSON_HEDLEY_TI_VERSION)
  281. #undef JSON_HEDLEY_TI_VERSION
  282. #endif
  283. #if \
  284. defined(__TI_COMPILER_VERSION__) && \
  285. ( \
  286. defined(__TMS470__) || defined(__TI_ARM__) || \
  287. defined(__MSP430__) || \
  288. defined(__TMS320C2000__) \
  289. )
  290. #if (__TI_COMPILER_VERSION__ >= 16000000)
  291. #define JSON_HEDLEY_TI_VERSION JSON_HEDLEY_VERSION_ENCODE(__TI_COMPILER_VERSION__ / 1000000, (__TI_COMPILER_VERSION__ % 1000000) / 1000, (__TI_COMPILER_VERSION__ % 1000))
  292. #endif
  293. #endif
  294. #if defined(JSON_HEDLEY_TI_VERSION_CHECK)
  295. #undef JSON_HEDLEY_TI_VERSION_CHECK
  296. #endif
  297. #if defined(JSON_HEDLEY_TI_VERSION)
  298. #define JSON_HEDLEY_TI_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_TI_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
  299. #else
  300. #define JSON_HEDLEY_TI_VERSION_CHECK(major,minor,patch) (0)
  301. #endif
  302. #if defined(JSON_HEDLEY_TI_CL2000_VERSION)
  303. #undef JSON_HEDLEY_TI_CL2000_VERSION
  304. #endif
  305. #if defined(__TI_COMPILER_VERSION__) && defined(__TMS320C2000__)
  306. #define JSON_HEDLEY_TI_CL2000_VERSION JSON_HEDLEY_VERSION_ENCODE(__TI_COMPILER_VERSION__ / 1000000, (__TI_COMPILER_VERSION__ % 1000000) / 1000, (__TI_COMPILER_VERSION__ % 1000))
  307. #endif
  308. #if defined(JSON_HEDLEY_TI_CL2000_VERSION_CHECK)
  309. #undef JSON_HEDLEY_TI_CL2000_VERSION_CHECK
  310. #endif
  311. #if defined(JSON_HEDLEY_TI_CL2000_VERSION)
  312. #define JSON_HEDLEY_TI_CL2000_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_TI_CL2000_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
  313. #else
  314. #define JSON_HEDLEY_TI_CL2000_VERSION_CHECK(major,minor,patch) (0)
  315. #endif
  316. #if defined(JSON_HEDLEY_TI_CL430_VERSION)
  317. #undef JSON_HEDLEY_TI_CL430_VERSION
  318. #endif
  319. #if defined(__TI_COMPILER_VERSION__) && defined(__MSP430__)
  320. #define JSON_HEDLEY_TI_CL430_VERSION JSON_HEDLEY_VERSION_ENCODE(__TI_COMPILER_VERSION__ / 1000000, (__TI_COMPILER_VERSION__ % 1000000) / 1000, (__TI_COMPILER_VERSION__ % 1000))
  321. #endif
  322. #if defined(JSON_HEDLEY_TI_CL430_VERSION_CHECK)
  323. #undef JSON_HEDLEY_TI_CL430_VERSION_CHECK
  324. #endif
  325. #if defined(JSON_HEDLEY_TI_CL430_VERSION)
  326. #define JSON_HEDLEY_TI_CL430_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_TI_CL430_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
  327. #else
  328. #define JSON_HEDLEY_TI_CL430_VERSION_CHECK(major,minor,patch) (0)
  329. #endif
  330. #if defined(JSON_HEDLEY_TI_ARMCL_VERSION)
  331. #undef JSON_HEDLEY_TI_ARMCL_VERSION
  332. #endif
  333. #if defined(__TI_COMPILER_VERSION__) && (defined(__TMS470__) || defined(__TI_ARM__))
  334. #define JSON_HEDLEY_TI_ARMCL_VERSION JSON_HEDLEY_VERSION_ENCODE(__TI_COMPILER_VERSION__ / 1000000, (__TI_COMPILER_VERSION__ % 1000000) / 1000, (__TI_COMPILER_VERSION__ % 1000))
  335. #endif
  336. #if defined(JSON_HEDLEY_TI_ARMCL_VERSION_CHECK)
  337. #undef JSON_HEDLEY_TI_ARMCL_VERSION_CHECK
  338. #endif
  339. #if defined(JSON_HEDLEY_TI_ARMCL_VERSION)
  340. #define JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_TI_ARMCL_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
  341. #else
  342. #define JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(major,minor,patch) (0)
  343. #endif
  344. #if defined(JSON_HEDLEY_TI_CL6X_VERSION)
  345. #undef JSON_HEDLEY_TI_CL6X_VERSION
  346. #endif
  347. #if defined(__TI_COMPILER_VERSION__) && defined(__TMS320C6X__)
  348. #define JSON_HEDLEY_TI_CL6X_VERSION JSON_HEDLEY_VERSION_ENCODE(__TI_COMPILER_VERSION__ / 1000000, (__TI_COMPILER_VERSION__ % 1000000) / 1000, (__TI_COMPILER_VERSION__ % 1000))
  349. #endif
  350. #if defined(JSON_HEDLEY_TI_CL6X_VERSION_CHECK)
  351. #undef JSON_HEDLEY_TI_CL6X_VERSION_CHECK
  352. #endif
  353. #if defined(JSON_HEDLEY_TI_CL6X_VERSION)
  354. #define JSON_HEDLEY_TI_CL6X_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_TI_CL6X_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
  355. #else
  356. #define JSON_HEDLEY_TI_CL6X_VERSION_CHECK(major,minor,patch) (0)
  357. #endif
  358. #if defined(JSON_HEDLEY_TI_CL7X_VERSION)
  359. #undef JSON_HEDLEY_TI_CL7X_VERSION
  360. #endif
  361. #if defined(__TI_COMPILER_VERSION__) && defined(__C7000__)
  362. #define JSON_HEDLEY_TI_CL7X_VERSION JSON_HEDLEY_VERSION_ENCODE(__TI_COMPILER_VERSION__ / 1000000, (__TI_COMPILER_VERSION__ % 1000000) / 1000, (__TI_COMPILER_VERSION__ % 1000))
  363. #endif
  364. #if defined(JSON_HEDLEY_TI_CL7X_VERSION_CHECK)
  365. #undef JSON_HEDLEY_TI_CL7X_VERSION_CHECK
  366. #endif
  367. #if defined(JSON_HEDLEY_TI_CL7X_VERSION)
  368. #define JSON_HEDLEY_TI_CL7X_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_TI_CL7X_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
  369. #else
  370. #define JSON_HEDLEY_TI_CL7X_VERSION_CHECK(major,minor,patch) (0)
  371. #endif
  372. #if defined(JSON_HEDLEY_TI_CLPRU_VERSION)
  373. #undef JSON_HEDLEY_TI_CLPRU_VERSION
  374. #endif
  375. #if defined(__TI_COMPILER_VERSION__) && defined(__PRU__)
  376. #define JSON_HEDLEY_TI_CLPRU_VERSION JSON_HEDLEY_VERSION_ENCODE(__TI_COMPILER_VERSION__ / 1000000, (__TI_COMPILER_VERSION__ % 1000000) / 1000, (__TI_COMPILER_VERSION__ % 1000))
  377. #endif
  378. #if defined(JSON_HEDLEY_TI_CLPRU_VERSION_CHECK)
  379. #undef JSON_HEDLEY_TI_CLPRU_VERSION_CHECK
  380. #endif
  381. #if defined(JSON_HEDLEY_TI_CLPRU_VERSION)
  382. #define JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_TI_CLPRU_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
  383. #else
  384. #define JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(major,minor,patch) (0)
  385. #endif
  386. #if defined(JSON_HEDLEY_CRAY_VERSION)
  387. #undef JSON_HEDLEY_CRAY_VERSION
  388. #endif
  389. #if defined(_CRAYC)
  390. #if defined(_RELEASE_PATCHLEVEL)
  391. #define JSON_HEDLEY_CRAY_VERSION JSON_HEDLEY_VERSION_ENCODE(_RELEASE_MAJOR, _RELEASE_MINOR, _RELEASE_PATCHLEVEL)
  392. #else
  393. #define JSON_HEDLEY_CRAY_VERSION JSON_HEDLEY_VERSION_ENCODE(_RELEASE_MAJOR, _RELEASE_MINOR, 0)
  394. #endif
  395. #endif
  396. #if defined(JSON_HEDLEY_CRAY_VERSION_CHECK)
  397. #undef JSON_HEDLEY_CRAY_VERSION_CHECK
  398. #endif
  399. #if defined(JSON_HEDLEY_CRAY_VERSION)
  400. #define JSON_HEDLEY_CRAY_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_CRAY_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
  401. #else
  402. #define JSON_HEDLEY_CRAY_VERSION_CHECK(major,minor,patch) (0)
  403. #endif
  404. #if defined(JSON_HEDLEY_IAR_VERSION)
  405. #undef JSON_HEDLEY_IAR_VERSION
  406. #endif
  407. #if defined(__IAR_SYSTEMS_ICC__)
  408. #if __VER__ > 1000
  409. #define JSON_HEDLEY_IAR_VERSION JSON_HEDLEY_VERSION_ENCODE((__VER__ / 1000000), ((__VER__ / 1000) % 1000), (__VER__ % 1000))
  410. #else
  411. #define JSON_HEDLEY_IAR_VERSION JSON_HEDLEY_VERSION_ENCODE(VER / 100, __VER__ % 100, 0)
  412. #endif
  413. #endif
  414. #if defined(JSON_HEDLEY_IAR_VERSION_CHECK)
  415. #undef JSON_HEDLEY_IAR_VERSION_CHECK
  416. #endif
  417. #if defined(JSON_HEDLEY_IAR_VERSION)
  418. #define JSON_HEDLEY_IAR_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_IAR_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
  419. #else
  420. #define JSON_HEDLEY_IAR_VERSION_CHECK(major,minor,patch) (0)
  421. #endif
  422. #if defined(JSON_HEDLEY_TINYC_VERSION)
  423. #undef JSON_HEDLEY_TINYC_VERSION
  424. #endif
  425. #if defined(__TINYC__)
  426. #define JSON_HEDLEY_TINYC_VERSION JSON_HEDLEY_VERSION_ENCODE(__TINYC__ / 1000, (__TINYC__ / 100) % 10, __TINYC__ % 100)
  427. #endif
  428. #if defined(JSON_HEDLEY_TINYC_VERSION_CHECK)
  429. #undef JSON_HEDLEY_TINYC_VERSION_CHECK
  430. #endif
  431. #if defined(JSON_HEDLEY_TINYC_VERSION)
  432. #define JSON_HEDLEY_TINYC_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_TINYC_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
  433. #else
  434. #define JSON_HEDLEY_TINYC_VERSION_CHECK(major,minor,patch) (0)
  435. #endif
  436. #if defined(JSON_HEDLEY_DMC_VERSION)
  437. #undef JSON_HEDLEY_DMC_VERSION
  438. #endif
  439. #if defined(__DMC__)
  440. #define JSON_HEDLEY_DMC_VERSION JSON_HEDLEY_VERSION_ENCODE(__DMC__ >> 8, (__DMC__ >> 4) & 0xf, __DMC__ & 0xf)
  441. #endif
  442. #if defined(JSON_HEDLEY_DMC_VERSION_CHECK)
  443. #undef JSON_HEDLEY_DMC_VERSION_CHECK
  444. #endif
  445. #if defined(JSON_HEDLEY_DMC_VERSION)
  446. #define JSON_HEDLEY_DMC_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_DMC_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
  447. #else
  448. #define JSON_HEDLEY_DMC_VERSION_CHECK(major,minor,patch) (0)
  449. #endif
  450. #if defined(JSON_HEDLEY_COMPCERT_VERSION)
  451. #undef JSON_HEDLEY_COMPCERT_VERSION
  452. #endif
  453. #if defined(__COMPCERT_VERSION__)
  454. #define JSON_HEDLEY_COMPCERT_VERSION JSON_HEDLEY_VERSION_ENCODE(__COMPCERT_VERSION__ / 10000, (__COMPCERT_VERSION__ / 100) % 100, __COMPCERT_VERSION__ % 100)
  455. #endif
  456. #if defined(JSON_HEDLEY_COMPCERT_VERSION_CHECK)
  457. #undef JSON_HEDLEY_COMPCERT_VERSION_CHECK
  458. #endif
  459. #if defined(JSON_HEDLEY_COMPCERT_VERSION)
  460. #define JSON_HEDLEY_COMPCERT_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_COMPCERT_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
  461. #else
  462. #define JSON_HEDLEY_COMPCERT_VERSION_CHECK(major,minor,patch) (0)
  463. #endif
  464. #if defined(JSON_HEDLEY_PELLES_VERSION)
  465. #undef JSON_HEDLEY_PELLES_VERSION
  466. #endif
  467. #if defined(__POCC__)
  468. #define JSON_HEDLEY_PELLES_VERSION JSON_HEDLEY_VERSION_ENCODE(__POCC__ / 100, __POCC__ % 100, 0)
  469. #endif
  470. #if defined(JSON_HEDLEY_PELLES_VERSION_CHECK)
  471. #undef JSON_HEDLEY_PELLES_VERSION_CHECK
  472. #endif
  473. #if defined(JSON_HEDLEY_PELLES_VERSION)
  474. #define JSON_HEDLEY_PELLES_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_PELLES_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
  475. #else
  476. #define JSON_HEDLEY_PELLES_VERSION_CHECK(major,minor,patch) (0)
  477. #endif
  478. #if defined(JSON_HEDLEY_GCC_VERSION)
  479. #undef JSON_HEDLEY_GCC_VERSION
  480. #endif
  481. #if \
  482. defined(JSON_HEDLEY_GNUC_VERSION) && \
  483. !defined(__clang__) && \
  484. !defined(JSON_HEDLEY_INTEL_VERSION) && \
  485. !defined(JSON_HEDLEY_PGI_VERSION) && \
  486. !defined(JSON_HEDLEY_ARM_VERSION) && \
  487. !defined(JSON_HEDLEY_TI_VERSION) && \
  488. !defined(JSON_HEDLEY_TI_ARMCL_VERSION) && \
  489. !defined(JSON_HEDLEY_TI_CL430_VERSION) && \
  490. !defined(JSON_HEDLEY_TI_CL2000_VERSION) && \
  491. !defined(JSON_HEDLEY_TI_CL6X_VERSION) && \
  492. !defined(JSON_HEDLEY_TI_CL7X_VERSION) && \
  493. !defined(JSON_HEDLEY_TI_CLPRU_VERSION) && \
  494. !defined(__COMPCERT__)
  495. #define JSON_HEDLEY_GCC_VERSION JSON_HEDLEY_GNUC_VERSION
  496. #endif
  497. #if defined(JSON_HEDLEY_GCC_VERSION_CHECK)
  498. #undef JSON_HEDLEY_GCC_VERSION_CHECK
  499. #endif
  500. #if defined(JSON_HEDLEY_GCC_VERSION)
  501. #define JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_GCC_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
  502. #else
  503. #define JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch) (0)
  504. #endif
  505. #if defined(JSON_HEDLEY_HAS_ATTRIBUTE)
  506. #undef JSON_HEDLEY_HAS_ATTRIBUTE
  507. #endif
  508. #if defined(__has_attribute)
  509. #define JSON_HEDLEY_HAS_ATTRIBUTE(attribute) __has_attribute(attribute)
  510. #else
  511. #define JSON_HEDLEY_HAS_ATTRIBUTE(attribute) (0)
  512. #endif
  513. #if defined(JSON_HEDLEY_GNUC_HAS_ATTRIBUTE)
  514. #undef JSON_HEDLEY_GNUC_HAS_ATTRIBUTE
  515. #endif
  516. #if defined(__has_attribute)
  517. #define JSON_HEDLEY_GNUC_HAS_ATTRIBUTE(attribute,major,minor,patch) __has_attribute(attribute)
  518. #else
  519. #define JSON_HEDLEY_GNUC_HAS_ATTRIBUTE(attribute,major,minor,patch) JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch)
  520. #endif
  521. #if defined(JSON_HEDLEY_GCC_HAS_ATTRIBUTE)
  522. #undef JSON_HEDLEY_GCC_HAS_ATTRIBUTE
  523. #endif
  524. #if defined(__has_attribute)
  525. #define JSON_HEDLEY_GCC_HAS_ATTRIBUTE(attribute,major,minor,patch) __has_attribute(attribute)
  526. #else
  527. #define JSON_HEDLEY_GCC_HAS_ATTRIBUTE(attribute,major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch)
  528. #endif
  529. #if defined(JSON_HEDLEY_HAS_CPP_ATTRIBUTE)
  530. #undef JSON_HEDLEY_HAS_CPP_ATTRIBUTE
  531. #endif
  532. #if \
  533. defined(__has_cpp_attribute) && \
  534. defined(__cplusplus) && \
  535. (!defined(JSON_HEDLEY_SUNPRO_VERSION) || JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,15,0))
  536. #define JSON_HEDLEY_HAS_CPP_ATTRIBUTE(attribute) __has_cpp_attribute(attribute)
  537. #else
  538. #define JSON_HEDLEY_HAS_CPP_ATTRIBUTE(attribute) (0)
  539. #endif
  540. #if defined(JSON_HEDLEY_HAS_CPP_ATTRIBUTE_NS)
  541. #undef JSON_HEDLEY_HAS_CPP_ATTRIBUTE_NS
  542. #endif
  543. #if !defined(__cplusplus) || !defined(__has_cpp_attribute)
  544. #define JSON_HEDLEY_HAS_CPP_ATTRIBUTE_NS(ns,attribute) (0)
  545. #elif \
  546. !defined(JSON_HEDLEY_PGI_VERSION) && \
  547. !defined(JSON_HEDLEY_IAR_VERSION) && \
  548. (!defined(JSON_HEDLEY_SUNPRO_VERSION) || JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,15,0)) && \
  549. (!defined(JSON_HEDLEY_MSVC_VERSION) || JSON_HEDLEY_MSVC_VERSION_CHECK(19,20,0))
  550. #define JSON_HEDLEY_HAS_CPP_ATTRIBUTE_NS(ns,attribute) JSON_HEDLEY_HAS_CPP_ATTRIBUTE(ns::attribute)
  551. #else
  552. #define JSON_HEDLEY_HAS_CPP_ATTRIBUTE_NS(ns,attribute) (0)
  553. #endif
  554. #if defined(JSON_HEDLEY_GNUC_HAS_CPP_ATTRIBUTE)
  555. #undef JSON_HEDLEY_GNUC_HAS_CPP_ATTRIBUTE
  556. #endif
  557. #if defined(__has_cpp_attribute) && defined(__cplusplus)
  558. #define JSON_HEDLEY_GNUC_HAS_CPP_ATTRIBUTE(attribute,major,minor,patch) __has_cpp_attribute(attribute)
  559. #else
  560. #define JSON_HEDLEY_GNUC_HAS_CPP_ATTRIBUTE(attribute,major,minor,patch) JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch)
  561. #endif
  562. #if defined(JSON_HEDLEY_GCC_HAS_CPP_ATTRIBUTE)
  563. #undef JSON_HEDLEY_GCC_HAS_CPP_ATTRIBUTE
  564. #endif
  565. #if defined(__has_cpp_attribute) && defined(__cplusplus)
  566. #define JSON_HEDLEY_GCC_HAS_CPP_ATTRIBUTE(attribute,major,minor,patch) __has_cpp_attribute(attribute)
  567. #else
  568. #define JSON_HEDLEY_GCC_HAS_CPP_ATTRIBUTE(attribute,major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch)
  569. #endif
  570. #if defined(JSON_HEDLEY_HAS_BUILTIN)
  571. #undef JSON_HEDLEY_HAS_BUILTIN
  572. #endif
  573. #if defined(__has_builtin)
  574. #define JSON_HEDLEY_HAS_BUILTIN(builtin) __has_builtin(builtin)
  575. #else
  576. #define JSON_HEDLEY_HAS_BUILTIN(builtin) (0)
  577. #endif
  578. #if defined(JSON_HEDLEY_GNUC_HAS_BUILTIN)
  579. #undef JSON_HEDLEY_GNUC_HAS_BUILTIN
  580. #endif
  581. #if defined(__has_builtin)
  582. #define JSON_HEDLEY_GNUC_HAS_BUILTIN(builtin,major,minor,patch) __has_builtin(builtin)
  583. #else
  584. #define JSON_HEDLEY_GNUC_HAS_BUILTIN(builtin,major,minor,patch) JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch)
  585. #endif
  586. #if defined(JSON_HEDLEY_GCC_HAS_BUILTIN)
  587. #undef JSON_HEDLEY_GCC_HAS_BUILTIN
  588. #endif
  589. #if defined(__has_builtin)
  590. #define JSON_HEDLEY_GCC_HAS_BUILTIN(builtin,major,minor,patch) __has_builtin(builtin)
  591. #else
  592. #define JSON_HEDLEY_GCC_HAS_BUILTIN(builtin,major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch)
  593. #endif
  594. #if defined(JSON_HEDLEY_HAS_FEATURE)
  595. #undef JSON_HEDLEY_HAS_FEATURE
  596. #endif
  597. #if defined(__has_feature)
  598. #define JSON_HEDLEY_HAS_FEATURE(feature) __has_feature(feature)
  599. #else
  600. #define JSON_HEDLEY_HAS_FEATURE(feature) (0)
  601. #endif
  602. #if defined(JSON_HEDLEY_GNUC_HAS_FEATURE)
  603. #undef JSON_HEDLEY_GNUC_HAS_FEATURE
  604. #endif
  605. #if defined(__has_feature)
  606. #define JSON_HEDLEY_GNUC_HAS_FEATURE(feature,major,minor,patch) __has_feature(feature)
  607. #else
  608. #define JSON_HEDLEY_GNUC_HAS_FEATURE(feature,major,minor,patch) JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch)
  609. #endif
  610. #if defined(JSON_HEDLEY_GCC_HAS_FEATURE)
  611. #undef JSON_HEDLEY_GCC_HAS_FEATURE
  612. #endif
  613. #if defined(__has_feature)
  614. #define JSON_HEDLEY_GCC_HAS_FEATURE(feature,major,minor,patch) __has_feature(feature)
  615. #else
  616. #define JSON_HEDLEY_GCC_HAS_FEATURE(feature,major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch)
  617. #endif
  618. #if defined(JSON_HEDLEY_HAS_EXTENSION)
  619. #undef JSON_HEDLEY_HAS_EXTENSION
  620. #endif
  621. #if defined(__has_extension)
  622. #define JSON_HEDLEY_HAS_EXTENSION(extension) __has_extension(extension)
  623. #else
  624. #define JSON_HEDLEY_HAS_EXTENSION(extension) (0)
  625. #endif
  626. #if defined(JSON_HEDLEY_GNUC_HAS_EXTENSION)
  627. #undef JSON_HEDLEY_GNUC_HAS_EXTENSION
  628. #endif
  629. #if defined(__has_extension)
  630. #define JSON_HEDLEY_GNUC_HAS_EXTENSION(extension,major,minor,patch) __has_extension(extension)
  631. #else
  632. #define JSON_HEDLEY_GNUC_HAS_EXTENSION(extension,major,minor,patch) JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch)
  633. #endif
  634. #if defined(JSON_HEDLEY_GCC_HAS_EXTENSION)
  635. #undef JSON_HEDLEY_GCC_HAS_EXTENSION
  636. #endif
  637. #if defined(__has_extension)
  638. #define JSON_HEDLEY_GCC_HAS_EXTENSION(extension,major,minor,patch) __has_extension(extension)
  639. #else
  640. #define JSON_HEDLEY_GCC_HAS_EXTENSION(extension,major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch)
  641. #endif
  642. #if defined(JSON_HEDLEY_HAS_DECLSPEC_ATTRIBUTE)
  643. #undef JSON_HEDLEY_HAS_DECLSPEC_ATTRIBUTE
  644. #endif
  645. #if defined(__has_declspec_attribute)
  646. #define JSON_HEDLEY_HAS_DECLSPEC_ATTRIBUTE(attribute) __has_declspec_attribute(attribute)
  647. #else
  648. #define JSON_HEDLEY_HAS_DECLSPEC_ATTRIBUTE(attribute) (0)
  649. #endif
  650. #if defined(JSON_HEDLEY_GNUC_HAS_DECLSPEC_ATTRIBUTE)
  651. #undef JSON_HEDLEY_GNUC_HAS_DECLSPEC_ATTRIBUTE
  652. #endif
  653. #if defined(__has_declspec_attribute)
  654. #define JSON_HEDLEY_GNUC_HAS_DECLSPEC_ATTRIBUTE(attribute,major,minor,patch) __has_declspec_attribute(attribute)
  655. #else
  656. #define JSON_HEDLEY_GNUC_HAS_DECLSPEC_ATTRIBUTE(attribute,major,minor,patch) JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch)
  657. #endif
  658. #if defined(JSON_HEDLEY_GCC_HAS_DECLSPEC_ATTRIBUTE)
  659. #undef JSON_HEDLEY_GCC_HAS_DECLSPEC_ATTRIBUTE
  660. #endif
  661. #if defined(__has_declspec_attribute)
  662. #define JSON_HEDLEY_GCC_HAS_DECLSPEC_ATTRIBUTE(attribute,major,minor,patch) __has_declspec_attribute(attribute)
  663. #else
  664. #define JSON_HEDLEY_GCC_HAS_DECLSPEC_ATTRIBUTE(attribute,major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch)
  665. #endif
  666. #if defined(JSON_HEDLEY_HAS_WARNING)
  667. #undef JSON_HEDLEY_HAS_WARNING
  668. #endif
  669. #if defined(__has_warning)
  670. #define JSON_HEDLEY_HAS_WARNING(warning) __has_warning(warning)
  671. #else
  672. #define JSON_HEDLEY_HAS_WARNING(warning) (0)
  673. #endif
  674. #if defined(JSON_HEDLEY_GNUC_HAS_WARNING)
  675. #undef JSON_HEDLEY_GNUC_HAS_WARNING
  676. #endif
  677. #if defined(__has_warning)
  678. #define JSON_HEDLEY_GNUC_HAS_WARNING(warning,major,minor,patch) __has_warning(warning)
  679. #else
  680. #define JSON_HEDLEY_GNUC_HAS_WARNING(warning,major,minor,patch) JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch)
  681. #endif
  682. #if defined(JSON_HEDLEY_GCC_HAS_WARNING)
  683. #undef JSON_HEDLEY_GCC_HAS_WARNING
  684. #endif
  685. #if defined(__has_warning)
  686. #define JSON_HEDLEY_GCC_HAS_WARNING(warning,major,minor,patch) __has_warning(warning)
  687. #else
  688. #define JSON_HEDLEY_GCC_HAS_WARNING(warning,major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch)
  689. #endif
  690. /* JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_ is for
  691. HEDLEY INTERNAL USE ONLY. API subject to change without notice. */
  692. #if defined(JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_)
  693. #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_
  694. #endif
  695. #if defined(__cplusplus)
  696. # if JSON_HEDLEY_HAS_WARNING("-Wc++98-compat")
  697. # if JSON_HEDLEY_HAS_WARNING("-Wc++17-extensions")
  698. # define JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_(xpr) \
  699. JSON_HEDLEY_DIAGNOSTIC_PUSH \
  700. _Pragma("clang diagnostic ignored \"-Wc++98-compat\"") \
  701. _Pragma("clang diagnostic ignored \"-Wc++17-extensions\"") \
  702. xpr \
  703. JSON_HEDLEY_DIAGNOSTIC_POP
  704. # else
  705. # define JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_(xpr) \
  706. JSON_HEDLEY_DIAGNOSTIC_PUSH \
  707. _Pragma("clang diagnostic ignored \"-Wc++98-compat\"") \
  708. xpr \
  709. JSON_HEDLEY_DIAGNOSTIC_POP
  710. # endif
  711. # endif
  712. #endif
  713. #if !defined(JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_)
  714. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_(x) x
  715. #endif
  716. #if defined(JSON_HEDLEY_CONST_CAST)
  717. #undef JSON_HEDLEY_CONST_CAST
  718. #endif
  719. #if defined(__cplusplus)
  720. # define JSON_HEDLEY_CONST_CAST(T, expr) (const_cast<T>(expr))
  721. #elif \
  722. JSON_HEDLEY_HAS_WARNING("-Wcast-qual") || \
  723. JSON_HEDLEY_GCC_VERSION_CHECK(4,6,0) || \
  724. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0)
  725. # define JSON_HEDLEY_CONST_CAST(T, expr) (__extension__ ({ \
  726. JSON_HEDLEY_DIAGNOSTIC_PUSH \
  727. JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL \
  728. ((T) (expr)); \
  729. JSON_HEDLEY_DIAGNOSTIC_POP \
  730. }))
  731. #else
  732. # define JSON_HEDLEY_CONST_CAST(T, expr) ((T) (expr))
  733. #endif
  734. #if defined(JSON_HEDLEY_REINTERPRET_CAST)
  735. #undef JSON_HEDLEY_REINTERPRET_CAST
  736. #endif
  737. #if defined(__cplusplus)
  738. #define JSON_HEDLEY_REINTERPRET_CAST(T, expr) (reinterpret_cast<T>(expr))
  739. #else
  740. #define JSON_HEDLEY_REINTERPRET_CAST(T, expr) ((T) (expr))
  741. #endif
  742. #if defined(JSON_HEDLEY_STATIC_CAST)
  743. #undef JSON_HEDLEY_STATIC_CAST
  744. #endif
  745. #if defined(__cplusplus)
  746. #define JSON_HEDLEY_STATIC_CAST(T, expr) (static_cast<T>(expr))
  747. #else
  748. #define JSON_HEDLEY_STATIC_CAST(T, expr) ((T) (expr))
  749. #endif
  750. #if defined(JSON_HEDLEY_CPP_CAST)
  751. #undef JSON_HEDLEY_CPP_CAST
  752. #endif
  753. #if defined(__cplusplus)
  754. # if JSON_HEDLEY_HAS_WARNING("-Wold-style-cast")
  755. # define JSON_HEDLEY_CPP_CAST(T, expr) \
  756. JSON_HEDLEY_DIAGNOSTIC_PUSH \
  757. _Pragma("clang diagnostic ignored \"-Wold-style-cast\"") \
  758. ((T) (expr)) \
  759. JSON_HEDLEY_DIAGNOSTIC_POP
  760. # elif JSON_HEDLEY_IAR_VERSION_CHECK(8,3,0)
  761. # define JSON_HEDLEY_CPP_CAST(T, expr) \
  762. JSON_HEDLEY_DIAGNOSTIC_PUSH \
  763. _Pragma("diag_suppress=Pe137") \
  764. JSON_HEDLEY_DIAGNOSTIC_POP \
  765. # else
  766. # define JSON_HEDLEY_CPP_CAST(T, expr) ((T) (expr))
  767. # endif
  768. #else
  769. # define JSON_HEDLEY_CPP_CAST(T, expr) (expr)
  770. #endif
  771. #if \
  772. (defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L)) || \
  773. defined(__clang__) || \
  774. JSON_HEDLEY_GCC_VERSION_CHECK(3,0,0) || \
  775. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
  776. JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0) || \
  777. JSON_HEDLEY_PGI_VERSION_CHECK(18,4,0) || \
  778. JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \
  779. JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \
  780. JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,7,0) || \
  781. JSON_HEDLEY_TI_CL430_VERSION_CHECK(2,0,1) || \
  782. JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,1,0) || \
  783. JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,0,0) || \
  784. JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \
  785. JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \
  786. JSON_HEDLEY_CRAY_VERSION_CHECK(5,0,0) || \
  787. JSON_HEDLEY_TINYC_VERSION_CHECK(0,9,17) || \
  788. JSON_HEDLEY_SUNPRO_VERSION_CHECK(8,0,0) || \
  789. (JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) && defined(__C99_PRAGMA_OPERATOR))
  790. #define JSON_HEDLEY_PRAGMA(value) _Pragma(#value)
  791. #elif JSON_HEDLEY_MSVC_VERSION_CHECK(15,0,0)
  792. #define JSON_HEDLEY_PRAGMA(value) __pragma(value)
  793. #else
  794. #define JSON_HEDLEY_PRAGMA(value)
  795. #endif
  796. #if defined(JSON_HEDLEY_DIAGNOSTIC_PUSH)
  797. #undef JSON_HEDLEY_DIAGNOSTIC_PUSH
  798. #endif
  799. #if defined(JSON_HEDLEY_DIAGNOSTIC_POP)
  800. #undef JSON_HEDLEY_DIAGNOSTIC_POP
  801. #endif
  802. #if defined(__clang__)
  803. #define JSON_HEDLEY_DIAGNOSTIC_PUSH _Pragma("clang diagnostic push")
  804. #define JSON_HEDLEY_DIAGNOSTIC_POP _Pragma("clang diagnostic pop")
  805. #elif JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0)
  806. #define JSON_HEDLEY_DIAGNOSTIC_PUSH _Pragma("warning(push)")
  807. #define JSON_HEDLEY_DIAGNOSTIC_POP _Pragma("warning(pop)")
  808. #elif JSON_HEDLEY_GCC_VERSION_CHECK(4,6,0)
  809. #define JSON_HEDLEY_DIAGNOSTIC_PUSH _Pragma("GCC diagnostic push")
  810. #define JSON_HEDLEY_DIAGNOSTIC_POP _Pragma("GCC diagnostic pop")
  811. #elif JSON_HEDLEY_MSVC_VERSION_CHECK(15,0,0)
  812. #define JSON_HEDLEY_DIAGNOSTIC_PUSH __pragma(warning(push))
  813. #define JSON_HEDLEY_DIAGNOSTIC_POP __pragma(warning(pop))
  814. #elif JSON_HEDLEY_ARM_VERSION_CHECK(5,6,0)
  815. #define JSON_HEDLEY_DIAGNOSTIC_PUSH _Pragma("push")
  816. #define JSON_HEDLEY_DIAGNOSTIC_POP _Pragma("pop")
  817. #elif \
  818. JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \
  819. JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \
  820. JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,4,0) || \
  821. JSON_HEDLEY_TI_CL6X_VERSION_CHECK(8,1,0) || \
  822. JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \
  823. JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0)
  824. #define JSON_HEDLEY_DIAGNOSTIC_PUSH _Pragma("diag_push")
  825. #define JSON_HEDLEY_DIAGNOSTIC_POP _Pragma("diag_pop")
  826. #elif JSON_HEDLEY_PELLES_VERSION_CHECK(2,90,0)
  827. #define JSON_HEDLEY_DIAGNOSTIC_PUSH _Pragma("warning(push)")
  828. #define JSON_HEDLEY_DIAGNOSTIC_POP _Pragma("warning(pop)")
  829. #else
  830. #define JSON_HEDLEY_DIAGNOSTIC_PUSH
  831. #define JSON_HEDLEY_DIAGNOSTIC_POP
  832. #endif
  833. #if defined(JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED)
  834. #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED
  835. #endif
  836. #if JSON_HEDLEY_HAS_WARNING("-Wdeprecated-declarations")
  837. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("clang diagnostic ignored \"-Wdeprecated-declarations\"")
  838. #elif JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0)
  839. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("warning(disable:1478 1786)")
  840. #elif JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0)
  841. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("diag_suppress 1215,1444")
  842. #elif JSON_HEDLEY_GCC_VERSION_CHECK(4,3,0)
  843. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("GCC diagnostic ignored \"-Wdeprecated-declarations\"")
  844. #elif JSON_HEDLEY_MSVC_VERSION_CHECK(15,0,0)
  845. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED __pragma(warning(disable:4996))
  846. #elif \
  847. JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \
  848. (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  849. JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \
  850. (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  851. JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \
  852. (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  853. JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \
  854. (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  855. JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \
  856. JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \
  857. JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0)
  858. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("diag_suppress 1291,1718")
  859. #elif JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,13,0) && !defined(__cplusplus)
  860. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("error_messages(off,E_DEPRECATED_ATT,E_DEPRECATED_ATT_MESS)")
  861. #elif JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,13,0) && defined(__cplusplus)
  862. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("error_messages(off,symdeprecated,symdeprecated2)")
  863. #elif JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0)
  864. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("diag_suppress=Pe1444,Pe1215")
  865. #elif JSON_HEDLEY_PELLES_VERSION_CHECK(2,90,0)
  866. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("warn(disable:2241)")
  867. #else
  868. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED
  869. #endif
  870. #if defined(JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS)
  871. #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS
  872. #endif
  873. #if JSON_HEDLEY_HAS_WARNING("-Wunknown-pragmas")
  874. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("clang diagnostic ignored \"-Wunknown-pragmas\"")
  875. #elif JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0)
  876. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("warning(disable:161)")
  877. #elif JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0)
  878. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("diag_suppress 1675")
  879. #elif JSON_HEDLEY_GCC_VERSION_CHECK(4,3,0)
  880. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("GCC diagnostic ignored \"-Wunknown-pragmas\"")
  881. #elif JSON_HEDLEY_MSVC_VERSION_CHECK(15,0,0)
  882. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS __pragma(warning(disable:4068))
  883. #elif \
  884. JSON_HEDLEY_TI_VERSION_CHECK(16,9,0) || \
  885. JSON_HEDLEY_TI_CL6X_VERSION_CHECK(8,0,0) || \
  886. JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \
  887. JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,3,0)
  888. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("diag_suppress 163")
  889. #elif JSON_HEDLEY_TI_CL6X_VERSION_CHECK(8,0,0)
  890. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("diag_suppress 163")
  891. #elif JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0)
  892. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("diag_suppress=Pe161")
  893. #else
  894. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS
  895. #endif
  896. #if defined(JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES)
  897. #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES
  898. #endif
  899. #if JSON_HEDLEY_HAS_WARNING("-Wunknown-attributes")
  900. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("clang diagnostic ignored \"-Wunknown-attributes\"")
  901. #elif JSON_HEDLEY_GCC_VERSION_CHECK(4,6,0)
  902. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("GCC diagnostic ignored \"-Wdeprecated-declarations\"")
  903. #elif JSON_HEDLEY_INTEL_VERSION_CHECK(17,0,0)
  904. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("warning(disable:1292)")
  905. #elif JSON_HEDLEY_MSVC_VERSION_CHECK(19,0,0)
  906. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES __pragma(warning(disable:5030))
  907. #elif JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0)
  908. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("diag_suppress 1097")
  909. #elif JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,14,0) && defined(__cplusplus)
  910. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("error_messages(off,attrskipunsup)")
  911. #elif \
  912. JSON_HEDLEY_TI_VERSION_CHECK(18,1,0) || \
  913. JSON_HEDLEY_TI_CL6X_VERSION_CHECK(8,3,0) || \
  914. JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0)
  915. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("diag_suppress 1173")
  916. #elif JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0)
  917. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("diag_suppress=Pe1097")
  918. #else
  919. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES
  920. #endif
  921. #if defined(JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL)
  922. #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL
  923. #endif
  924. #if JSON_HEDLEY_HAS_WARNING("-Wcast-qual")
  925. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL _Pragma("clang diagnostic ignored \"-Wcast-qual\"")
  926. #elif JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0)
  927. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL _Pragma("warning(disable:2203 2331)")
  928. #elif JSON_HEDLEY_GCC_VERSION_CHECK(3,0,0)
  929. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL _Pragma("GCC diagnostic ignored \"-Wcast-qual\"")
  930. #else
  931. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL
  932. #endif
  933. #if defined(JSON_HEDLEY_DEPRECATED)
  934. #undef JSON_HEDLEY_DEPRECATED
  935. #endif
  936. #if defined(JSON_HEDLEY_DEPRECATED_FOR)
  937. #undef JSON_HEDLEY_DEPRECATED_FOR
  938. #endif
  939. #if JSON_HEDLEY_MSVC_VERSION_CHECK(14,0,0)
  940. #define JSON_HEDLEY_DEPRECATED(since) __declspec(deprecated("Since " # since))
  941. #define JSON_HEDLEY_DEPRECATED_FOR(since, replacement) __declspec(deprecated("Since " #since "; use " #replacement))
  942. #elif defined(__cplusplus) && (__cplusplus >= 201402L)
  943. #define JSON_HEDLEY_DEPRECATED(since) JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[deprecated("Since " #since)]])
  944. #define JSON_HEDLEY_DEPRECATED_FOR(since, replacement) JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[deprecated("Since " #since "; use " #replacement)]])
  945. #elif \
  946. JSON_HEDLEY_HAS_EXTENSION(attribute_deprecated_with_message) || \
  947. JSON_HEDLEY_GCC_VERSION_CHECK(4,5,0) || \
  948. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
  949. JSON_HEDLEY_ARM_VERSION_CHECK(5,6,0) || \
  950. JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,13,0) || \
  951. JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0) || \
  952. JSON_HEDLEY_TI_VERSION_CHECK(18,1,0) || \
  953. JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(18,1,0) || \
  954. JSON_HEDLEY_TI_CL6X_VERSION_CHECK(8,3,0) || \
  955. JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \
  956. JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,3,0)
  957. #define JSON_HEDLEY_DEPRECATED(since) __attribute__((__deprecated__("Since " #since)))
  958. #define JSON_HEDLEY_DEPRECATED_FOR(since, replacement) __attribute__((__deprecated__("Since " #since "; use " #replacement)))
  959. #elif \
  960. JSON_HEDLEY_HAS_ATTRIBUTE(deprecated) || \
  961. JSON_HEDLEY_GCC_VERSION_CHECK(3,1,0) || \
  962. JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \
  963. JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \
  964. (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  965. JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \
  966. (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  967. JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \
  968. (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  969. JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \
  970. (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  971. JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \
  972. JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \
  973. JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0)
  974. #define JSON_HEDLEY_DEPRECATED(since) __attribute__((__deprecated__))
  975. #define JSON_HEDLEY_DEPRECATED_FOR(since, replacement) __attribute__((__deprecated__))
  976. #elif \
  977. JSON_HEDLEY_MSVC_VERSION_CHECK(13,10,0) || \
  978. JSON_HEDLEY_PELLES_VERSION_CHECK(6,50,0)
  979. #define JSON_HEDLEY_DEPRECATED(since) __declspec(deprecated)
  980. #define JSON_HEDLEY_DEPRECATED_FOR(since, replacement) __declspec(deprecated)
  981. #elif JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0)
  982. #define JSON_HEDLEY_DEPRECATED(since) _Pragma("deprecated")
  983. #define JSON_HEDLEY_DEPRECATED_FOR(since, replacement) _Pragma("deprecated")
  984. #else
  985. #define JSON_HEDLEY_DEPRECATED(since)
  986. #define JSON_HEDLEY_DEPRECATED_FOR(since, replacement)
  987. #endif
  988. #if defined(JSON_HEDLEY_UNAVAILABLE)
  989. #undef JSON_HEDLEY_UNAVAILABLE
  990. #endif
  991. #if \
  992. JSON_HEDLEY_HAS_ATTRIBUTE(warning) || \
  993. JSON_HEDLEY_GCC_VERSION_CHECK(4,3,0) || \
  994. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0)
  995. #define JSON_HEDLEY_UNAVAILABLE(available_since) __attribute__((__warning__("Not available until " #available_since)))
  996. #else
  997. #define JSON_HEDLEY_UNAVAILABLE(available_since)
  998. #endif
  999. #if defined(JSON_HEDLEY_WARN_UNUSED_RESULT)
  1000. #undef JSON_HEDLEY_WARN_UNUSED_RESULT
  1001. #endif
  1002. #if defined(JSON_HEDLEY_WARN_UNUSED_RESULT_MSG)
  1003. #undef JSON_HEDLEY_WARN_UNUSED_RESULT_MSG
  1004. #endif
  1005. #if (JSON_HEDLEY_HAS_CPP_ATTRIBUTE(nodiscard) >= 201907L)
  1006. #define JSON_HEDLEY_WARN_UNUSED_RESULT JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[nodiscard]])
  1007. #define JSON_HEDLEY_WARN_UNUSED_RESULT_MSG(msg) JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[nodiscard(msg)]])
  1008. #elif JSON_HEDLEY_HAS_CPP_ATTRIBUTE(nodiscard)
  1009. #define JSON_HEDLEY_WARN_UNUSED_RESULT JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[nodiscard]])
  1010. #define JSON_HEDLEY_WARN_UNUSED_RESULT_MSG(msg) JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[nodiscard]])
  1011. #elif \
  1012. JSON_HEDLEY_HAS_ATTRIBUTE(warn_unused_result) || \
  1013. JSON_HEDLEY_GCC_VERSION_CHECK(3,4,0) || \
  1014. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
  1015. JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \
  1016. (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  1017. JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \
  1018. (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  1019. JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \
  1020. (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  1021. JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \
  1022. (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  1023. JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \
  1024. JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \
  1025. JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \
  1026. (JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,15,0) && defined(__cplusplus)) || \
  1027. JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0)
  1028. #define JSON_HEDLEY_WARN_UNUSED_RESULT __attribute__((__warn_unused_result__))
  1029. #define JSON_HEDLEY_WARN_UNUSED_RESULT_MSG(msg) __attribute__((__warn_unused_result__))
  1030. #elif defined(_Check_return_) /* SAL */
  1031. #define JSON_HEDLEY_WARN_UNUSED_RESULT _Check_return_
  1032. #define JSON_HEDLEY_WARN_UNUSED_RESULT_MSG(msg) _Check_return_
  1033. #else
  1034. #define JSON_HEDLEY_WARN_UNUSED_RESULT
  1035. #define JSON_HEDLEY_WARN_UNUSED_RESULT_MSG(msg)
  1036. #endif
  1037. #if defined(JSON_HEDLEY_SENTINEL)
  1038. #undef JSON_HEDLEY_SENTINEL
  1039. #endif
  1040. #if \
  1041. JSON_HEDLEY_HAS_ATTRIBUTE(sentinel) || \
  1042. JSON_HEDLEY_GCC_VERSION_CHECK(4,0,0) || \
  1043. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
  1044. JSON_HEDLEY_ARM_VERSION_CHECK(5,4,0)
  1045. #define JSON_HEDLEY_SENTINEL(position) __attribute__((__sentinel__(position)))
  1046. #else
  1047. #define JSON_HEDLEY_SENTINEL(position)
  1048. #endif
  1049. #if defined(JSON_HEDLEY_NO_RETURN)
  1050. #undef JSON_HEDLEY_NO_RETURN
  1051. #endif
  1052. #if JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0)
  1053. #define JSON_HEDLEY_NO_RETURN __noreturn
  1054. #elif JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0)
  1055. #define JSON_HEDLEY_NO_RETURN __attribute__((__noreturn__))
  1056. #elif defined(__STDC_VERSION__) && __STDC_VERSION__ >= 201112L
  1057. #define JSON_HEDLEY_NO_RETURN _Noreturn
  1058. #elif defined(__cplusplus) && (__cplusplus >= 201103L)
  1059. #define JSON_HEDLEY_NO_RETURN JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[noreturn]])
  1060. #elif \
  1061. JSON_HEDLEY_HAS_ATTRIBUTE(noreturn) || \
  1062. JSON_HEDLEY_GCC_VERSION_CHECK(3,2,0) || \
  1063. JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,11,0) || \
  1064. JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \
  1065. JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \
  1066. JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \
  1067. (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  1068. JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \
  1069. (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  1070. JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \
  1071. (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  1072. JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \
  1073. (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  1074. JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \
  1075. JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \
  1076. JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0)
  1077. #define JSON_HEDLEY_NO_RETURN __attribute__((__noreturn__))
  1078. #elif JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,10,0)
  1079. #define JSON_HEDLEY_NO_RETURN _Pragma("does_not_return")
  1080. #elif JSON_HEDLEY_MSVC_VERSION_CHECK(13,10,0)
  1081. #define JSON_HEDLEY_NO_RETURN __declspec(noreturn)
  1082. #elif JSON_HEDLEY_TI_CL6X_VERSION_CHECK(6,0,0) && defined(__cplusplus)
  1083. #define JSON_HEDLEY_NO_RETURN _Pragma("FUNC_NEVER_RETURNS;")
  1084. #elif JSON_HEDLEY_COMPCERT_VERSION_CHECK(3,2,0)
  1085. #define JSON_HEDLEY_NO_RETURN __attribute((noreturn))
  1086. #elif JSON_HEDLEY_PELLES_VERSION_CHECK(9,0,0)
  1087. #define JSON_HEDLEY_NO_RETURN __declspec(noreturn)
  1088. #else
  1089. #define JSON_HEDLEY_NO_RETURN
  1090. #endif
  1091. #if defined(JSON_HEDLEY_NO_ESCAPE)
  1092. #undef JSON_HEDLEY_NO_ESCAPE
  1093. #endif
  1094. #if JSON_HEDLEY_HAS_ATTRIBUTE(noescape)
  1095. #define JSON_HEDLEY_NO_ESCAPE __attribute__((__noescape__))
  1096. #else
  1097. #define JSON_HEDLEY_NO_ESCAPE
  1098. #endif
  1099. #if defined(JSON_HEDLEY_UNREACHABLE)
  1100. #undef JSON_HEDLEY_UNREACHABLE
  1101. #endif
  1102. #if defined(JSON_HEDLEY_UNREACHABLE_RETURN)
  1103. #undef JSON_HEDLEY_UNREACHABLE_RETURN
  1104. #endif
  1105. #if defined(JSON_HEDLEY_ASSUME)
  1106. #undef JSON_HEDLEY_ASSUME
  1107. #endif
  1108. #if \
  1109. JSON_HEDLEY_MSVC_VERSION_CHECK(13,10,0) || \
  1110. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0)
  1111. #define JSON_HEDLEY_ASSUME(expr) __assume(expr)
  1112. #elif JSON_HEDLEY_HAS_BUILTIN(__builtin_assume)
  1113. #define JSON_HEDLEY_ASSUME(expr) __builtin_assume(expr)
  1114. #elif \
  1115. JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,2,0) || \
  1116. JSON_HEDLEY_TI_CL6X_VERSION_CHECK(4,0,0)
  1117. #if defined(__cplusplus)
  1118. #define JSON_HEDLEY_ASSUME(expr) std::_nassert(expr)
  1119. #else
  1120. #define JSON_HEDLEY_ASSUME(expr) _nassert(expr)
  1121. #endif
  1122. #endif
  1123. #if \
  1124. (JSON_HEDLEY_HAS_BUILTIN(__builtin_unreachable) && (!defined(JSON_HEDLEY_ARM_VERSION))) || \
  1125. JSON_HEDLEY_GCC_VERSION_CHECK(4,5,0) || \
  1126. JSON_HEDLEY_PGI_VERSION_CHECK(18,10,0) || \
  1127. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
  1128. JSON_HEDLEY_IBM_VERSION_CHECK(13,1,5)
  1129. #define JSON_HEDLEY_UNREACHABLE() __builtin_unreachable()
  1130. #elif defined(JSON_HEDLEY_ASSUME)
  1131. #define JSON_HEDLEY_UNREACHABLE() JSON_HEDLEY_ASSUME(0)
  1132. #endif
  1133. #if !defined(JSON_HEDLEY_ASSUME)
  1134. #if defined(JSON_HEDLEY_UNREACHABLE)
  1135. #define JSON_HEDLEY_ASSUME(expr) JSON_HEDLEY_STATIC_CAST(void, ((expr) ? 1 : (JSON_HEDLEY_UNREACHABLE(), 1)))
  1136. #else
  1137. #define JSON_HEDLEY_ASSUME(expr) JSON_HEDLEY_STATIC_CAST(void, expr)
  1138. #endif
  1139. #endif
  1140. #if defined(JSON_HEDLEY_UNREACHABLE)
  1141. #if \
  1142. JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,2,0) || \
  1143. JSON_HEDLEY_TI_CL6X_VERSION_CHECK(4,0,0)
  1144. #define JSON_HEDLEY_UNREACHABLE_RETURN(value) return (JSON_HEDLEY_STATIC_CAST(void, JSON_HEDLEY_ASSUME(0)), (value))
  1145. #else
  1146. #define JSON_HEDLEY_UNREACHABLE_RETURN(value) JSON_HEDLEY_UNREACHABLE()
  1147. #endif
  1148. #else
  1149. #define JSON_HEDLEY_UNREACHABLE_RETURN(value) return (value)
  1150. #endif
  1151. #if !defined(JSON_HEDLEY_UNREACHABLE)
  1152. #define JSON_HEDLEY_UNREACHABLE() JSON_HEDLEY_ASSUME(0)
  1153. #endif
  1154. JSON_HEDLEY_DIAGNOSTIC_PUSH
  1155. #if JSON_HEDLEY_HAS_WARNING("-Wpedantic")
  1156. #pragma clang diagnostic ignored "-Wpedantic"
  1157. #endif
  1158. #if JSON_HEDLEY_HAS_WARNING("-Wc++98-compat-pedantic") && defined(__cplusplus)
  1159. #pragma clang diagnostic ignored "-Wc++98-compat-pedantic"
  1160. #endif
  1161. #if JSON_HEDLEY_GCC_HAS_WARNING("-Wvariadic-macros",4,0,0)
  1162. #if defined(__clang__)
  1163. #pragma clang diagnostic ignored "-Wvariadic-macros"
  1164. #elif defined(JSON_HEDLEY_GCC_VERSION)
  1165. #pragma GCC diagnostic ignored "-Wvariadic-macros"
  1166. #endif
  1167. #endif
  1168. #if defined(JSON_HEDLEY_NON_NULL)
  1169. #undef JSON_HEDLEY_NON_NULL
  1170. #endif
  1171. #if \
  1172. JSON_HEDLEY_HAS_ATTRIBUTE(nonnull) || \
  1173. JSON_HEDLEY_GCC_VERSION_CHECK(3,3,0) || \
  1174. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
  1175. JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0)
  1176. #define JSON_HEDLEY_NON_NULL(...) __attribute__((__nonnull__(__VA_ARGS__)))
  1177. #else
  1178. #define JSON_HEDLEY_NON_NULL(...)
  1179. #endif
  1180. JSON_HEDLEY_DIAGNOSTIC_POP
  1181. #if defined(JSON_HEDLEY_PRINTF_FORMAT)
  1182. #undef JSON_HEDLEY_PRINTF_FORMAT
  1183. #endif
  1184. #if defined(__MINGW32__) && JSON_HEDLEY_GCC_HAS_ATTRIBUTE(format,4,4,0) && !defined(__USE_MINGW_ANSI_STDIO)
  1185. #define JSON_HEDLEY_PRINTF_FORMAT(string_idx,first_to_check) __attribute__((__format__(ms_printf, string_idx, first_to_check)))
  1186. #elif defined(__MINGW32__) && JSON_HEDLEY_GCC_HAS_ATTRIBUTE(format,4,4,0) && defined(__USE_MINGW_ANSI_STDIO)
  1187. #define JSON_HEDLEY_PRINTF_FORMAT(string_idx,first_to_check) __attribute__((__format__(gnu_printf, string_idx, first_to_check)))
  1188. #elif \
  1189. JSON_HEDLEY_HAS_ATTRIBUTE(format) || \
  1190. JSON_HEDLEY_GCC_VERSION_CHECK(3,1,0) || \
  1191. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
  1192. JSON_HEDLEY_ARM_VERSION_CHECK(5,6,0) || \
  1193. JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \
  1194. JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \
  1195. (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  1196. JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \
  1197. (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  1198. JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \
  1199. (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  1200. JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \
  1201. (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  1202. JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \
  1203. JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \
  1204. JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0)
  1205. #define JSON_HEDLEY_PRINTF_FORMAT(string_idx,first_to_check) __attribute__((__format__(__printf__, string_idx, first_to_check)))
  1206. #elif JSON_HEDLEY_PELLES_VERSION_CHECK(6,0,0)
  1207. #define JSON_HEDLEY_PRINTF_FORMAT(string_idx,first_to_check) __declspec(vaformat(printf,string_idx,first_to_check))
  1208. #else
  1209. #define JSON_HEDLEY_PRINTF_FORMAT(string_idx,first_to_check)
  1210. #endif
  1211. #if defined(JSON_HEDLEY_CONSTEXPR)
  1212. #undef JSON_HEDLEY_CONSTEXPR
  1213. #endif
  1214. #if defined(__cplusplus)
  1215. #if __cplusplus >= 201103L
  1216. #define JSON_HEDLEY_CONSTEXPR JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_(constexpr)
  1217. #endif
  1218. #endif
  1219. #if !defined(JSON_HEDLEY_CONSTEXPR)
  1220. #define JSON_HEDLEY_CONSTEXPR
  1221. #endif
  1222. #if defined(JSON_HEDLEY_PREDICT)
  1223. #undef JSON_HEDLEY_PREDICT
  1224. #endif
  1225. #if defined(JSON_HEDLEY_LIKELY)
  1226. #undef JSON_HEDLEY_LIKELY
  1227. #endif
  1228. #if defined(JSON_HEDLEY_UNLIKELY)
  1229. #undef JSON_HEDLEY_UNLIKELY
  1230. #endif
  1231. #if defined(JSON_HEDLEY_UNPREDICTABLE)
  1232. #undef JSON_HEDLEY_UNPREDICTABLE
  1233. #endif
  1234. #if JSON_HEDLEY_HAS_BUILTIN(__builtin_unpredictable)
  1235. #define JSON_HEDLEY_UNPREDICTABLE(expr) __builtin_unpredictable((expr))
  1236. #endif
  1237. #if \
  1238. JSON_HEDLEY_HAS_BUILTIN(__builtin_expect_with_probability) || \
  1239. JSON_HEDLEY_GCC_VERSION_CHECK(9,0,0)
  1240. # define JSON_HEDLEY_PREDICT(expr, value, probability) __builtin_expect_with_probability( (expr), (value), (probability))
  1241. # define JSON_HEDLEY_PREDICT_TRUE(expr, probability) __builtin_expect_with_probability(!!(expr), 1 , (probability))
  1242. # define JSON_HEDLEY_PREDICT_FALSE(expr, probability) __builtin_expect_with_probability(!!(expr), 0 , (probability))
  1243. # define JSON_HEDLEY_LIKELY(expr) __builtin_expect (!!(expr), 1 )
  1244. # define JSON_HEDLEY_UNLIKELY(expr) __builtin_expect (!!(expr), 0 )
  1245. #elif \
  1246. JSON_HEDLEY_HAS_BUILTIN(__builtin_expect) || \
  1247. JSON_HEDLEY_GCC_VERSION_CHECK(3,0,0) || \
  1248. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
  1249. (JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,15,0) && defined(__cplusplus)) || \
  1250. JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \
  1251. JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \
  1252. JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \
  1253. JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,7,0) || \
  1254. JSON_HEDLEY_TI_CL430_VERSION_CHECK(3,1,0) || \
  1255. JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,1,0) || \
  1256. JSON_HEDLEY_TI_CL6X_VERSION_CHECK(6,1,0) || \
  1257. JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \
  1258. JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \
  1259. JSON_HEDLEY_TINYC_VERSION_CHECK(0,9,27) || \
  1260. JSON_HEDLEY_CRAY_VERSION_CHECK(8,1,0)
  1261. # define JSON_HEDLEY_PREDICT(expr, expected, probability) \
  1262. (((probability) >= 0.9) ? __builtin_expect((expr), (expected)) : (JSON_HEDLEY_STATIC_CAST(void, expected), (expr)))
  1263. # define JSON_HEDLEY_PREDICT_TRUE(expr, probability) \
  1264. (__extension__ ({ \
  1265. double hedley_probability_ = (probability); \
  1266. ((hedley_probability_ >= 0.9) ? __builtin_expect(!!(expr), 1) : ((hedley_probability_ <= 0.1) ? __builtin_expect(!!(expr), 0) : !!(expr))); \
  1267. }))
  1268. # define JSON_HEDLEY_PREDICT_FALSE(expr, probability) \
  1269. (__extension__ ({ \
  1270. double hedley_probability_ = (probability); \
  1271. ((hedley_probability_ >= 0.9) ? __builtin_expect(!!(expr), 0) : ((hedley_probability_ <= 0.1) ? __builtin_expect(!!(expr), 1) : !!(expr))); \
  1272. }))
  1273. # define JSON_HEDLEY_LIKELY(expr) __builtin_expect(!!(expr), 1)
  1274. # define JSON_HEDLEY_UNLIKELY(expr) __builtin_expect(!!(expr), 0)
  1275. #else
  1276. # define JSON_HEDLEY_PREDICT(expr, expected, probability) (JSON_HEDLEY_STATIC_CAST(void, expected), (expr))
  1277. # define JSON_HEDLEY_PREDICT_TRUE(expr, probability) (!!(expr))
  1278. # define JSON_HEDLEY_PREDICT_FALSE(expr, probability) (!!(expr))
  1279. # define JSON_HEDLEY_LIKELY(expr) (!!(expr))
  1280. # define JSON_HEDLEY_UNLIKELY(expr) (!!(expr))
  1281. #endif
  1282. #if !defined(JSON_HEDLEY_UNPREDICTABLE)
  1283. #define JSON_HEDLEY_UNPREDICTABLE(expr) JSON_HEDLEY_PREDICT(expr, 1, 0.5)
  1284. #endif
  1285. #if defined(JSON_HEDLEY_MALLOC)
  1286. #undef JSON_HEDLEY_MALLOC
  1287. #endif
  1288. #if \
  1289. JSON_HEDLEY_HAS_ATTRIBUTE(malloc) || \
  1290. JSON_HEDLEY_GCC_VERSION_CHECK(3,1,0) || \
  1291. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
  1292. JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,11,0) || \
  1293. JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \
  1294. JSON_HEDLEY_IBM_VERSION_CHECK(12,1,0) || \
  1295. JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \
  1296. (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  1297. JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \
  1298. (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  1299. JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \
  1300. (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  1301. JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \
  1302. (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  1303. JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \
  1304. JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \
  1305. JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0)
  1306. #define JSON_HEDLEY_MALLOC __attribute__((__malloc__))
  1307. #elif JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,10,0)
  1308. #define JSON_HEDLEY_MALLOC _Pragma("returns_new_memory")
  1309. #elif JSON_HEDLEY_MSVC_VERSION_CHECK(14, 0, 0)
  1310. #define JSON_HEDLEY_MALLOC __declspec(restrict)
  1311. #else
  1312. #define JSON_HEDLEY_MALLOC
  1313. #endif
  1314. #if defined(JSON_HEDLEY_PURE)
  1315. #undef JSON_HEDLEY_PURE
  1316. #endif
  1317. #if \
  1318. JSON_HEDLEY_HAS_ATTRIBUTE(pure) || \
  1319. JSON_HEDLEY_GCC_VERSION_CHECK(2,96,0) || \
  1320. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
  1321. JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,11,0) || \
  1322. JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \
  1323. JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \
  1324. JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \
  1325. (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  1326. JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \
  1327. (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  1328. JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \
  1329. (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  1330. JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \
  1331. (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  1332. JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \
  1333. JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \
  1334. JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \
  1335. JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0)
  1336. # define JSON_HEDLEY_PURE __attribute__((__pure__))
  1337. #elif JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,10,0)
  1338. # define JSON_HEDLEY_PURE _Pragma("does_not_write_global_data")
  1339. #elif defined(__cplusplus) && \
  1340. ( \
  1341. JSON_HEDLEY_TI_CL430_VERSION_CHECK(2,0,1) || \
  1342. JSON_HEDLEY_TI_CL6X_VERSION_CHECK(4,0,0) || \
  1343. JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) \
  1344. )
  1345. # define JSON_HEDLEY_PURE _Pragma("FUNC_IS_PURE;")
  1346. #else
  1347. # define JSON_HEDLEY_PURE
  1348. #endif
  1349. #if defined(JSON_HEDLEY_CONST)
  1350. #undef JSON_HEDLEY_CONST
  1351. #endif
  1352. #if \
  1353. JSON_HEDLEY_HAS_ATTRIBUTE(const) || \
  1354. JSON_HEDLEY_GCC_VERSION_CHECK(2,5,0) || \
  1355. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
  1356. JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,11,0) || \
  1357. JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \
  1358. JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \
  1359. JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \
  1360. (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  1361. JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \
  1362. (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  1363. JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \
  1364. (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  1365. JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \
  1366. (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  1367. JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \
  1368. JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \
  1369. JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \
  1370. JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0)
  1371. #define JSON_HEDLEY_CONST __attribute__((__const__))
  1372. #elif \
  1373. JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,10,0)
  1374. #define JSON_HEDLEY_CONST _Pragma("no_side_effect")
  1375. #else
  1376. #define JSON_HEDLEY_CONST JSON_HEDLEY_PURE
  1377. #endif
  1378. #if defined(JSON_HEDLEY_RESTRICT)
  1379. #undef JSON_HEDLEY_RESTRICT
  1380. #endif
  1381. #if defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) && !defined(__cplusplus)
  1382. #define JSON_HEDLEY_RESTRICT restrict
  1383. #elif \
  1384. JSON_HEDLEY_GCC_VERSION_CHECK(3,1,0) || \
  1385. JSON_HEDLEY_MSVC_VERSION_CHECK(14,0,0) || \
  1386. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
  1387. JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \
  1388. JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \
  1389. JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0) || \
  1390. JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \
  1391. JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,2,4) || \
  1392. JSON_HEDLEY_TI_CL6X_VERSION_CHECK(8,1,0) || \
  1393. JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \
  1394. (JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,14,0) && defined(__cplusplus)) || \
  1395. JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0) || \
  1396. defined(__clang__)
  1397. #define JSON_HEDLEY_RESTRICT __restrict
  1398. #elif JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,3,0) && !defined(__cplusplus)
  1399. #define JSON_HEDLEY_RESTRICT _Restrict
  1400. #else
  1401. #define JSON_HEDLEY_RESTRICT
  1402. #endif
  1403. #if defined(JSON_HEDLEY_INLINE)
  1404. #undef JSON_HEDLEY_INLINE
  1405. #endif
  1406. #if \
  1407. (defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L)) || \
  1408. (defined(__cplusplus) && (__cplusplus >= 199711L))
  1409. #define JSON_HEDLEY_INLINE inline
  1410. #elif \
  1411. defined(JSON_HEDLEY_GCC_VERSION) || \
  1412. JSON_HEDLEY_ARM_VERSION_CHECK(6,2,0)
  1413. #define JSON_HEDLEY_INLINE __inline__
  1414. #elif \
  1415. JSON_HEDLEY_MSVC_VERSION_CHECK(12,0,0) || \
  1416. JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \
  1417. JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,1,0) || \
  1418. JSON_HEDLEY_TI_CL430_VERSION_CHECK(3,1,0) || \
  1419. JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,2,0) || \
  1420. JSON_HEDLEY_TI_CL6X_VERSION_CHECK(8,0,0) || \
  1421. JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \
  1422. JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0)
  1423. #define JSON_HEDLEY_INLINE __inline
  1424. #else
  1425. #define JSON_HEDLEY_INLINE
  1426. #endif
  1427. #if defined(JSON_HEDLEY_ALWAYS_INLINE)
  1428. #undef JSON_HEDLEY_ALWAYS_INLINE
  1429. #endif
  1430. #if \
  1431. JSON_HEDLEY_HAS_ATTRIBUTE(always_inline) || \
  1432. JSON_HEDLEY_GCC_VERSION_CHECK(4,0,0) || \
  1433. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
  1434. JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,11,0) || \
  1435. JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \
  1436. JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \
  1437. JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \
  1438. (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  1439. JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \
  1440. (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  1441. JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \
  1442. (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  1443. JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \
  1444. (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  1445. JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \
  1446. JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \
  1447. JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0)
  1448. # define JSON_HEDLEY_ALWAYS_INLINE __attribute__((__always_inline__)) JSON_HEDLEY_INLINE
  1449. #elif JSON_HEDLEY_MSVC_VERSION_CHECK(12,0,0)
  1450. # define JSON_HEDLEY_ALWAYS_INLINE __forceinline
  1451. #elif defined(__cplusplus) && \
  1452. ( \
  1453. JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \
  1454. JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \
  1455. JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \
  1456. JSON_HEDLEY_TI_CL6X_VERSION_CHECK(6,1,0) || \
  1457. JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \
  1458. JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) \
  1459. )
  1460. # define JSON_HEDLEY_ALWAYS_INLINE _Pragma("FUNC_ALWAYS_INLINE;")
  1461. #elif JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0)
  1462. # define JSON_HEDLEY_ALWAYS_INLINE _Pragma("inline=forced")
  1463. #else
  1464. # define JSON_HEDLEY_ALWAYS_INLINE JSON_HEDLEY_INLINE
  1465. #endif
  1466. #if defined(JSON_HEDLEY_NEVER_INLINE)
  1467. #undef JSON_HEDLEY_NEVER_INLINE
  1468. #endif
  1469. #if \
  1470. JSON_HEDLEY_HAS_ATTRIBUTE(noinline) || \
  1471. JSON_HEDLEY_GCC_VERSION_CHECK(4,0,0) || \
  1472. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
  1473. JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,11,0) || \
  1474. JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \
  1475. JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \
  1476. JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \
  1477. (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  1478. JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \
  1479. (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  1480. JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \
  1481. (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  1482. JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \
  1483. (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  1484. JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \
  1485. JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \
  1486. JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0)
  1487. #define JSON_HEDLEY_NEVER_INLINE __attribute__((__noinline__))
  1488. #elif JSON_HEDLEY_MSVC_VERSION_CHECK(13,10,0)
  1489. #define JSON_HEDLEY_NEVER_INLINE __declspec(noinline)
  1490. #elif JSON_HEDLEY_PGI_VERSION_CHECK(10,2,0)
  1491. #define JSON_HEDLEY_NEVER_INLINE _Pragma("noinline")
  1492. #elif JSON_HEDLEY_TI_CL6X_VERSION_CHECK(6,0,0) && defined(__cplusplus)
  1493. #define JSON_HEDLEY_NEVER_INLINE _Pragma("FUNC_CANNOT_INLINE;")
  1494. #elif JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0)
  1495. #define JSON_HEDLEY_NEVER_INLINE _Pragma("inline=never")
  1496. #elif JSON_HEDLEY_COMPCERT_VERSION_CHECK(3,2,0)
  1497. #define JSON_HEDLEY_NEVER_INLINE __attribute((noinline))
  1498. #elif JSON_HEDLEY_PELLES_VERSION_CHECK(9,0,0)
  1499. #define JSON_HEDLEY_NEVER_INLINE __declspec(noinline)
  1500. #else
  1501. #define JSON_HEDLEY_NEVER_INLINE
  1502. #endif
  1503. #if defined(JSON_HEDLEY_PRIVATE)
  1504. #undef JSON_HEDLEY_PRIVATE
  1505. #endif
  1506. #if defined(JSON_HEDLEY_PUBLIC)
  1507. #undef JSON_HEDLEY_PUBLIC
  1508. #endif
  1509. #if defined(JSON_HEDLEY_IMPORT)
  1510. #undef JSON_HEDLEY_IMPORT
  1511. #endif
  1512. #if defined(_WIN32) || defined(__CYGWIN__)
  1513. # define JSON_HEDLEY_PRIVATE
  1514. # define JSON_HEDLEY_PUBLIC __declspec(dllexport)
  1515. # define JSON_HEDLEY_IMPORT __declspec(dllimport)
  1516. #else
  1517. # if \
  1518. JSON_HEDLEY_HAS_ATTRIBUTE(visibility) || \
  1519. JSON_HEDLEY_GCC_VERSION_CHECK(3,3,0) || \
  1520. JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,11,0) || \
  1521. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
  1522. JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \
  1523. JSON_HEDLEY_IBM_VERSION_CHECK(13,1,0) || \
  1524. ( \
  1525. defined(__TI_EABI__) && \
  1526. ( \
  1527. (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  1528. JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) \
  1529. ) \
  1530. )
  1531. # define JSON_HEDLEY_PRIVATE __attribute__((__visibility__("hidden")))
  1532. # define JSON_HEDLEY_PUBLIC __attribute__((__visibility__("default")))
  1533. # else
  1534. # define JSON_HEDLEY_PRIVATE
  1535. # define JSON_HEDLEY_PUBLIC
  1536. # endif
  1537. # define JSON_HEDLEY_IMPORT extern
  1538. #endif
  1539. #if defined(JSON_HEDLEY_NO_THROW)
  1540. #undef JSON_HEDLEY_NO_THROW
  1541. #endif
  1542. #if \
  1543. JSON_HEDLEY_HAS_ATTRIBUTE(nothrow) || \
  1544. JSON_HEDLEY_GCC_VERSION_CHECK(3,3,0) || \
  1545. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0)
  1546. #define JSON_HEDLEY_NO_THROW __attribute__((__nothrow__))
  1547. #elif \
  1548. JSON_HEDLEY_MSVC_VERSION_CHECK(13,1,0) || \
  1549. JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0)
  1550. #define JSON_HEDLEY_NO_THROW __declspec(nothrow)
  1551. #else
  1552. #define JSON_HEDLEY_NO_THROW
  1553. #endif
  1554. #if defined(JSON_HEDLEY_FALL_THROUGH)
  1555. #undef JSON_HEDLEY_FALL_THROUGH
  1556. #endif
  1557. #if \
  1558. JSON_HEDLEY_HAS_ATTRIBUTE(fallthrough) || \
  1559. JSON_HEDLEY_GCC_VERSION_CHECK(7,0,0)
  1560. #define JSON_HEDLEY_FALL_THROUGH __attribute__((__fallthrough__))
  1561. #elif JSON_HEDLEY_HAS_CPP_ATTRIBUTE_NS(clang,fallthrough)
  1562. #define JSON_HEDLEY_FALL_THROUGH JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[clang::fallthrough]])
  1563. #elif JSON_HEDLEY_HAS_CPP_ATTRIBUTE(fallthrough)
  1564. #define JSON_HEDLEY_FALL_THROUGH JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[fallthrough]])
  1565. #elif defined(__fallthrough) /* SAL */
  1566. #define JSON_HEDLEY_FALL_THROUGH __fallthrough
  1567. #else
  1568. #define JSON_HEDLEY_FALL_THROUGH
  1569. #endif
  1570. #if defined(JSON_HEDLEY_RETURNS_NON_NULL)
  1571. #undef JSON_HEDLEY_RETURNS_NON_NULL
  1572. #endif
  1573. #if \
  1574. JSON_HEDLEY_HAS_ATTRIBUTE(returns_nonnull) || \
  1575. JSON_HEDLEY_GCC_VERSION_CHECK(4,9,0)
  1576. #define JSON_HEDLEY_RETURNS_NON_NULL __attribute__((__returns_nonnull__))
  1577. #elif defined(_Ret_notnull_) /* SAL */
  1578. #define JSON_HEDLEY_RETURNS_NON_NULL _Ret_notnull_
  1579. #else
  1580. #define JSON_HEDLEY_RETURNS_NON_NULL
  1581. #endif
  1582. #if defined(JSON_HEDLEY_ARRAY_PARAM)
  1583. #undef JSON_HEDLEY_ARRAY_PARAM
  1584. #endif
  1585. #if \
  1586. defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) && \
  1587. !defined(__STDC_NO_VLA__) && \
  1588. !defined(__cplusplus) && \
  1589. !defined(JSON_HEDLEY_PGI_VERSION) && \
  1590. !defined(JSON_HEDLEY_TINYC_VERSION)
  1591. #define JSON_HEDLEY_ARRAY_PARAM(name) (name)
  1592. #else
  1593. #define JSON_HEDLEY_ARRAY_PARAM(name)
  1594. #endif
  1595. #if defined(JSON_HEDLEY_IS_CONSTANT)
  1596. #undef JSON_HEDLEY_IS_CONSTANT
  1597. #endif
  1598. #if defined(JSON_HEDLEY_REQUIRE_CONSTEXPR)
  1599. #undef JSON_HEDLEY_REQUIRE_CONSTEXPR
  1600. #endif
  1601. /* JSON_HEDLEY_IS_CONSTEXPR_ is for
  1602. HEDLEY INTERNAL USE ONLY. API subject to change without notice. */
  1603. #if defined(JSON_HEDLEY_IS_CONSTEXPR_)
  1604. #undef JSON_HEDLEY_IS_CONSTEXPR_
  1605. #endif
  1606. #if \
  1607. JSON_HEDLEY_HAS_BUILTIN(__builtin_constant_p) || \
  1608. JSON_HEDLEY_GCC_VERSION_CHECK(3,4,0) || \
  1609. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
  1610. JSON_HEDLEY_TINYC_VERSION_CHECK(0,9,19) || \
  1611. JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \
  1612. JSON_HEDLEY_IBM_VERSION_CHECK(13,1,0) || \
  1613. JSON_HEDLEY_TI_CL6X_VERSION_CHECK(6,1,0) || \
  1614. (JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,10,0) && !defined(__cplusplus)) || \
  1615. JSON_HEDLEY_CRAY_VERSION_CHECK(8,1,0)
  1616. #define JSON_HEDLEY_IS_CONSTANT(expr) __builtin_constant_p(expr)
  1617. #endif
  1618. #if !defined(__cplusplus)
  1619. # if \
  1620. JSON_HEDLEY_HAS_BUILTIN(__builtin_types_compatible_p) || \
  1621. JSON_HEDLEY_GCC_VERSION_CHECK(3,4,0) || \
  1622. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
  1623. JSON_HEDLEY_IBM_VERSION_CHECK(13,1,0) || \
  1624. JSON_HEDLEY_CRAY_VERSION_CHECK(8,1,0) || \
  1625. JSON_HEDLEY_ARM_VERSION_CHECK(5,4,0) || \
  1626. JSON_HEDLEY_TINYC_VERSION_CHECK(0,9,24)
  1627. #if defined(__INTPTR_TYPE__)
  1628. #define JSON_HEDLEY_IS_CONSTEXPR_(expr) __builtin_types_compatible_p(__typeof__((1 ? (void*) ((__INTPTR_TYPE__) ((expr) * 0)) : (int*) 0)), int*)
  1629. #else
  1630. #include <stdint.h>
  1631. #define JSON_HEDLEY_IS_CONSTEXPR_(expr) __builtin_types_compatible_p(__typeof__((1 ? (void*) ((intptr_t) ((expr) * 0)) : (int*) 0)), int*)
  1632. #endif
  1633. # elif \
  1634. ( \
  1635. defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 201112L) && \
  1636. !defined(JSON_HEDLEY_SUNPRO_VERSION) && \
  1637. !defined(JSON_HEDLEY_PGI_VERSION) && \
  1638. !defined(JSON_HEDLEY_IAR_VERSION)) || \
  1639. JSON_HEDLEY_HAS_EXTENSION(c_generic_selections) || \
  1640. JSON_HEDLEY_GCC_VERSION_CHECK(4,9,0) || \
  1641. JSON_HEDLEY_INTEL_VERSION_CHECK(17,0,0) || \
  1642. JSON_HEDLEY_IBM_VERSION_CHECK(12,1,0) || \
  1643. JSON_HEDLEY_ARM_VERSION_CHECK(5,3,0)
  1644. #if defined(__INTPTR_TYPE__)
  1645. #define JSON_HEDLEY_IS_CONSTEXPR_(expr) _Generic((1 ? (void*) ((__INTPTR_TYPE__) ((expr) * 0)) : (int*) 0), int*: 1, void*: 0)
  1646. #else
  1647. #include <stdint.h>
  1648. #define JSON_HEDLEY_IS_CONSTEXPR_(expr) _Generic((1 ? (void*) ((intptr_t) * 0) : (int*) 0), int*: 1, void*: 0)
  1649. #endif
  1650. # elif \
  1651. defined(JSON_HEDLEY_GCC_VERSION) || \
  1652. defined(JSON_HEDLEY_INTEL_VERSION) || \
  1653. defined(JSON_HEDLEY_TINYC_VERSION) || \
  1654. defined(JSON_HEDLEY_TI_ARMCL_VERSION) || \
  1655. JSON_HEDLEY_TI_CL430_VERSION_CHECK(18,12,0) || \
  1656. defined(JSON_HEDLEY_TI_CL2000_VERSION) || \
  1657. defined(JSON_HEDLEY_TI_CL6X_VERSION) || \
  1658. defined(JSON_HEDLEY_TI_CL7X_VERSION) || \
  1659. defined(JSON_HEDLEY_TI_CLPRU_VERSION) || \
  1660. defined(__clang__)
  1661. # define JSON_HEDLEY_IS_CONSTEXPR_(expr) ( \
  1662. sizeof(void) != \
  1663. sizeof(*( \
  1664. 1 ? \
  1665. ((void*) ((expr) * 0L) ) : \
  1666. ((struct { char v[sizeof(void) * 2]; } *) 1) \
  1667. ) \
  1668. ) \
  1669. )
  1670. # endif
  1671. #endif
  1672. #if defined(JSON_HEDLEY_IS_CONSTEXPR_)
  1673. #if !defined(JSON_HEDLEY_IS_CONSTANT)
  1674. #define JSON_HEDLEY_IS_CONSTANT(expr) JSON_HEDLEY_IS_CONSTEXPR_(expr)
  1675. #endif
  1676. #define JSON_HEDLEY_REQUIRE_CONSTEXPR(expr) (JSON_HEDLEY_IS_CONSTEXPR_(expr) ? (expr) : (-1))
  1677. #else
  1678. #if !defined(JSON_HEDLEY_IS_CONSTANT)
  1679. #define JSON_HEDLEY_IS_CONSTANT(expr) (0)
  1680. #endif
  1681. #define JSON_HEDLEY_REQUIRE_CONSTEXPR(expr) (expr)
  1682. #endif
  1683. #if defined(JSON_HEDLEY_BEGIN_C_DECLS)
  1684. #undef JSON_HEDLEY_BEGIN_C_DECLS
  1685. #endif
  1686. #if defined(JSON_HEDLEY_END_C_DECLS)
  1687. #undef JSON_HEDLEY_END_C_DECLS
  1688. #endif
  1689. #if defined(JSON_HEDLEY_C_DECL)
  1690. #undef JSON_HEDLEY_C_DECL
  1691. #endif
  1692. #if defined(__cplusplus)
  1693. #define JSON_HEDLEY_BEGIN_C_DECLS extern "C" {
  1694. #define JSON_HEDLEY_END_C_DECLS }
  1695. #define JSON_HEDLEY_C_DECL extern "C"
  1696. #else
  1697. #define JSON_HEDLEY_BEGIN_C_DECLS
  1698. #define JSON_HEDLEY_END_C_DECLS
  1699. #define JSON_HEDLEY_C_DECL
  1700. #endif
  1701. #if defined(JSON_HEDLEY_STATIC_ASSERT)
  1702. #undef JSON_HEDLEY_STATIC_ASSERT
  1703. #endif
  1704. #if \
  1705. !defined(__cplusplus) && ( \
  1706. (defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 201112L)) || \
  1707. JSON_HEDLEY_HAS_FEATURE(c_static_assert) || \
  1708. JSON_HEDLEY_GCC_VERSION_CHECK(6,0,0) || \
  1709. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
  1710. defined(_Static_assert) \
  1711. )
  1712. # define JSON_HEDLEY_STATIC_ASSERT(expr, message) _Static_assert(expr, message)
  1713. #elif \
  1714. (defined(__cplusplus) && (__cplusplus >= 201103L)) || \
  1715. JSON_HEDLEY_MSVC_VERSION_CHECK(16,0,0)
  1716. # define JSON_HEDLEY_STATIC_ASSERT(expr, message) JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_(static_assert(expr, message))
  1717. #else
  1718. # define JSON_HEDLEY_STATIC_ASSERT(expr, message)
  1719. #endif
  1720. #if defined(JSON_HEDLEY_NULL)
  1721. #undef JSON_HEDLEY_NULL
  1722. #endif
  1723. #if defined(__cplusplus)
  1724. #if __cplusplus >= 201103L
  1725. #define JSON_HEDLEY_NULL JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_(nullptr)
  1726. #elif defined(NULL)
  1727. #define JSON_HEDLEY_NULL NULL
  1728. #else
  1729. #define JSON_HEDLEY_NULL JSON_HEDLEY_STATIC_CAST(void*, 0)
  1730. #endif
  1731. #elif defined(NULL)
  1732. #define JSON_HEDLEY_NULL NULL
  1733. #else
  1734. #define JSON_HEDLEY_NULL ((void*) 0)
  1735. #endif
  1736. #if defined(JSON_HEDLEY_MESSAGE)
  1737. #undef JSON_HEDLEY_MESSAGE
  1738. #endif
  1739. #if JSON_HEDLEY_HAS_WARNING("-Wunknown-pragmas")
  1740. # define JSON_HEDLEY_MESSAGE(msg) \
  1741. JSON_HEDLEY_DIAGNOSTIC_PUSH \
  1742. JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS \
  1743. JSON_HEDLEY_PRAGMA(message msg) \
  1744. JSON_HEDLEY_DIAGNOSTIC_POP
  1745. #elif \
  1746. JSON_HEDLEY_GCC_VERSION_CHECK(4,4,0) || \
  1747. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0)
  1748. # define JSON_HEDLEY_MESSAGE(msg) JSON_HEDLEY_PRAGMA(message msg)
  1749. #elif JSON_HEDLEY_CRAY_VERSION_CHECK(5,0,0)
  1750. # define JSON_HEDLEY_MESSAGE(msg) JSON_HEDLEY_PRAGMA(_CRI message msg)
  1751. #elif JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0)
  1752. # define JSON_HEDLEY_MESSAGE(msg) JSON_HEDLEY_PRAGMA(message(msg))
  1753. #elif JSON_HEDLEY_PELLES_VERSION_CHECK(2,0,0)
  1754. # define JSON_HEDLEY_MESSAGE(msg) JSON_HEDLEY_PRAGMA(message(msg))
  1755. #else
  1756. # define JSON_HEDLEY_MESSAGE(msg)
  1757. #endif
  1758. #if defined(JSON_HEDLEY_WARNING)
  1759. #undef JSON_HEDLEY_WARNING
  1760. #endif
  1761. #if JSON_HEDLEY_HAS_WARNING("-Wunknown-pragmas")
  1762. # define JSON_HEDLEY_WARNING(msg) \
  1763. JSON_HEDLEY_DIAGNOSTIC_PUSH \
  1764. JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS \
  1765. JSON_HEDLEY_PRAGMA(clang warning msg) \
  1766. JSON_HEDLEY_DIAGNOSTIC_POP
  1767. #elif \
  1768. JSON_HEDLEY_GCC_VERSION_CHECK(4,8,0) || \
  1769. JSON_HEDLEY_PGI_VERSION_CHECK(18,4,0) || \
  1770. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0)
  1771. # define JSON_HEDLEY_WARNING(msg) JSON_HEDLEY_PRAGMA(GCC warning msg)
  1772. #elif JSON_HEDLEY_MSVC_VERSION_CHECK(15,0,0)
  1773. # define JSON_HEDLEY_WARNING(msg) JSON_HEDLEY_PRAGMA(message(msg))
  1774. #else
  1775. # define JSON_HEDLEY_WARNING(msg) JSON_HEDLEY_MESSAGE(msg)
  1776. #endif
  1777. #if defined(JSON_HEDLEY_REQUIRE)
  1778. #undef JSON_HEDLEY_REQUIRE
  1779. #endif
  1780. #if defined(JSON_HEDLEY_REQUIRE_MSG)
  1781. #undef JSON_HEDLEY_REQUIRE_MSG
  1782. #endif
  1783. #if JSON_HEDLEY_HAS_ATTRIBUTE(diagnose_if)
  1784. # if JSON_HEDLEY_HAS_WARNING("-Wgcc-compat")
  1785. # define JSON_HEDLEY_REQUIRE(expr) \
  1786. JSON_HEDLEY_DIAGNOSTIC_PUSH \
  1787. _Pragma("clang diagnostic ignored \"-Wgcc-compat\"") \
  1788. __attribute__((diagnose_if(!(expr), #expr, "error"))) \
  1789. JSON_HEDLEY_DIAGNOSTIC_POP
  1790. # define JSON_HEDLEY_REQUIRE_MSG(expr,msg) \
  1791. JSON_HEDLEY_DIAGNOSTIC_PUSH \
  1792. _Pragma("clang diagnostic ignored \"-Wgcc-compat\"") \
  1793. __attribute__((diagnose_if(!(expr), msg, "error"))) \
  1794. JSON_HEDLEY_DIAGNOSTIC_POP
  1795. # else
  1796. # define JSON_HEDLEY_REQUIRE(expr) __attribute__((diagnose_if(!(expr), #expr, "error")))
  1797. # define JSON_HEDLEY_REQUIRE_MSG(expr,msg) __attribute__((diagnose_if(!(expr), msg, "error")))
  1798. # endif
  1799. #else
  1800. # define JSON_HEDLEY_REQUIRE(expr)
  1801. # define JSON_HEDLEY_REQUIRE_MSG(expr,msg)
  1802. #endif
  1803. #if defined(JSON_HEDLEY_FLAGS)
  1804. #undef JSON_HEDLEY_FLAGS
  1805. #endif
  1806. #if JSON_HEDLEY_HAS_ATTRIBUTE(flag_enum)
  1807. #define JSON_HEDLEY_FLAGS __attribute__((__flag_enum__))
  1808. #endif
  1809. #if defined(JSON_HEDLEY_FLAGS_CAST)
  1810. #undef JSON_HEDLEY_FLAGS_CAST
  1811. #endif
  1812. #if JSON_HEDLEY_INTEL_VERSION_CHECK(19,0,0)
  1813. # define JSON_HEDLEY_FLAGS_CAST(T, expr) (__extension__ ({ \
  1814. JSON_HEDLEY_DIAGNOSTIC_PUSH \
  1815. _Pragma("warning(disable:188)") \
  1816. ((T) (expr)); \
  1817. JSON_HEDLEY_DIAGNOSTIC_POP \
  1818. }))
  1819. #else
  1820. # define JSON_HEDLEY_FLAGS_CAST(T, expr) JSON_HEDLEY_STATIC_CAST(T, expr)
  1821. #endif
  1822. #if defined(JSON_HEDLEY_EMPTY_BASES)
  1823. #undef JSON_HEDLEY_EMPTY_BASES
  1824. #endif
  1825. #if JSON_HEDLEY_MSVC_VERSION_CHECK(19,0,23918) && !JSON_HEDLEY_MSVC_VERSION_CHECK(20,0,0)
  1826. #define JSON_HEDLEY_EMPTY_BASES __declspec(empty_bases)
  1827. #else
  1828. #define JSON_HEDLEY_EMPTY_BASES
  1829. #endif
  1830. /* Remaining macros are deprecated. */
  1831. #if defined(JSON_HEDLEY_GCC_NOT_CLANG_VERSION_CHECK)
  1832. #undef JSON_HEDLEY_GCC_NOT_CLANG_VERSION_CHECK
  1833. #endif
  1834. #if defined(__clang__)
  1835. #define JSON_HEDLEY_GCC_NOT_CLANG_VERSION_CHECK(major,minor,patch) (0)
  1836. #else
  1837. #define JSON_HEDLEY_GCC_NOT_CLANG_VERSION_CHECK(major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch)
  1838. #endif
  1839. #if defined(JSON_HEDLEY_CLANG_HAS_ATTRIBUTE)
  1840. #undef JSON_HEDLEY_CLANG_HAS_ATTRIBUTE
  1841. #endif
  1842. #define JSON_HEDLEY_CLANG_HAS_ATTRIBUTE(attribute) JSON_HEDLEY_HAS_ATTRIBUTE(attribute)
  1843. #if defined(JSON_HEDLEY_CLANG_HAS_CPP_ATTRIBUTE)
  1844. #undef JSON_HEDLEY_CLANG_HAS_CPP_ATTRIBUTE
  1845. #endif
  1846. #define JSON_HEDLEY_CLANG_HAS_CPP_ATTRIBUTE(attribute) JSON_HEDLEY_HAS_CPP_ATTRIBUTE(attribute)
  1847. #if defined(JSON_HEDLEY_CLANG_HAS_BUILTIN)
  1848. #undef JSON_HEDLEY_CLANG_HAS_BUILTIN
  1849. #endif
  1850. #define JSON_HEDLEY_CLANG_HAS_BUILTIN(builtin) JSON_HEDLEY_HAS_BUILTIN(builtin)
  1851. #if defined(JSON_HEDLEY_CLANG_HAS_FEATURE)
  1852. #undef JSON_HEDLEY_CLANG_HAS_FEATURE
  1853. #endif
  1854. #define JSON_HEDLEY_CLANG_HAS_FEATURE(feature) JSON_HEDLEY_HAS_FEATURE(feature)
  1855. #if defined(JSON_HEDLEY_CLANG_HAS_EXTENSION)
  1856. #undef JSON_HEDLEY_CLANG_HAS_EXTENSION
  1857. #endif
  1858. #define JSON_HEDLEY_CLANG_HAS_EXTENSION(extension) JSON_HEDLEY_HAS_EXTENSION(extension)
  1859. #if defined(JSON_HEDLEY_CLANG_HAS_DECLSPEC_DECLSPEC_ATTRIBUTE)
  1860. #undef JSON_HEDLEY_CLANG_HAS_DECLSPEC_DECLSPEC_ATTRIBUTE
  1861. #endif
  1862. #define JSON_HEDLEY_CLANG_HAS_DECLSPEC_ATTRIBUTE(attribute) JSON_HEDLEY_HAS_DECLSPEC_ATTRIBUTE(attribute)
  1863. #if defined(JSON_HEDLEY_CLANG_HAS_WARNING)
  1864. #undef JSON_HEDLEY_CLANG_HAS_WARNING
  1865. #endif
  1866. #define JSON_HEDLEY_CLANG_HAS_WARNING(warning) JSON_HEDLEY_HAS_WARNING(warning)
  1867. #endif /* !defined(JSON_HEDLEY_VERSION) || (JSON_HEDLEY_VERSION < X) */
  1868. // This file contains all internal macro definitions
  1869. // You MUST include macro_unscope.hpp at the end of json.hpp to undef all of them
  1870. // exclude unsupported compilers
  1871. #if !defined(JSON_SKIP_UNSUPPORTED_COMPILER_CHECK)
  1872. #if defined(__clang__)
  1873. #if (__clang_major__ * 10000 + __clang_minor__ * 100 + __clang_patchlevel__) < 30400
  1874. #error "unsupported Clang version - see https://github.com/nlohmann/json#supported-compilers"
  1875. #endif
  1876. #elif defined(__GNUC__) && !(defined(__ICC) || defined(__INTEL_COMPILER))
  1877. #if (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__) < 40800
  1878. #error "unsupported GCC version - see https://github.com/nlohmann/json#supported-compilers"
  1879. #endif
  1880. #endif
  1881. #endif
  1882. // C++ language standard detection
  1883. #if (defined(__cplusplus) && __cplusplus >= 201703L) || (defined(_HAS_CXX17) && _HAS_CXX17 == 1) // fix for issue #464
  1884. #define JSON_HAS_CPP_17
  1885. #define JSON_HAS_CPP_14
  1886. #elif (defined(__cplusplus) && __cplusplus >= 201402L) || (defined(_HAS_CXX14) && _HAS_CXX14 == 1)
  1887. #define JSON_HAS_CPP_14
  1888. #endif
  1889. // disable float-equal warnings on GCC/clang
  1890. #if defined(__clang__) || defined(__GNUC__) || defined(__GNUG__)
  1891. #pragma GCC diagnostic push
  1892. #pragma GCC diagnostic ignored "-Wfloat-equal"
  1893. #endif
  1894. // disable documentation warnings on clang
  1895. #if defined(__clang__)
  1896. #pragma GCC diagnostic push
  1897. #pragma GCC diagnostic ignored "-Wdocumentation"
  1898. #endif
  1899. // allow to disable exceptions
  1900. #if (defined(__cpp_exceptions) || defined(__EXCEPTIONS) || defined(_CPPUNWIND)) && !defined(JSON_NOEXCEPTION)
  1901. #define JSON_THROW(exception) throw exception
  1902. #define JSON_TRY try
  1903. #define JSON_CATCH(exception) catch(exception)
  1904. #define JSON_INTERNAL_CATCH(exception) catch(exception)
  1905. #else
  1906. #include <cstdlib>
  1907. #define JSON_THROW(exception) std::abort()
  1908. #define JSON_TRY if(true)
  1909. #define JSON_CATCH(exception) if(false)
  1910. #define JSON_INTERNAL_CATCH(exception) if(false)
  1911. #endif
  1912. // override exception macros
  1913. #if defined(JSON_THROW_USER)
  1914. #undef JSON_THROW
  1915. #define JSON_THROW JSON_THROW_USER
  1916. #endif
  1917. #if defined(JSON_TRY_USER)
  1918. #undef JSON_TRY
  1919. #define JSON_TRY JSON_TRY_USER
  1920. #endif
  1921. #if defined(JSON_CATCH_USER)
  1922. #undef JSON_CATCH
  1923. #define JSON_CATCH JSON_CATCH_USER
  1924. #undef JSON_INTERNAL_CATCH
  1925. #define JSON_INTERNAL_CATCH JSON_CATCH_USER
  1926. #endif
  1927. #if defined(JSON_INTERNAL_CATCH_USER)
  1928. #undef JSON_INTERNAL_CATCH
  1929. #define JSON_INTERNAL_CATCH JSON_INTERNAL_CATCH_USER
  1930. #endif
  1931. /*!
  1932. @brief macro to briefly define a mapping between an enum and JSON
  1933. @def NLOHMANN_JSON_SERIALIZE_ENUM
  1934. @since version 3.4.0
  1935. */
  1936. #define NLOHMANN_JSON_SERIALIZE_ENUM(ENUM_TYPE, ...) \
  1937. template<typename BasicJsonType> \
  1938. inline void to_json(BasicJsonType& j, const ENUM_TYPE& e) \
  1939. { \
  1940. static_assert(std::is_enum<ENUM_TYPE>::value, #ENUM_TYPE " must be an enum!"); \
  1941. static const std::pair<ENUM_TYPE, BasicJsonType> m[] = __VA_ARGS__; \
  1942. auto it = std::find_if(std::begin(m), std::end(m), \
  1943. [e](const std::pair<ENUM_TYPE, BasicJsonType>& ej_pair) -> bool \
  1944. { \
  1945. return ej_pair.first == e; \
  1946. }); \
  1947. j = ((it != std::end(m)) ? it : std::begin(m))->second; \
  1948. } \
  1949. template<typename BasicJsonType> \
  1950. inline void from_json(const BasicJsonType& j, ENUM_TYPE& e) \
  1951. { \
  1952. static_assert(std::is_enum<ENUM_TYPE>::value, #ENUM_TYPE " must be an enum!"); \
  1953. static const std::pair<ENUM_TYPE, BasicJsonType> m[] = __VA_ARGS__; \
  1954. auto it = std::find_if(std::begin(m), std::end(m), \
  1955. [&j](const std::pair<ENUM_TYPE, BasicJsonType>& ej_pair) -> bool \
  1956. { \
  1957. return ej_pair.second == j; \
  1958. }); \
  1959. e = ((it != std::end(m)) ? it : std::begin(m))->first; \
  1960. }
  1961. // Ugly macros to avoid uglier copy-paste when specializing basic_json. They
  1962. // may be removed in the future once the class is split.
  1963. #define NLOHMANN_BASIC_JSON_TPL_DECLARATION \
  1964. template<template<typename, typename, typename...> class ObjectType, \
  1965. template<typename, typename...> class ArrayType, \
  1966. class StringType, class BooleanType, class NumberIntegerType, \
  1967. class NumberUnsignedType, class NumberFloatType, \
  1968. template<typename> class AllocatorType, \
  1969. template<typename, typename = void> class JSONSerializer, \
  1970. class BinaryType>
  1971. #define NLOHMANN_BASIC_JSON_TPL \
  1972. basic_json<ObjectType, ArrayType, StringType, BooleanType, \
  1973. NumberIntegerType, NumberUnsignedType, NumberFloatType, \
  1974. AllocatorType, JSONSerializer, BinaryType>
  1975. namespace nlohmann
  1976. {
  1977. namespace detail
  1978. {
  1979. ////////////////
  1980. // exceptions //
  1981. ////////////////
  1982. /*!
  1983. @brief general exception of the @ref basic_json class
  1984. This class is an extension of `std::exception` objects with a member @a id for
  1985. exception ids. It is used as the base class for all exceptions thrown by the
  1986. @ref basic_json class. This class can hence be used as "wildcard" to catch
  1987. exceptions.
  1988. Subclasses:
  1989. - @ref parse_error for exceptions indicating a parse error
  1990. - @ref invalid_iterator for exceptions indicating errors with iterators
  1991. - @ref type_error for exceptions indicating executing a member function with
  1992. a wrong type
  1993. - @ref out_of_range for exceptions indicating access out of the defined range
  1994. - @ref other_error for exceptions indicating other library errors
  1995. @internal
  1996. @note To have nothrow-copy-constructible exceptions, we internally use
  1997. `std::runtime_error` which can cope with arbitrary-length error messages.
  1998. Intermediate strings are built with static functions and then passed to
  1999. the actual constructor.
  2000. @endinternal
  2001. @liveexample{The following code shows how arbitrary library exceptions can be
  2002. caught.,exception}
  2003. @since version 3.0.0
  2004. */
  2005. class exception : public std::exception
  2006. {
  2007. public:
  2008. /// returns the explanatory string
  2009. JSON_HEDLEY_RETURNS_NON_NULL
  2010. const char* what() const noexcept override
  2011. {
  2012. return m.what();
  2013. }
  2014. /// the id of the exception
  2015. const int id;
  2016. protected:
  2017. JSON_HEDLEY_NON_NULL(3)
  2018. exception(int id_, const char* what_arg) : id(id_), m(what_arg) {}
  2019. static std::string name(const std::string& ename, int id_)
  2020. {
  2021. return "[json.exception." + ename + "." + std::to_string(id_) + "] ";
  2022. }
  2023. private:
  2024. /// an exception object as storage for error messages
  2025. std::runtime_error m;
  2026. };
  2027. /*!
  2028. @brief exception indicating a parse error
  2029. This exception is thrown by the library when a parse error occurs. Parse errors
  2030. can occur during the deserialization of JSON text, CBOR, MessagePack, as well
  2031. as when using JSON Patch.
  2032. Member @a byte holds the byte index of the last read character in the input
  2033. file.
  2034. Exceptions have ids 1xx.
  2035. name / id | example message | description
  2036. ------------------------------ | --------------- | -------------------------
  2037. 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.
  2038. 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.
  2039. 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.
  2040. 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.
  2041. 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.
  2042. 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`.
  2043. 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.
  2044. 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.
  2045. json.exception.parse_error.109 | parse error: array index 'one' is not a number | A JSON Pointer array index must be a number.
  2046. 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.
  2047. 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.
  2048. 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.
  2049. json.exception.parse_error.114 | parse error: Unsupported BSON record type 0x0F | The parsing of the corresponding BSON record type is not implemented (yet).
  2050. @note For an input with n bytes, 1 is the index of the first character and n+1
  2051. is the index of the terminating null byte or the end of file. This also
  2052. holds true when reading a byte vector (CBOR or MessagePack).
  2053. @liveexample{The following code shows how a `parse_error` exception can be
  2054. caught.,parse_error}
  2055. @sa - @ref exception for the base class of the library exceptions
  2056. @sa - @ref invalid_iterator for exceptions indicating errors with iterators
  2057. @sa - @ref type_error for exceptions indicating executing a member function with
  2058. a wrong type
  2059. @sa - @ref out_of_range for exceptions indicating access out of the defined range
  2060. @sa - @ref other_error for exceptions indicating other library errors
  2061. @since version 3.0.0
  2062. */
  2063. class parse_error : public exception
  2064. {
  2065. public:
  2066. /*!
  2067. @brief create a parse error exception
  2068. @param[in] id_ the id of the exception
  2069. @param[in] pos the position where the error occurred (or with
  2070. chars_read_total=0 if the position cannot be
  2071. determined)
  2072. @param[in] what_arg the explanatory string
  2073. @return parse_error object
  2074. */
  2075. static parse_error create(int id_, const position_t& pos, const std::string& what_arg)
  2076. {
  2077. std::string w = exception::name("parse_error", id_) + "parse error" +
  2078. position_string(pos) + ": " + what_arg;
  2079. return parse_error(id_, pos.chars_read_total, w.c_str());
  2080. }
  2081. static parse_error create(int id_, std::size_t byte_, const std::string& what_arg)
  2082. {
  2083. std::string w = exception::name("parse_error", id_) + "parse error" +
  2084. (byte_ != 0 ? (" at byte " + std::to_string(byte_)) : "") +
  2085. ": " + what_arg;
  2086. return parse_error(id_, byte_, w.c_str());
  2087. }
  2088. /*!
  2089. @brief byte index of the parse error
  2090. The byte index of the last read character in the input file.
  2091. @note For an input with n bytes, 1 is the index of the first character and
  2092. n+1 is the index of the terminating null byte or the end of file.
  2093. This also holds true when reading a byte vector (CBOR or MessagePack).
  2094. */
  2095. const std::size_t byte;
  2096. private:
  2097. parse_error(int id_, std::size_t byte_, const char* what_arg)
  2098. : exception(id_, what_arg), byte(byte_) {}
  2099. static std::string position_string(const position_t& pos)
  2100. {
  2101. return " at line " + std::to_string(pos.lines_read + 1) +
  2102. ", column " + std::to_string(pos.chars_read_current_line);
  2103. }
  2104. };
  2105. /*!
  2106. @brief exception indicating errors with iterators
  2107. This exception is thrown if iterators passed to a library function do not match
  2108. the expected semantics.
  2109. Exceptions have ids 2xx.
  2110. name / id | example message | description
  2111. ----------------------------------- | --------------- | -------------------------
  2112. 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.
  2113. 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.
  2114. 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.
  2115. 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.
  2116. 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.
  2117. 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.
  2118. 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.
  2119. 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.
  2120. 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.
  2121. 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.
  2122. 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.
  2123. json.exception.invalid_iterator.212 | cannot compare iterators of different containers | When two iterators are compared, they must belong to the same container.
  2124. json.exception.invalid_iterator.213 | cannot compare order of object iterators | The order of object iterators cannot be compared, because JSON objects are unordered.
  2125. 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().
  2126. @liveexample{The following code shows how an `invalid_iterator` exception can be
  2127. caught.,invalid_iterator}
  2128. @sa - @ref exception for the base class of the library exceptions
  2129. @sa - @ref parse_error for exceptions indicating a parse error
  2130. @sa - @ref type_error for exceptions indicating executing a member function with
  2131. a wrong type
  2132. @sa - @ref out_of_range for exceptions indicating access out of the defined range
  2133. @sa - @ref other_error for exceptions indicating other library errors
  2134. @since version 3.0.0
  2135. */
  2136. class invalid_iterator : public exception
  2137. {
  2138. public:
  2139. static invalid_iterator create(int id_, const std::string& what_arg)
  2140. {
  2141. std::string w = exception::name("invalid_iterator", id_) + what_arg;
  2142. return invalid_iterator(id_, w.c_str());
  2143. }
  2144. private:
  2145. JSON_HEDLEY_NON_NULL(3)
  2146. invalid_iterator(int id_, const char* what_arg)
  2147. : exception(id_, what_arg) {}
  2148. };
  2149. /*!
  2150. @brief exception indicating executing a member function with a wrong type
  2151. This exception is thrown in case of a type error; that is, a library function is
  2152. executed on a JSON value whose type does not match the expected semantics.
  2153. Exceptions have ids 3xx.
  2154. name / id | example message | description
  2155. ----------------------------- | --------------- | -------------------------
  2156. 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.
  2157. 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.
  2158. 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 &.
  2159. json.exception.type_error.304 | cannot use at() with string | The @ref at() member functions can only be executed for certain JSON types.
  2160. json.exception.type_error.305 | cannot use operator[] with string | The @ref operator[] member functions can only be executed for certain JSON types.
  2161. json.exception.type_error.306 | cannot use value() with string | The @ref value() member functions can only be executed for certain JSON types.
  2162. json.exception.type_error.307 | cannot use erase() with string | The @ref erase() member functions can only be executed for certain JSON types.
  2163. 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.
  2164. json.exception.type_error.309 | cannot use insert() with | The @ref insert() member functions can only be executed for certain JSON types.
  2165. json.exception.type_error.310 | cannot use swap() with number | The @ref swap() member functions can only be executed for certain JSON types.
  2166. 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.
  2167. json.exception.type_error.312 | cannot use update() with string | The @ref update() member functions can only be executed for certain JSON types.
  2168. 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.
  2169. json.exception.type_error.314 | only objects can be unflattened | The @ref unflatten function only works for an object whose keys are JSON Pointers.
  2170. 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.
  2171. 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. |
  2172. 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) |
  2173. @liveexample{The following code shows how a `type_error` exception can be
  2174. caught.,type_error}
  2175. @sa - @ref exception for the base class of the library exceptions
  2176. @sa - @ref parse_error for exceptions indicating a parse error
  2177. @sa - @ref invalid_iterator for exceptions indicating errors with iterators
  2178. @sa - @ref out_of_range for exceptions indicating access out of the defined range
  2179. @sa - @ref other_error for exceptions indicating other library errors
  2180. @since version 3.0.0
  2181. */
  2182. class type_error : public exception
  2183. {
  2184. public:
  2185. static type_error create(int id_, const std::string& what_arg)
  2186. {
  2187. std::string w = exception::name("type_error", id_) + what_arg;
  2188. return type_error(id_, w.c_str());
  2189. }
  2190. private:
  2191. JSON_HEDLEY_NON_NULL(3)
  2192. type_error(int id_, const char* what_arg) : exception(id_, what_arg) {}
  2193. };
  2194. /*!
  2195. @brief exception indicating access out of the defined range
  2196. This exception is thrown in case a library function is called on an input
  2197. parameter that exceeds the expected range, for instance in case of array
  2198. indices or nonexisting object keys.
  2199. Exceptions have ids 4xx.
  2200. name / id | example message | description
  2201. ------------------------------- | --------------- | -------------------------
  2202. 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.
  2203. 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.
  2204. json.exception.out_of_range.403 | key 'foo' not found | The provided key was not found in the JSON object.
  2205. json.exception.out_of_range.404 | unresolved reference token 'foo' | A reference token in a JSON Pointer could not be resolved.
  2206. 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.
  2207. 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.
  2208. json.exception.out_of_range.407 | number overflow serializing '9223372036854775808' | UBJSON and BSON only support integer numbers up to 9223372036854775807. |
  2209. json.exception.out_of_range.408 | excessive array size: 8658170730974374167 | The size (following `#`) of an UBJSON array or object exceeds the maximal capacity. |
  2210. 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 |
  2211. @liveexample{The following code shows how an `out_of_range` exception can be
  2212. caught.,out_of_range}
  2213. @sa - @ref exception for the base class of the library exceptions
  2214. @sa - @ref parse_error for exceptions indicating a parse error
  2215. @sa - @ref invalid_iterator for exceptions indicating errors with iterators
  2216. @sa - @ref type_error for exceptions indicating executing a member function with
  2217. a wrong type
  2218. @sa - @ref other_error for exceptions indicating other library errors
  2219. @since version 3.0.0
  2220. */
  2221. class out_of_range : public exception
  2222. {
  2223. public:
  2224. static out_of_range create(int id_, const std::string& what_arg)
  2225. {
  2226. std::string w = exception::name("out_of_range", id_) + what_arg;
  2227. return out_of_range(id_, w.c_str());
  2228. }
  2229. private:
  2230. JSON_HEDLEY_NON_NULL(3)
  2231. out_of_range(int id_, const char* what_arg) : exception(id_, what_arg) {}
  2232. };
  2233. /*!
  2234. @brief exception indicating other library errors
  2235. This exception is thrown in case of errors that cannot be classified with the
  2236. other exception types.
  2237. Exceptions have ids 5xx.
  2238. name / id | example message | description
  2239. ------------------------------ | --------------- | -------------------------
  2240. json.exception.other_error.501 | unsuccessful: {"op":"test","path":"/baz", "value":"bar"} | A JSON Patch operation 'test' failed. The unsuccessful operation is also printed.
  2241. @sa - @ref exception for the base class of the library exceptions
  2242. @sa - @ref parse_error for exceptions indicating a parse error
  2243. @sa - @ref invalid_iterator for exceptions indicating errors with iterators
  2244. @sa - @ref type_error for exceptions indicating executing a member function with
  2245. a wrong type
  2246. @sa - @ref out_of_range for exceptions indicating access out of the defined range
  2247. @liveexample{The following code shows how an `other_error` exception can be
  2248. caught.,other_error}
  2249. @since version 3.0.0
  2250. */
  2251. class other_error : public exception
  2252. {
  2253. public:
  2254. static other_error create(int id_, const std::string& what_arg)
  2255. {
  2256. std::string w = exception::name("other_error", id_) + what_arg;
  2257. return other_error(id_, w.c_str());
  2258. }
  2259. private:
  2260. JSON_HEDLEY_NON_NULL(3)
  2261. other_error(int id_, const char* what_arg) : exception(id_, what_arg) {}
  2262. };
  2263. } // namespace detail
  2264. } // namespace nlohmann
  2265. // #include <nlohmann/detail/macro_scope.hpp>
  2266. // #include <nlohmann/detail/meta/cpp_future.hpp>
  2267. #include <ciso646> // not
  2268. #include <cstddef> // size_t
  2269. #include <type_traits> // conditional, enable_if, false_type, integral_constant, is_constructible, is_integral, is_same, remove_cv, remove_reference, true_type
  2270. namespace nlohmann
  2271. {
  2272. namespace detail
  2273. {
  2274. // alias templates to reduce boilerplate
  2275. template<bool B, typename T = void>
  2276. using enable_if_t = typename std::enable_if<B, T>::type;
  2277. template<typename T>
  2278. using uncvref_t = typename std::remove_cv<typename std::remove_reference<T>::type>::type;
  2279. // implementation of C++14 index_sequence and affiliates
  2280. // source: https://stackoverflow.com/a/32223343
  2281. template<std::size_t... Ints>
  2282. struct index_sequence
  2283. {
  2284. using type = index_sequence;
  2285. using value_type = std::size_t;
  2286. static constexpr std::size_t size() noexcept
  2287. {
  2288. return sizeof...(Ints);
  2289. }
  2290. };
  2291. template<class Sequence1, class Sequence2>
  2292. struct merge_and_renumber;
  2293. template<std::size_t... I1, std::size_t... I2>
  2294. struct merge_and_renumber<index_sequence<I1...>, index_sequence<I2...>>
  2295. : index_sequence < I1..., (sizeof...(I1) + I2)... > {};
  2296. template<std::size_t N>
  2297. struct make_index_sequence
  2298. : merge_and_renumber < typename make_index_sequence < N / 2 >::type,
  2299. typename make_index_sequence < N - N / 2 >::type > {};
  2300. template<> struct make_index_sequence<0> : index_sequence<> {};
  2301. template<> struct make_index_sequence<1> : index_sequence<0> {};
  2302. template<typename... Ts>
  2303. using index_sequence_for = make_index_sequence<sizeof...(Ts)>;
  2304. // dispatch utility (taken from ranges-v3)
  2305. template<unsigned N> struct priority_tag : priority_tag < N - 1 > {};
  2306. template<> struct priority_tag<0> {};
  2307. // taken from ranges-v3
  2308. template<typename T>
  2309. struct static_const
  2310. {
  2311. static constexpr T value{};
  2312. };
  2313. template<typename T>
  2314. constexpr T static_const<T>::value;
  2315. } // namespace detail
  2316. } // namespace nlohmann
  2317. // #include <nlohmann/detail/meta/type_traits.hpp>
  2318. #include <ciso646> // not
  2319. #include <limits> // numeric_limits
  2320. #include <type_traits> // false_type, is_constructible, is_integral, is_same, true_type
  2321. #include <utility> // declval
  2322. // #include <nlohmann/detail/iterators/iterator_traits.hpp>
  2323. #include <iterator> // random_access_iterator_tag
  2324. // #include <nlohmann/detail/meta/void_t.hpp>
  2325. namespace nlohmann
  2326. {
  2327. namespace detail
  2328. {
  2329. template <typename ...Ts> struct make_void
  2330. {
  2331. using type = void;
  2332. };
  2333. template <typename ...Ts> using void_t = typename make_void<Ts...>::type;
  2334. } // namespace detail
  2335. } // namespace nlohmann
  2336. // #include <nlohmann/detail/meta/cpp_future.hpp>
  2337. namespace nlohmann
  2338. {
  2339. namespace detail
  2340. {
  2341. template <typename It, typename = void>
  2342. struct iterator_types {};
  2343. template <typename It>
  2344. struct iterator_types <
  2345. It,
  2346. void_t<typename It::difference_type, typename It::value_type, typename It::pointer,
  2347. typename It::reference, typename It::iterator_category >>
  2348. {
  2349. using difference_type = typename It::difference_type;
  2350. using value_type = typename It::value_type;
  2351. using pointer = typename It::pointer;
  2352. using reference = typename It::reference;
  2353. using iterator_category = typename It::iterator_category;
  2354. };
  2355. // This is required as some compilers implement std::iterator_traits in a way that
  2356. // doesn't work with SFINAE. See https://github.com/nlohmann/json/issues/1341.
  2357. template <typename T, typename = void>
  2358. struct iterator_traits
  2359. {
  2360. };
  2361. template <typename T>
  2362. struct iterator_traits < T, enable_if_t < !std::is_pointer<T>::value >>
  2363. : iterator_types<T>
  2364. {
  2365. };
  2366. template <typename T>
  2367. struct iterator_traits<T*, enable_if_t<std::is_object<T>::value>>
  2368. {
  2369. using iterator_category = std::random_access_iterator_tag;
  2370. using value_type = T;
  2371. using difference_type = ptrdiff_t;
  2372. using pointer = T*;
  2373. using reference = T&;
  2374. };
  2375. } // namespace detail
  2376. } // namespace nlohmann
  2377. // #include <nlohmann/detail/macro_scope.hpp>
  2378. // #include <nlohmann/detail/meta/cpp_future.hpp>
  2379. // #include <nlohmann/detail/meta/detected.hpp>
  2380. #include <type_traits>
  2381. // #include <nlohmann/detail/meta/void_t.hpp>
  2382. // https://en.cppreference.com/w/cpp/experimental/is_detected
  2383. namespace nlohmann
  2384. {
  2385. namespace detail
  2386. {
  2387. struct nonesuch
  2388. {
  2389. nonesuch() = delete;
  2390. ~nonesuch() = delete;
  2391. nonesuch(nonesuch const&) = delete;
  2392. nonesuch(nonesuch const&&) = delete;
  2393. void operator=(nonesuch const&) = delete;
  2394. void operator=(nonesuch&&) = delete;
  2395. };
  2396. template <class Default,
  2397. class AlwaysVoid,
  2398. template <class...> class Op,
  2399. class... Args>
  2400. struct detector
  2401. {
  2402. using value_t = std::false_type;
  2403. using type = Default;
  2404. };
  2405. template <class Default, template <class...> class Op, class... Args>
  2406. struct detector<Default, void_t<Op<Args...>>, Op, Args...>
  2407. {
  2408. using value_t = std::true_type;
  2409. using type = Op<Args...>;
  2410. };
  2411. template <template <class...> class Op, class... Args>
  2412. using is_detected = typename detector<nonesuch, void, Op, Args...>::value_t;
  2413. template <template <class...> class Op, class... Args>
  2414. using detected_t = typename detector<nonesuch, void, Op, Args...>::type;
  2415. template <class Default, template <class...> class Op, class... Args>
  2416. using detected_or = detector<Default, void, Op, Args...>;
  2417. template <class Default, template <class...> class Op, class... Args>
  2418. using detected_or_t = typename detected_or<Default, Op, Args...>::type;
  2419. template <class Expected, template <class...> class Op, class... Args>
  2420. using is_detected_exact = std::is_same<Expected, detected_t<Op, Args...>>;
  2421. template <class To, template <class...> class Op, class... Args>
  2422. using is_detected_convertible =
  2423. std::is_convertible<detected_t<Op, Args...>, To>;
  2424. } // namespace detail
  2425. } // namespace nlohmann
  2426. // #include <nlohmann/json_fwd.hpp>
  2427. #ifndef INCLUDE_NLOHMANN_JSON_FWD_HPP_
  2428. #define INCLUDE_NLOHMANN_JSON_FWD_HPP_
  2429. #include <cstdint> // int64_t, uint64_t
  2430. #include <map> // map
  2431. #include <memory> // allocator
  2432. #include <string> // string
  2433. #include <vector> // vector
  2434. /*!
  2435. @brief namespace for Niels Lohmann
  2436. @see https://github.com/nlohmann
  2437. @since version 1.0.0
  2438. */
  2439. namespace nlohmann
  2440. {
  2441. /*!
  2442. @brief default JSONSerializer template argument
  2443. This serializer ignores the template arguments and uses ADL
  2444. ([argument-dependent lookup](https://en.cppreference.com/w/cpp/language/adl))
  2445. for serialization.
  2446. */
  2447. template<typename T = void, typename SFINAE = void>
  2448. struct adl_serializer;
  2449. template<template<typename U, typename V, typename... Args> class ObjectType =
  2450. std::map,
  2451. template<typename U, typename... Args> class ArrayType = std::vector,
  2452. class StringType = std::string, class BooleanType = bool,
  2453. class NumberIntegerType = std::int64_t,
  2454. class NumberUnsignedType = std::uint64_t,
  2455. class NumberFloatType = double,
  2456. template<typename U> class AllocatorType = std::allocator,
  2457. template<typename T, typename SFINAE = void> class JSONSerializer =
  2458. adl_serializer,
  2459. class BinaryType = std::vector<std::uint8_t>>
  2460. class basic_json;
  2461. /*!
  2462. @brief JSON Pointer
  2463. A JSON pointer defines a string syntax for identifying a specific value
  2464. within a JSON document. It can be used with functions `at` and
  2465. `operator[]`. Furthermore, JSON pointers are the base for JSON patches.
  2466. @sa [RFC 6901](https://tools.ietf.org/html/rfc6901)
  2467. @since version 2.0.0
  2468. */
  2469. template<typename BasicJsonType>
  2470. class json_pointer;
  2471. /*!
  2472. @brief default JSON class
  2473. This type is the default specialization of the @ref basic_json class which
  2474. uses the standard template types.
  2475. @since version 1.0.0
  2476. */
  2477. using json = basic_json<>;
  2478. } // namespace nlohmann
  2479. #endif // INCLUDE_NLOHMANN_JSON_FWD_HPP_
  2480. namespace nlohmann
  2481. {
  2482. /*!
  2483. @brief detail namespace with internal helper functions
  2484. This namespace collects functions that should not be exposed,
  2485. implementations of some @ref basic_json methods, and meta-programming helpers.
  2486. @since version 2.1.0
  2487. */
  2488. namespace detail
  2489. {
  2490. /////////////
  2491. // helpers //
  2492. /////////////
  2493. // Note to maintainers:
  2494. //
  2495. // Every trait in this file expects a non CV-qualified type.
  2496. // The only exceptions are in the 'aliases for detected' section
  2497. // (i.e. those of the form: decltype(T::member_function(std::declval<T>())))
  2498. //
  2499. // In this case, T has to be properly CV-qualified to constraint the function arguments
  2500. // (e.g. to_json(BasicJsonType&, const T&))
  2501. template<typename> struct is_basic_json : std::false_type {};
  2502. NLOHMANN_BASIC_JSON_TPL_DECLARATION
  2503. struct is_basic_json<NLOHMANN_BASIC_JSON_TPL> : std::true_type {};
  2504. //////////////////////
  2505. // json_ref helpers //
  2506. //////////////////////
  2507. template <typename>
  2508. class json_ref;
  2509. template<typename>
  2510. struct is_json_ref : std::false_type {};
  2511. template <typename T>
  2512. struct is_json_ref<json_ref<T>> : std::true_type {};
  2513. //////////////////////////
  2514. // aliases for detected //
  2515. //////////////////////////
  2516. template <typename T>
  2517. using mapped_type_t = typename T::mapped_type;
  2518. template <typename T>
  2519. using key_type_t = typename T::key_type;
  2520. template <typename T>
  2521. using value_type_t = typename T::value_type;
  2522. template <typename T>
  2523. using difference_type_t = typename T::difference_type;
  2524. template <typename T>
  2525. using pointer_t = typename T::pointer;
  2526. template <typename T>
  2527. using reference_t = typename T::reference;
  2528. template <typename T>
  2529. using iterator_category_t = typename T::iterator_category;
  2530. template <typename T>
  2531. using iterator_t = typename T::iterator;
  2532. template <typename T, typename... Args>
  2533. using to_json_function = decltype(T::to_json(std::declval<Args>()...));
  2534. template <typename T, typename... Args>
  2535. using from_json_function = decltype(T::from_json(std::declval<Args>()...));
  2536. template <typename T, typename U>
  2537. using get_template_function = decltype(std::declval<T>().template get<U>());
  2538. // trait checking if JSONSerializer<T>::from_json(json const&, udt&) exists
  2539. template <typename BasicJsonType, typename T, typename = void>
  2540. struct has_from_json : std::false_type {};
  2541. template <typename BasicJsonType, typename T>
  2542. struct has_from_json<BasicJsonType, T,
  2543. enable_if_t<not is_basic_json<T>::value>>
  2544. {
  2545. using serializer = typename BasicJsonType::template json_serializer<T, void>;
  2546. static constexpr bool value =
  2547. is_detected_exact<void, from_json_function, serializer,
  2548. const BasicJsonType&, T&>::value;
  2549. };
  2550. // This trait checks if JSONSerializer<T>::from_json(json const&) exists
  2551. // this overload is used for non-default-constructible user-defined-types
  2552. template <typename BasicJsonType, typename T, typename = void>
  2553. struct has_non_default_from_json : std::false_type {};
  2554. template<typename BasicJsonType, typename T>
  2555. struct has_non_default_from_json<BasicJsonType, T, enable_if_t<not is_basic_json<T>::value>>
  2556. {
  2557. using serializer = typename BasicJsonType::template json_serializer<T, void>;
  2558. static constexpr bool value =
  2559. is_detected_exact<T, from_json_function, serializer,
  2560. const BasicJsonType&>::value;
  2561. };
  2562. // This trait checks if BasicJsonType::json_serializer<T>::to_json exists
  2563. // Do not evaluate the trait when T is a basic_json type, to avoid template instantiation infinite recursion.
  2564. template <typename BasicJsonType, typename T, typename = void>
  2565. struct has_to_json : std::false_type {};
  2566. template <typename BasicJsonType, typename T>
  2567. struct has_to_json<BasicJsonType, T, enable_if_t<not is_basic_json<T>::value>>
  2568. {
  2569. using serializer = typename BasicJsonType::template json_serializer<T, void>;
  2570. static constexpr bool value =
  2571. is_detected_exact<void, to_json_function, serializer, BasicJsonType&,
  2572. T>::value;
  2573. };
  2574. ///////////////////
  2575. // is_ functions //
  2576. ///////////////////
  2577. template <typename T, typename = void>
  2578. struct is_iterator_traits : std::false_type {};
  2579. template <typename T>
  2580. struct is_iterator_traits<iterator_traits<T>>
  2581. {
  2582. private:
  2583. using traits = iterator_traits<T>;
  2584. public:
  2585. static constexpr auto value =
  2586. is_detected<value_type_t, traits>::value &&
  2587. is_detected<difference_type_t, traits>::value &&
  2588. is_detected<pointer_t, traits>::value &&
  2589. is_detected<iterator_category_t, traits>::value &&
  2590. is_detected<reference_t, traits>::value;
  2591. };
  2592. // source: https://stackoverflow.com/a/37193089/4116453
  2593. template <typename T, typename = void>
  2594. struct is_complete_type : std::false_type {};
  2595. template <typename T>
  2596. struct is_complete_type<T, decltype(void(sizeof(T)))> : std::true_type {};
  2597. template <typename BasicJsonType, typename CompatibleObjectType,
  2598. typename = void>
  2599. struct is_compatible_object_type_impl : std::false_type {};
  2600. template <typename BasicJsonType, typename CompatibleObjectType>
  2601. struct is_compatible_object_type_impl <
  2602. BasicJsonType, CompatibleObjectType,
  2603. enable_if_t<is_detected<mapped_type_t, CompatibleObjectType>::value and
  2604. is_detected<key_type_t, CompatibleObjectType>::value >>
  2605. {
  2606. using object_t = typename BasicJsonType::object_t;
  2607. // macOS's is_constructible does not play well with nonesuch...
  2608. static constexpr bool value =
  2609. std::is_constructible<typename object_t::key_type,
  2610. typename CompatibleObjectType::key_type>::value and
  2611. std::is_constructible<typename object_t::mapped_type,
  2612. typename CompatibleObjectType::mapped_type>::value;
  2613. };
  2614. template <typename BasicJsonType, typename CompatibleObjectType>
  2615. struct is_compatible_object_type
  2616. : is_compatible_object_type_impl<BasicJsonType, CompatibleObjectType> {};
  2617. template <typename BasicJsonType, typename ConstructibleObjectType,
  2618. typename = void>
  2619. struct is_constructible_object_type_impl : std::false_type {};
  2620. template <typename BasicJsonType, typename ConstructibleObjectType>
  2621. struct is_constructible_object_type_impl <
  2622. BasicJsonType, ConstructibleObjectType,
  2623. enable_if_t<is_detected<mapped_type_t, ConstructibleObjectType>::value and
  2624. is_detected<key_type_t, ConstructibleObjectType>::value >>
  2625. {
  2626. using object_t = typename BasicJsonType::object_t;
  2627. static constexpr bool value =
  2628. (std::is_default_constructible<ConstructibleObjectType>::value and
  2629. (std::is_move_assignable<ConstructibleObjectType>::value or
  2630. std::is_copy_assignable<ConstructibleObjectType>::value) and
  2631. (std::is_constructible<typename ConstructibleObjectType::key_type,
  2632. typename object_t::key_type>::value and
  2633. std::is_same <
  2634. typename object_t::mapped_type,
  2635. typename ConstructibleObjectType::mapped_type >::value)) or
  2636. (has_from_json<BasicJsonType,
  2637. typename ConstructibleObjectType::mapped_type>::value or
  2638. has_non_default_from_json <
  2639. BasicJsonType,
  2640. typename ConstructibleObjectType::mapped_type >::value);
  2641. };
  2642. template <typename BasicJsonType, typename ConstructibleObjectType>
  2643. struct is_constructible_object_type
  2644. : is_constructible_object_type_impl<BasicJsonType,
  2645. ConstructibleObjectType> {};
  2646. template <typename BasicJsonType, typename CompatibleStringType,
  2647. typename = void>
  2648. struct is_compatible_string_type_impl : std::false_type {};
  2649. template <typename BasicJsonType, typename CompatibleStringType>
  2650. struct is_compatible_string_type_impl <
  2651. BasicJsonType, CompatibleStringType,
  2652. enable_if_t<is_detected_exact<typename BasicJsonType::string_t::value_type,
  2653. value_type_t, CompatibleStringType>::value >>
  2654. {
  2655. static constexpr auto value =
  2656. std::is_constructible<typename BasicJsonType::string_t, CompatibleStringType>::value;
  2657. };
  2658. template <typename BasicJsonType, typename ConstructibleStringType>
  2659. struct is_compatible_string_type
  2660. : is_compatible_string_type_impl<BasicJsonType, ConstructibleStringType> {};
  2661. template <typename BasicJsonType, typename ConstructibleStringType,
  2662. typename = void>
  2663. struct is_constructible_string_type_impl : std::false_type {};
  2664. template <typename BasicJsonType, typename ConstructibleStringType>
  2665. struct is_constructible_string_type_impl <
  2666. BasicJsonType, ConstructibleStringType,
  2667. enable_if_t<is_detected_exact<typename BasicJsonType::string_t::value_type,
  2668. value_type_t, ConstructibleStringType>::value >>
  2669. {
  2670. static constexpr auto value =
  2671. std::is_constructible<ConstructibleStringType,
  2672. typename BasicJsonType::string_t>::value;
  2673. };
  2674. template <typename BasicJsonType, typename ConstructibleStringType>
  2675. struct is_constructible_string_type
  2676. : is_constructible_string_type_impl<BasicJsonType, ConstructibleStringType> {};
  2677. template <typename BasicJsonType, typename CompatibleArrayType, typename = void>
  2678. struct is_compatible_array_type_impl : std::false_type {};
  2679. template <typename BasicJsonType, typename CompatibleArrayType>
  2680. struct is_compatible_array_type_impl <
  2681. BasicJsonType, CompatibleArrayType,
  2682. enable_if_t<is_detected<value_type_t, CompatibleArrayType>::value and
  2683. is_detected<iterator_t, CompatibleArrayType>::value and
  2684. // This is needed because json_reverse_iterator has a ::iterator type...
  2685. // Therefore it is detected as a CompatibleArrayType.
  2686. // The real fix would be to have an Iterable concept.
  2687. not is_iterator_traits<
  2688. iterator_traits<CompatibleArrayType>>::value >>
  2689. {
  2690. static constexpr bool value =
  2691. std::is_constructible<BasicJsonType,
  2692. typename CompatibleArrayType::value_type>::value;
  2693. };
  2694. template <typename BasicJsonType, typename CompatibleArrayType>
  2695. struct is_compatible_array_type
  2696. : is_compatible_array_type_impl<BasicJsonType, CompatibleArrayType> {};
  2697. template <typename BasicJsonType, typename ConstructibleArrayType, typename = void>
  2698. struct is_constructible_array_type_impl : std::false_type {};
  2699. template <typename BasicJsonType, typename ConstructibleArrayType>
  2700. struct is_constructible_array_type_impl <
  2701. BasicJsonType, ConstructibleArrayType,
  2702. enable_if_t<std::is_same<ConstructibleArrayType,
  2703. typename BasicJsonType::value_type>::value >>
  2704. : std::true_type {};
  2705. template <typename BasicJsonType, typename ConstructibleArrayType>
  2706. struct is_constructible_array_type_impl <
  2707. BasicJsonType, ConstructibleArrayType,
  2708. enable_if_t<not std::is_same<ConstructibleArrayType,
  2709. typename BasicJsonType::value_type>::value and
  2710. std::is_default_constructible<ConstructibleArrayType>::value and
  2711. (std::is_move_assignable<ConstructibleArrayType>::value or
  2712. std::is_copy_assignable<ConstructibleArrayType>::value) and
  2713. is_detected<value_type_t, ConstructibleArrayType>::value and
  2714. is_detected<iterator_t, ConstructibleArrayType>::value and
  2715. is_complete_type<
  2716. detected_t<value_type_t, ConstructibleArrayType>>::value >>
  2717. {
  2718. static constexpr bool value =
  2719. // This is needed because json_reverse_iterator has a ::iterator type,
  2720. // furthermore, std::back_insert_iterator (and other iterators) have a
  2721. // base class `iterator`... Therefore it is detected as a
  2722. // ConstructibleArrayType. The real fix would be to have an Iterable
  2723. // concept.
  2724. not is_iterator_traits<iterator_traits<ConstructibleArrayType>>::value and
  2725. (std::is_same<typename ConstructibleArrayType::value_type,
  2726. typename BasicJsonType::array_t::value_type>::value or
  2727. has_from_json<BasicJsonType,
  2728. typename ConstructibleArrayType::value_type>::value or
  2729. has_non_default_from_json <
  2730. BasicJsonType, typename ConstructibleArrayType::value_type >::value);
  2731. };
  2732. template <typename BasicJsonType, typename ConstructibleArrayType>
  2733. struct is_constructible_array_type
  2734. : is_constructible_array_type_impl<BasicJsonType, ConstructibleArrayType> {};
  2735. template <typename RealIntegerType, typename CompatibleNumberIntegerType,
  2736. typename = void>
  2737. struct is_compatible_integer_type_impl : std::false_type {};
  2738. template <typename RealIntegerType, typename CompatibleNumberIntegerType>
  2739. struct is_compatible_integer_type_impl <
  2740. RealIntegerType, CompatibleNumberIntegerType,
  2741. enable_if_t<std::is_integral<RealIntegerType>::value and
  2742. std::is_integral<CompatibleNumberIntegerType>::value and
  2743. not std::is_same<bool, CompatibleNumberIntegerType>::value >>
  2744. {
  2745. // is there an assert somewhere on overflows?
  2746. using RealLimits = std::numeric_limits<RealIntegerType>;
  2747. using CompatibleLimits = std::numeric_limits<CompatibleNumberIntegerType>;
  2748. static constexpr auto value =
  2749. std::is_constructible<RealIntegerType,
  2750. CompatibleNumberIntegerType>::value and
  2751. CompatibleLimits::is_integer and
  2752. RealLimits::is_signed == CompatibleLimits::is_signed;
  2753. };
  2754. template <typename RealIntegerType, typename CompatibleNumberIntegerType>
  2755. struct is_compatible_integer_type
  2756. : is_compatible_integer_type_impl<RealIntegerType,
  2757. CompatibleNumberIntegerType> {};
  2758. template <typename BasicJsonType, typename CompatibleType, typename = void>
  2759. struct is_compatible_type_impl: std::false_type {};
  2760. template <typename BasicJsonType, typename CompatibleType>
  2761. struct is_compatible_type_impl <
  2762. BasicJsonType, CompatibleType,
  2763. enable_if_t<is_complete_type<CompatibleType>::value >>
  2764. {
  2765. static constexpr bool value =
  2766. has_to_json<BasicJsonType, CompatibleType>::value;
  2767. };
  2768. template <typename BasicJsonType, typename CompatibleType>
  2769. struct is_compatible_type
  2770. : is_compatible_type_impl<BasicJsonType, CompatibleType> {};
  2771. // https://en.cppreference.com/w/cpp/types/conjunction
  2772. template<class...> struct conjunction : std::true_type { };
  2773. template<class B1> struct conjunction<B1> : B1 { };
  2774. template<class B1, class... Bn>
  2775. struct conjunction<B1, Bn...>
  2776. : std::conditional<bool(B1::value), conjunction<Bn...>, B1>::type {};
  2777. template <typename T1, typename T2>
  2778. struct is_constructible_tuple : std::false_type {};
  2779. template <typename T1, typename... Args>
  2780. struct is_constructible_tuple<T1, std::tuple<Args...>> : conjunction<std::is_constructible<T1, Args>...> {};
  2781. } // namespace detail
  2782. } // namespace nlohmann
  2783. // #include <nlohmann/detail/value_t.hpp>
  2784. #include <array> // array
  2785. #include <ciso646> // and
  2786. #include <cstddef> // size_t
  2787. #include <cstdint> // uint8_t
  2788. #include <string> // string
  2789. namespace nlohmann
  2790. {
  2791. namespace detail
  2792. {
  2793. ///////////////////////////
  2794. // JSON type enumeration //
  2795. ///////////////////////////
  2796. /*!
  2797. @brief the JSON type enumeration
  2798. This enumeration collects the different JSON types. It is internally used to
  2799. distinguish the stored values, and the functions @ref basic_json::is_null(),
  2800. @ref basic_json::is_object(), @ref basic_json::is_array(),
  2801. @ref basic_json::is_string(), @ref basic_json::is_boolean(),
  2802. @ref basic_json::is_number() (with @ref basic_json::is_number_integer(),
  2803. @ref basic_json::is_number_unsigned(), and @ref basic_json::is_number_float()),
  2804. @ref basic_json::is_discarded(), @ref basic_json::is_primitive(), and
  2805. @ref basic_json::is_structured() rely on it.
  2806. @note There are three enumeration entries (number_integer, number_unsigned, and
  2807. number_float), because the library distinguishes these three types for numbers:
  2808. @ref basic_json::number_unsigned_t is used for unsigned integers,
  2809. @ref basic_json::number_integer_t is used for signed integers, and
  2810. @ref basic_json::number_float_t is used for floating-point numbers or to
  2811. approximate integers which do not fit in the limits of their respective type.
  2812. @sa @ref basic_json::basic_json(const value_t value_type) -- create a JSON
  2813. value with the default value for a given type
  2814. @since version 1.0.0
  2815. */
  2816. enum class value_t : std::uint8_t
  2817. {
  2818. null, ///< null value
  2819. object, ///< object (unordered set of name/value pairs)
  2820. array, ///< array (ordered collection of values)
  2821. string, ///< string value
  2822. boolean, ///< boolean value
  2823. number_integer, ///< number value (signed integer)
  2824. number_unsigned, ///< number value (unsigned integer)
  2825. number_float, ///< number value (floating-point)
  2826. binary, ///< binary array (ordered collection of bytes)
  2827. discarded ///< discarded by the parser callback function
  2828. };
  2829. /*!
  2830. @brief comparison operator for JSON types
  2831. Returns an ordering that is similar to Python:
  2832. - order: null < boolean < number < object < array < string < binary
  2833. - furthermore, each type is not smaller than itself
  2834. - discarded values are not comparable
  2835. - binary is represented as a b"" string in python and directly comparable to a
  2836. string; however, making a binary array directly comparable with a string would
  2837. be surprising behavior in a JSON file.
  2838. @since version 1.0.0
  2839. */
  2840. inline bool operator<(const value_t lhs, const value_t rhs) noexcept
  2841. {
  2842. static constexpr std::array<std::uint8_t, 9> order = {{
  2843. 0 /* null */, 3 /* object */, 4 /* array */, 5 /* string */,
  2844. 1 /* boolean */, 2 /* integer */, 2 /* unsigned */, 2 /* float */,
  2845. 6 /* binary */
  2846. }
  2847. };
  2848. const auto l_index = static_cast<std::size_t>(lhs);
  2849. const auto r_index = static_cast<std::size_t>(rhs);
  2850. return l_index < order.size() and r_index < order.size() and order[l_index] < order[r_index];
  2851. }
  2852. } // namespace detail
  2853. } // namespace nlohmann
  2854. namespace nlohmann
  2855. {
  2856. namespace detail
  2857. {
  2858. template<typename BasicJsonType>
  2859. void from_json(const BasicJsonType& j, typename std::nullptr_t& n)
  2860. {
  2861. if (JSON_HEDLEY_UNLIKELY(not j.is_null()))
  2862. {
  2863. JSON_THROW(type_error::create(302, "type must be null, but is " + std::string(j.type_name())));
  2864. }
  2865. n = nullptr;
  2866. }
  2867. // overloads for basic_json template parameters
  2868. template<typename BasicJsonType, typename ArithmeticType,
  2869. enable_if_t<std::is_arithmetic<ArithmeticType>::value and
  2870. not std::is_same<ArithmeticType, typename BasicJsonType::boolean_t>::value,
  2871. int> = 0>
  2872. void get_arithmetic_value(const BasicJsonType& j, ArithmeticType& val)
  2873. {
  2874. switch (static_cast<value_t>(j))
  2875. {
  2876. case value_t::number_unsigned:
  2877. {
  2878. val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::number_unsigned_t*>());
  2879. break;
  2880. }
  2881. case value_t::number_integer:
  2882. {
  2883. val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::number_integer_t*>());
  2884. break;
  2885. }
  2886. case value_t::number_float:
  2887. {
  2888. val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::number_float_t*>());
  2889. break;
  2890. }
  2891. default:
  2892. JSON_THROW(type_error::create(302, "type must be number, but is " + std::string(j.type_name())));
  2893. }
  2894. }
  2895. template<typename BasicJsonType>
  2896. void from_json(const BasicJsonType& j, typename BasicJsonType::boolean_t& b)
  2897. {
  2898. if (JSON_HEDLEY_UNLIKELY(not j.is_boolean()))
  2899. {
  2900. JSON_THROW(type_error::create(302, "type must be boolean, but is " + std::string(j.type_name())));
  2901. }
  2902. b = *j.template get_ptr<const typename BasicJsonType::boolean_t*>();
  2903. }
  2904. template<typename BasicJsonType>
  2905. void from_json(const BasicJsonType& j, typename BasicJsonType::string_t& s)
  2906. {
  2907. if (JSON_HEDLEY_UNLIKELY(not j.is_string()))
  2908. {
  2909. JSON_THROW(type_error::create(302, "type must be string, but is " + std::string(j.type_name())));
  2910. }
  2911. s = *j.template get_ptr<const typename BasicJsonType::string_t*>();
  2912. }
  2913. template <
  2914. typename BasicJsonType, typename ConstructibleStringType,
  2915. enable_if_t <
  2916. is_constructible_string_type<BasicJsonType, ConstructibleStringType>::value and
  2917. not std::is_same<typename BasicJsonType::string_t,
  2918. ConstructibleStringType>::value,
  2919. int > = 0 >
  2920. void from_json(const BasicJsonType& j, ConstructibleStringType& s)
  2921. {
  2922. if (JSON_HEDLEY_UNLIKELY(not j.is_string()))
  2923. {
  2924. JSON_THROW(type_error::create(302, "type must be string, but is " + std::string(j.type_name())));
  2925. }
  2926. s = *j.template get_ptr<const typename BasicJsonType::string_t*>();
  2927. }
  2928. template<typename BasicJsonType>
  2929. void from_json(const BasicJsonType& j, typename BasicJsonType::number_float_t& val)
  2930. {
  2931. get_arithmetic_value(j, val);
  2932. }
  2933. template<typename BasicJsonType>
  2934. void from_json(const BasicJsonType& j, typename BasicJsonType::number_unsigned_t& val)
  2935. {
  2936. get_arithmetic_value(j, val);
  2937. }
  2938. template<typename BasicJsonType>
  2939. void from_json(const BasicJsonType& j, typename BasicJsonType::number_integer_t& val)
  2940. {
  2941. get_arithmetic_value(j, val);
  2942. }
  2943. template<typename BasicJsonType, typename EnumType,
  2944. enable_if_t<std::is_enum<EnumType>::value, int> = 0>
  2945. void from_json(const BasicJsonType& j, EnumType& e)
  2946. {
  2947. typename std::underlying_type<EnumType>::type val;
  2948. get_arithmetic_value(j, val);
  2949. e = static_cast<EnumType>(val);
  2950. }
  2951. // forward_list doesn't have an insert method
  2952. template<typename BasicJsonType, typename T, typename Allocator,
  2953. enable_if_t<std::is_convertible<BasicJsonType, T>::value, int> = 0>
  2954. void from_json(const BasicJsonType& j, std::forward_list<T, Allocator>& l)
  2955. {
  2956. if (JSON_HEDLEY_UNLIKELY(not j.is_array()))
  2957. {
  2958. JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(j.type_name())));
  2959. }
  2960. l.clear();
  2961. std::transform(j.rbegin(), j.rend(),
  2962. std::front_inserter(l), [](const BasicJsonType & i)
  2963. {
  2964. return i.template get<T>();
  2965. });
  2966. }
  2967. // valarray doesn't have an insert method
  2968. template<typename BasicJsonType, typename T,
  2969. enable_if_t<std::is_convertible<BasicJsonType, T>::value, int> = 0>
  2970. void from_json(const BasicJsonType& j, std::valarray<T>& l)
  2971. {
  2972. if (JSON_HEDLEY_UNLIKELY(not j.is_array()))
  2973. {
  2974. JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(j.type_name())));
  2975. }
  2976. l.resize(j.size());
  2977. std::copy(j.begin(), j.end(), std::begin(l));
  2978. }
  2979. template <typename BasicJsonType, typename T, std::size_t N>
  2980. auto from_json(const BasicJsonType& j, T (&arr)[N])
  2981. -> decltype(j.template get<T>(), void())
  2982. {
  2983. for (std::size_t i = 0; i < N; ++i)
  2984. {
  2985. arr[i] = j.at(i).template get<T>();
  2986. }
  2987. }
  2988. template<typename BasicJsonType>
  2989. void from_json_array_impl(const BasicJsonType& j, typename BasicJsonType::array_t& arr, priority_tag<3> /*unused*/)
  2990. {
  2991. arr = *j.template get_ptr<const typename BasicJsonType::array_t*>();
  2992. }
  2993. template <typename BasicJsonType, typename T, std::size_t N>
  2994. auto from_json_array_impl(const BasicJsonType& j, std::array<T, N>& arr,
  2995. priority_tag<2> /*unused*/)
  2996. -> decltype(j.template get<T>(), void())
  2997. {
  2998. for (std::size_t i = 0; i < N; ++i)
  2999. {
  3000. arr[i] = j.at(i).template get<T>();
  3001. }
  3002. }
  3003. template<typename BasicJsonType, typename ConstructibleArrayType>
  3004. auto from_json_array_impl(const BasicJsonType& j, ConstructibleArrayType& arr, priority_tag<1> /*unused*/)
  3005. -> decltype(
  3006. arr.reserve(std::declval<typename ConstructibleArrayType::size_type>()),
  3007. j.template get<typename ConstructibleArrayType::value_type>(),
  3008. void())
  3009. {
  3010. using std::end;
  3011. ConstructibleArrayType ret;
  3012. ret.reserve(j.size());
  3013. std::transform(j.begin(), j.end(),
  3014. std::inserter(ret, end(ret)), [](const BasicJsonType & i)
  3015. {
  3016. // get<BasicJsonType>() returns *this, this won't call a from_json
  3017. // method when value_type is BasicJsonType
  3018. return i.template get<typename ConstructibleArrayType::value_type>();
  3019. });
  3020. arr = std::move(ret);
  3021. }
  3022. template <typename BasicJsonType, typename ConstructibleArrayType>
  3023. void from_json_array_impl(const BasicJsonType& j, ConstructibleArrayType& arr,
  3024. priority_tag<0> /*unused*/)
  3025. {
  3026. using std::end;
  3027. ConstructibleArrayType ret;
  3028. std::transform(
  3029. j.begin(), j.end(), std::inserter(ret, end(ret)),
  3030. [](const BasicJsonType & i)
  3031. {
  3032. // get<BasicJsonType>() returns *this, this won't call a from_json
  3033. // method when value_type is BasicJsonType
  3034. return i.template get<typename ConstructibleArrayType::value_type>();
  3035. });
  3036. arr = std::move(ret);
  3037. }
  3038. template <typename BasicJsonType, typename ConstructibleArrayType,
  3039. enable_if_t <
  3040. is_constructible_array_type<BasicJsonType, ConstructibleArrayType>::value and
  3041. not is_constructible_object_type<BasicJsonType, ConstructibleArrayType>::value and
  3042. not is_constructible_string_type<BasicJsonType, ConstructibleArrayType>::value and
  3043. not is_basic_json<ConstructibleArrayType>::value,
  3044. int > = 0 >
  3045. auto from_json(const BasicJsonType& j, ConstructibleArrayType& arr)
  3046. -> decltype(from_json_array_impl(j, arr, priority_tag<3> {}),
  3047. j.template get<typename ConstructibleArrayType::value_type>(),
  3048. void())
  3049. {
  3050. if (JSON_HEDLEY_UNLIKELY(not j.is_array()))
  3051. {
  3052. JSON_THROW(type_error::create(302, "type must be array, but is " +
  3053. std::string(j.type_name())));
  3054. }
  3055. from_json_array_impl(j, arr, priority_tag<3> {});
  3056. }
  3057. template<typename BasicJsonType, typename ConstructibleObjectType,
  3058. enable_if_t<is_constructible_object_type<BasicJsonType, ConstructibleObjectType>::value, int> = 0>
  3059. void from_json(const BasicJsonType& j, ConstructibleObjectType& obj)
  3060. {
  3061. if (JSON_HEDLEY_UNLIKELY(not j.is_object()))
  3062. {
  3063. JSON_THROW(type_error::create(302, "type must be object, but is " + std::string(j.type_name())));
  3064. }
  3065. ConstructibleObjectType ret;
  3066. auto inner_object = j.template get_ptr<const typename BasicJsonType::object_t*>();
  3067. using value_type = typename ConstructibleObjectType::value_type;
  3068. std::transform(
  3069. inner_object->begin(), inner_object->end(),
  3070. std::inserter(ret, ret.begin()),
  3071. [](typename BasicJsonType::object_t::value_type const & p)
  3072. {
  3073. return value_type(p.first, p.second.template get<typename ConstructibleObjectType::mapped_type>());
  3074. });
  3075. obj = std::move(ret);
  3076. }
  3077. // overload for arithmetic types, not chosen for basic_json template arguments
  3078. // (BooleanType, etc..); note: Is it really necessary to provide explicit
  3079. // overloads for boolean_t etc. in case of a custom BooleanType which is not
  3080. // an arithmetic type?
  3081. template<typename BasicJsonType, typename ArithmeticType,
  3082. enable_if_t <
  3083. std::is_arithmetic<ArithmeticType>::value and
  3084. not std::is_same<ArithmeticType, typename BasicJsonType::number_unsigned_t>::value and
  3085. not std::is_same<ArithmeticType, typename BasicJsonType::number_integer_t>::value and
  3086. not std::is_same<ArithmeticType, typename BasicJsonType::number_float_t>::value and
  3087. not std::is_same<ArithmeticType, typename BasicJsonType::boolean_t>::value,
  3088. int> = 0>
  3089. void from_json(const BasicJsonType& j, ArithmeticType& val)
  3090. {
  3091. switch (static_cast<value_t>(j))
  3092. {
  3093. case value_t::number_unsigned:
  3094. {
  3095. val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::number_unsigned_t*>());
  3096. break;
  3097. }
  3098. case value_t::number_integer:
  3099. {
  3100. val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::number_integer_t*>());
  3101. break;
  3102. }
  3103. case value_t::number_float:
  3104. {
  3105. val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::number_float_t*>());
  3106. break;
  3107. }
  3108. case value_t::boolean:
  3109. {
  3110. val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::boolean_t*>());
  3111. break;
  3112. }
  3113. default:
  3114. JSON_THROW(type_error::create(302, "type must be number, but is " + std::string(j.type_name())));
  3115. }
  3116. }
  3117. template<typename BasicJsonType, typename A1, typename A2>
  3118. void from_json(const BasicJsonType& j, std::pair<A1, A2>& p)
  3119. {
  3120. p = {j.at(0).template get<A1>(), j.at(1).template get<A2>()};
  3121. }
  3122. template<typename BasicJsonType, typename Tuple, std::size_t... Idx>
  3123. void from_json_tuple_impl(const BasicJsonType& j, Tuple& t, index_sequence<Idx...> /*unused*/)
  3124. {
  3125. t = std::make_tuple(j.at(Idx).template get<typename std::tuple_element<Idx, Tuple>::type>()...);
  3126. }
  3127. template<typename BasicJsonType, typename... Args>
  3128. void from_json(const BasicJsonType& j, std::tuple<Args...>& t)
  3129. {
  3130. from_json_tuple_impl(j, t, index_sequence_for<Args...> {});
  3131. }
  3132. template <typename BasicJsonType, typename Key, typename Value, typename Compare, typename Allocator,
  3133. typename = enable_if_t<not std::is_constructible<
  3134. typename BasicJsonType::string_t, Key>::value>>
  3135. void from_json(const BasicJsonType& j, std::map<Key, Value, Compare, Allocator>& m)
  3136. {
  3137. if (JSON_HEDLEY_UNLIKELY(not j.is_array()))
  3138. {
  3139. JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(j.type_name())));
  3140. }
  3141. m.clear();
  3142. for (const auto& p : j)
  3143. {
  3144. if (JSON_HEDLEY_UNLIKELY(not p.is_array()))
  3145. {
  3146. JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(p.type_name())));
  3147. }
  3148. m.emplace(p.at(0).template get<Key>(), p.at(1).template get<Value>());
  3149. }
  3150. }
  3151. template <typename BasicJsonType, typename Key, typename Value, typename Hash, typename KeyEqual, typename Allocator,
  3152. typename = enable_if_t<not std::is_constructible<
  3153. typename BasicJsonType::string_t, Key>::value>>
  3154. void from_json(const BasicJsonType& j, std::unordered_map<Key, Value, Hash, KeyEqual, Allocator>& m)
  3155. {
  3156. if (JSON_HEDLEY_UNLIKELY(not j.is_array()))
  3157. {
  3158. JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(j.type_name())));
  3159. }
  3160. m.clear();
  3161. for (const auto& p : j)
  3162. {
  3163. if (JSON_HEDLEY_UNLIKELY(not p.is_array()))
  3164. {
  3165. JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(p.type_name())));
  3166. }
  3167. m.emplace(p.at(0).template get<Key>(), p.at(1).template get<Value>());
  3168. }
  3169. }
  3170. struct from_json_fn
  3171. {
  3172. template<typename BasicJsonType, typename T>
  3173. auto operator()(const BasicJsonType& j, T& val) const
  3174. noexcept(noexcept(from_json(j, val)))
  3175. -> decltype(from_json(j, val), void())
  3176. {
  3177. return from_json(j, val);
  3178. }
  3179. };
  3180. } // namespace detail
  3181. /// namespace to hold default `from_json` function
  3182. /// to see why this is required:
  3183. /// http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2015/n4381.html
  3184. namespace
  3185. {
  3186. constexpr const auto& from_json = detail::static_const<detail::from_json_fn>::value;
  3187. } // namespace
  3188. } // namespace nlohmann
  3189. // #include <nlohmann/detail/conversions/to_json.hpp>
  3190. #include <algorithm> // copy
  3191. #include <ciso646> // or, and, not
  3192. #include <iterator> // begin, end
  3193. #include <string> // string
  3194. #include <tuple> // tuple, get
  3195. #include <type_traits> // is_same, is_constructible, is_floating_point, is_enum, underlying_type
  3196. #include <utility> // move, forward, declval, pair
  3197. #include <valarray> // valarray
  3198. #include <vector> // vector
  3199. // #include <nlohmann/detail/iterators/iteration_proxy.hpp>
  3200. #include <cstddef> // size_t
  3201. #include <iterator> // input_iterator_tag
  3202. #include <string> // string, to_string
  3203. #include <tuple> // tuple_size, get, tuple_element
  3204. // #include <nlohmann/detail/meta/type_traits.hpp>
  3205. // #include <nlohmann/detail/value_t.hpp>
  3206. namespace nlohmann
  3207. {
  3208. namespace detail
  3209. {
  3210. template<typename string_type>
  3211. void int_to_string( string_type& target, std::size_t value )
  3212. {
  3213. target = std::to_string(value);
  3214. }
  3215. template <typename IteratorType> class iteration_proxy_value
  3216. {
  3217. public:
  3218. using difference_type = std::ptrdiff_t;
  3219. using value_type = iteration_proxy_value;
  3220. using pointer = value_type * ;
  3221. using reference = value_type & ;
  3222. using iterator_category = std::input_iterator_tag;
  3223. using string_type = typename std::remove_cv< typename std::remove_reference<decltype( std::declval<IteratorType>().key() ) >::type >::type;
  3224. private:
  3225. /// the iterator
  3226. IteratorType anchor;
  3227. /// an index for arrays (used to create key names)
  3228. std::size_t array_index = 0;
  3229. /// last stringified array index
  3230. mutable std::size_t array_index_last = 0;
  3231. /// a string representation of the array index
  3232. mutable string_type array_index_str = "0";
  3233. /// an empty string (to return a reference for primitive values)
  3234. const string_type empty_str = "";
  3235. public:
  3236. explicit iteration_proxy_value(IteratorType it) noexcept : anchor(it) {}
  3237. /// dereference operator (needed for range-based for)
  3238. iteration_proxy_value& operator*()
  3239. {
  3240. return *this;
  3241. }
  3242. /// increment operator (needed for range-based for)
  3243. iteration_proxy_value& operator++()
  3244. {
  3245. ++anchor;
  3246. ++array_index;
  3247. return *this;
  3248. }
  3249. /// equality operator (needed for InputIterator)
  3250. bool operator==(const iteration_proxy_value& o) const
  3251. {
  3252. return anchor == o.anchor;
  3253. }
  3254. /// inequality operator (needed for range-based for)
  3255. bool operator!=(const iteration_proxy_value& o) const
  3256. {
  3257. return anchor != o.anchor;
  3258. }
  3259. /// return key of the iterator
  3260. const string_type& key() const
  3261. {
  3262. assert(anchor.m_object != nullptr);
  3263. switch (anchor.m_object->type())
  3264. {
  3265. // use integer array index as key
  3266. case value_t::array:
  3267. {
  3268. if (array_index != array_index_last)
  3269. {
  3270. int_to_string( array_index_str, array_index );
  3271. array_index_last = array_index;
  3272. }
  3273. return array_index_str;
  3274. }
  3275. // use key from the object
  3276. case value_t::object:
  3277. return anchor.key();
  3278. // use an empty key for all primitive types
  3279. default:
  3280. return empty_str;
  3281. }
  3282. }
  3283. /// return value of the iterator
  3284. typename IteratorType::reference value() const
  3285. {
  3286. return anchor.value();
  3287. }
  3288. };
  3289. /// proxy class for the items() function
  3290. template<typename IteratorType> class iteration_proxy
  3291. {
  3292. private:
  3293. /// the container to iterate
  3294. typename IteratorType::reference container;
  3295. public:
  3296. /// construct iteration proxy from a container
  3297. explicit iteration_proxy(typename IteratorType::reference cont) noexcept
  3298. : container(cont) {}
  3299. /// return iterator begin (needed for range-based for)
  3300. iteration_proxy_value<IteratorType> begin() noexcept
  3301. {
  3302. return iteration_proxy_value<IteratorType>(container.begin());
  3303. }
  3304. /// return iterator end (needed for range-based for)
  3305. iteration_proxy_value<IteratorType> end() noexcept
  3306. {
  3307. return iteration_proxy_value<IteratorType>(container.end());
  3308. }
  3309. };
  3310. // Structured Bindings Support
  3311. // For further reference see https://blog.tartanllama.xyz/structured-bindings/
  3312. // And see https://github.com/nlohmann/json/pull/1391
  3313. template <std::size_t N, typename IteratorType, enable_if_t<N == 0, int> = 0>
  3314. auto get(const nlohmann::detail::iteration_proxy_value<IteratorType>& i) -> decltype(i.key())
  3315. {
  3316. return i.key();
  3317. }
  3318. // Structured Bindings Support
  3319. // For further reference see https://blog.tartanllama.xyz/structured-bindings/
  3320. // And see https://github.com/nlohmann/json/pull/1391
  3321. template <std::size_t N, typename IteratorType, enable_if_t<N == 1, int> = 0>
  3322. auto get(const nlohmann::detail::iteration_proxy_value<IteratorType>& i) -> decltype(i.value())
  3323. {
  3324. return i.value();
  3325. }
  3326. } // namespace detail
  3327. } // namespace nlohmann
  3328. // The Addition to the STD Namespace is required to add
  3329. // Structured Bindings Support to the iteration_proxy_value class
  3330. // For further reference see https://blog.tartanllama.xyz/structured-bindings/
  3331. // And see https://github.com/nlohmann/json/pull/1391
  3332. namespace std
  3333. {
  3334. #if defined(__clang__)
  3335. // Fix: https://github.com/nlohmann/json/issues/1401
  3336. #pragma clang diagnostic push
  3337. #pragma clang diagnostic ignored "-Wmismatched-tags"
  3338. #endif
  3339. template <typename IteratorType>
  3340. class tuple_size<::nlohmann::detail::iteration_proxy_value<IteratorType>>
  3341. : public std::integral_constant<std::size_t, 2> {};
  3342. template <std::size_t N, typename IteratorType>
  3343. class tuple_element<N, ::nlohmann::detail::iteration_proxy_value<IteratorType >>
  3344. {
  3345. public:
  3346. using type = decltype(
  3347. get<N>(std::declval <
  3348. ::nlohmann::detail::iteration_proxy_value<IteratorType >> ()));
  3349. };
  3350. #if defined(__clang__)
  3351. #pragma clang diagnostic pop
  3352. #endif
  3353. } // namespace std
  3354. // #include <nlohmann/detail/meta/cpp_future.hpp>
  3355. // #include <nlohmann/detail/meta/type_traits.hpp>
  3356. // #include <nlohmann/detail/value_t.hpp>
  3357. namespace nlohmann
  3358. {
  3359. namespace detail
  3360. {
  3361. //////////////////
  3362. // constructors //
  3363. //////////////////
  3364. template<value_t> struct external_constructor;
  3365. template<>
  3366. struct external_constructor<value_t::boolean>
  3367. {
  3368. template<typename BasicJsonType>
  3369. static void construct(BasicJsonType& j, typename BasicJsonType::boolean_t b) noexcept
  3370. {
  3371. j.m_type = value_t::boolean;
  3372. j.m_value = b;
  3373. j.assert_invariant();
  3374. }
  3375. };
  3376. template<>
  3377. struct external_constructor<value_t::string>
  3378. {
  3379. template<typename BasicJsonType>
  3380. static void construct(BasicJsonType& j, const typename BasicJsonType::string_t& s)
  3381. {
  3382. j.m_type = value_t::string;
  3383. j.m_value = s;
  3384. j.assert_invariant();
  3385. }
  3386. template<typename BasicJsonType>
  3387. static void construct(BasicJsonType& j, typename BasicJsonType::string_t&& s)
  3388. {
  3389. j.m_type = value_t::string;
  3390. j.m_value = std::move(s);
  3391. j.assert_invariant();
  3392. }
  3393. template<typename BasicJsonType, typename CompatibleStringType,
  3394. enable_if_t<not std::is_same<CompatibleStringType, typename BasicJsonType::string_t>::value,
  3395. int> = 0>
  3396. static void construct(BasicJsonType& j, const CompatibleStringType& str)
  3397. {
  3398. j.m_type = value_t::string;
  3399. j.m_value.string = j.template create<typename BasicJsonType::string_t>(str);
  3400. j.assert_invariant();
  3401. }
  3402. };
  3403. template<>
  3404. struct external_constructor<value_t::binary>
  3405. {
  3406. template<typename BasicJsonType>
  3407. static void construct(BasicJsonType& j, const typename BasicJsonType::binary_t& b)
  3408. {
  3409. j.m_type = value_t::binary;
  3410. typename BasicJsonType::internal_binary_t value{b};
  3411. j.m_value = value;
  3412. j.assert_invariant();
  3413. }
  3414. template<typename BasicJsonType>
  3415. static void construct(BasicJsonType& j, typename BasicJsonType::binary_t&& b)
  3416. {
  3417. j.m_type = value_t::binary;
  3418. typename BasicJsonType::internal_binary_t value{std::move(b)};
  3419. j.m_value = value;
  3420. j.assert_invariant();
  3421. }
  3422. };
  3423. template<>
  3424. struct external_constructor<value_t::number_float>
  3425. {
  3426. template<typename BasicJsonType>
  3427. static void construct(BasicJsonType& j, typename BasicJsonType::number_float_t val) noexcept
  3428. {
  3429. j.m_type = value_t::number_float;
  3430. j.m_value = val;
  3431. j.assert_invariant();
  3432. }
  3433. };
  3434. template<>
  3435. struct external_constructor<value_t::number_unsigned>
  3436. {
  3437. template<typename BasicJsonType>
  3438. static void construct(BasicJsonType& j, typename BasicJsonType::number_unsigned_t val) noexcept
  3439. {
  3440. j.m_type = value_t::number_unsigned;
  3441. j.m_value = val;
  3442. j.assert_invariant();
  3443. }
  3444. };
  3445. template<>
  3446. struct external_constructor<value_t::number_integer>
  3447. {
  3448. template<typename BasicJsonType>
  3449. static void construct(BasicJsonType& j, typename BasicJsonType::number_integer_t val) noexcept
  3450. {
  3451. j.m_type = value_t::number_integer;
  3452. j.m_value = val;
  3453. j.assert_invariant();
  3454. }
  3455. };
  3456. template<>
  3457. struct external_constructor<value_t::array>
  3458. {
  3459. template<typename BasicJsonType>
  3460. static void construct(BasicJsonType& j, const typename BasicJsonType::array_t& arr)
  3461. {
  3462. j.m_type = value_t::array;
  3463. j.m_value = arr;
  3464. j.assert_invariant();
  3465. }
  3466. template<typename BasicJsonType>
  3467. static void construct(BasicJsonType& j, typename BasicJsonType::array_t&& arr)
  3468. {
  3469. j.m_type = value_t::array;
  3470. j.m_value = std::move(arr);
  3471. j.assert_invariant();
  3472. }
  3473. template<typename BasicJsonType, typename CompatibleArrayType,
  3474. enable_if_t<not std::is_same<CompatibleArrayType, typename BasicJsonType::array_t>::value,
  3475. int> = 0>
  3476. static void construct(BasicJsonType& j, const CompatibleArrayType& arr)
  3477. {
  3478. using std::begin;
  3479. using std::end;
  3480. j.m_type = value_t::array;
  3481. j.m_value.array = j.template create<typename BasicJsonType::array_t>(begin(arr), end(arr));
  3482. j.assert_invariant();
  3483. }
  3484. template<typename BasicJsonType>
  3485. static void construct(BasicJsonType& j, const std::vector<bool>& arr)
  3486. {
  3487. j.m_type = value_t::array;
  3488. j.m_value = value_t::array;
  3489. j.m_value.array->reserve(arr.size());
  3490. for (const bool x : arr)
  3491. {
  3492. j.m_value.array->push_back(x);
  3493. }
  3494. j.assert_invariant();
  3495. }
  3496. template<typename BasicJsonType, typename T,
  3497. enable_if_t<std::is_convertible<T, BasicJsonType>::value, int> = 0>
  3498. static void construct(BasicJsonType& j, const std::valarray<T>& arr)
  3499. {
  3500. j.m_type = value_t::array;
  3501. j.m_value = value_t::array;
  3502. j.m_value.array->resize(arr.size());
  3503. if (arr.size() > 0)
  3504. {
  3505. std::copy(std::begin(arr), std::end(arr), j.m_value.array->begin());
  3506. }
  3507. j.assert_invariant();
  3508. }
  3509. };
  3510. template<>
  3511. struct external_constructor<value_t::object>
  3512. {
  3513. template<typename BasicJsonType>
  3514. static void construct(BasicJsonType& j, const typename BasicJsonType::object_t& obj)
  3515. {
  3516. j.m_type = value_t::object;
  3517. j.m_value = obj;
  3518. j.assert_invariant();
  3519. }
  3520. template<typename BasicJsonType>
  3521. static void construct(BasicJsonType& j, typename BasicJsonType::object_t&& obj)
  3522. {
  3523. j.m_type = value_t::object;
  3524. j.m_value = std::move(obj);
  3525. j.assert_invariant();
  3526. }
  3527. template<typename BasicJsonType, typename CompatibleObjectType,
  3528. enable_if_t<not std::is_same<CompatibleObjectType, typename BasicJsonType::object_t>::value, int> = 0>
  3529. static void construct(BasicJsonType& j, const CompatibleObjectType& obj)
  3530. {
  3531. using std::begin;
  3532. using std::end;
  3533. j.m_type = value_t::object;
  3534. j.m_value.object = j.template create<typename BasicJsonType::object_t>(begin(obj), end(obj));
  3535. j.assert_invariant();
  3536. }
  3537. };
  3538. /////////////
  3539. // to_json //
  3540. /////////////
  3541. template<typename BasicJsonType, typename T,
  3542. enable_if_t<std::is_same<T, typename BasicJsonType::boolean_t>::value, int> = 0>
  3543. void to_json(BasicJsonType& j, T b) noexcept
  3544. {
  3545. external_constructor<value_t::boolean>::construct(j, b);
  3546. }
  3547. template<typename BasicJsonType, typename CompatibleString,
  3548. enable_if_t<std::is_constructible<typename BasicJsonType::string_t, CompatibleString>::value, int> = 0>
  3549. void to_json(BasicJsonType& j, const CompatibleString& s)
  3550. {
  3551. external_constructor<value_t::string>::construct(j, s);
  3552. }
  3553. template<typename BasicJsonType>
  3554. void to_json(BasicJsonType& j, typename BasicJsonType::string_t&& s)
  3555. {
  3556. external_constructor<value_t::string>::construct(j, std::move(s));
  3557. }
  3558. template<typename BasicJsonType, typename FloatType,
  3559. enable_if_t<std::is_floating_point<FloatType>::value, int> = 0>
  3560. void to_json(BasicJsonType& j, FloatType val) noexcept
  3561. {
  3562. external_constructor<value_t::number_float>::construct(j, static_cast<typename BasicJsonType::number_float_t>(val));
  3563. }
  3564. template<typename BasicJsonType, typename CompatibleNumberUnsignedType,
  3565. enable_if_t<is_compatible_integer_type<typename BasicJsonType::number_unsigned_t, CompatibleNumberUnsignedType>::value, int> = 0>
  3566. void to_json(BasicJsonType& j, CompatibleNumberUnsignedType val) noexcept
  3567. {
  3568. external_constructor<value_t::number_unsigned>::construct(j, static_cast<typename BasicJsonType::number_unsigned_t>(val));
  3569. }
  3570. template<typename BasicJsonType, typename CompatibleNumberIntegerType,
  3571. enable_if_t<is_compatible_integer_type<typename BasicJsonType::number_integer_t, CompatibleNumberIntegerType>::value, int> = 0>
  3572. void to_json(BasicJsonType& j, CompatibleNumberIntegerType val) noexcept
  3573. {
  3574. external_constructor<value_t::number_integer>::construct(j, static_cast<typename BasicJsonType::number_integer_t>(val));
  3575. }
  3576. template<typename BasicJsonType, typename EnumType,
  3577. enable_if_t<std::is_enum<EnumType>::value, int> = 0>
  3578. void to_json(BasicJsonType& j, EnumType e) noexcept
  3579. {
  3580. using underlying_type = typename std::underlying_type<EnumType>::type;
  3581. external_constructor<value_t::number_integer>::construct(j, static_cast<underlying_type>(e));
  3582. }
  3583. template<typename BasicJsonType>
  3584. void to_json(BasicJsonType& j, const std::vector<bool>& e)
  3585. {
  3586. external_constructor<value_t::array>::construct(j, e);
  3587. }
  3588. template <typename BasicJsonType, typename CompatibleArrayType,
  3589. enable_if_t<is_compatible_array_type<BasicJsonType,
  3590. CompatibleArrayType>::value and
  3591. not is_compatible_object_type<
  3592. BasicJsonType, CompatibleArrayType>::value and
  3593. not is_compatible_string_type<BasicJsonType, CompatibleArrayType>::value and
  3594. not is_basic_json<CompatibleArrayType>::value,
  3595. int> = 0>
  3596. void to_json(BasicJsonType& j, const CompatibleArrayType& arr)
  3597. {
  3598. external_constructor<value_t::array>::construct(j, arr);
  3599. }
  3600. template<typename BasicJsonType, typename T,
  3601. enable_if_t<std::is_convertible<T, BasicJsonType>::value, int> = 0>
  3602. void to_json(BasicJsonType& j, const std::valarray<T>& arr)
  3603. {
  3604. external_constructor<value_t::array>::construct(j, std::move(arr));
  3605. }
  3606. template<typename BasicJsonType>
  3607. void to_json(BasicJsonType& j, typename BasicJsonType::array_t&& arr)
  3608. {
  3609. external_constructor<value_t::array>::construct(j, std::move(arr));
  3610. }
  3611. template<typename BasicJsonType, typename CompatibleObjectType,
  3612. enable_if_t<is_compatible_object_type<BasicJsonType, CompatibleObjectType>::value and not is_basic_json<CompatibleObjectType>::value, int> = 0>
  3613. void to_json(BasicJsonType& j, const CompatibleObjectType& obj)
  3614. {
  3615. external_constructor<value_t::object>::construct(j, obj);
  3616. }
  3617. template<typename BasicJsonType>
  3618. void to_json(BasicJsonType& j, typename BasicJsonType::object_t&& obj)
  3619. {
  3620. external_constructor<value_t::object>::construct(j, std::move(obj));
  3621. }
  3622. template <
  3623. typename BasicJsonType, typename T, std::size_t N,
  3624. enable_if_t<not std::is_constructible<typename BasicJsonType::string_t,
  3625. const T(&)[N]>::value,
  3626. int> = 0 >
  3627. void to_json(BasicJsonType& j, const T(&arr)[N])
  3628. {
  3629. external_constructor<value_t::array>::construct(j, arr);
  3630. }
  3631. template < typename BasicJsonType, typename T1, typename T2, enable_if_t < std::is_constructible<BasicJsonType, T1>::value&& std::is_constructible<BasicJsonType, T2>::value, int > = 0 >
  3632. void to_json(BasicJsonType& j, const std::pair<T1, T2>& p)
  3633. {
  3634. j = { p.first, p.second };
  3635. }
  3636. // for https://github.com/nlohmann/json/pull/1134
  3637. template < typename BasicJsonType, typename T,
  3638. enable_if_t<std::is_same<T, iteration_proxy_value<typename BasicJsonType::iterator>>::value, int> = 0>
  3639. void to_json(BasicJsonType& j, const T& b)
  3640. {
  3641. j = { {b.key(), b.value()} };
  3642. }
  3643. template<typename BasicJsonType, typename Tuple, std::size_t... Idx>
  3644. void to_json_tuple_impl(BasicJsonType& j, const Tuple& t, index_sequence<Idx...> /*unused*/)
  3645. {
  3646. j = { std::get<Idx>(t)... };
  3647. }
  3648. template<typename BasicJsonType, typename T, enable_if_t<is_constructible_tuple<BasicJsonType, T>::value, int > = 0>
  3649. void to_json(BasicJsonType& j, const T& t)
  3650. {
  3651. to_json_tuple_impl(j, t, make_index_sequence<std::tuple_size<T>::value> {});
  3652. }
  3653. struct to_json_fn
  3654. {
  3655. template<typename BasicJsonType, typename T>
  3656. auto operator()(BasicJsonType& j, T&& val) const noexcept(noexcept(to_json(j, std::forward<T>(val))))
  3657. -> decltype(to_json(j, std::forward<T>(val)), void())
  3658. {
  3659. return to_json(j, std::forward<T>(val));
  3660. }
  3661. };
  3662. } // namespace detail
  3663. /// namespace to hold default `to_json` function
  3664. namespace
  3665. {
  3666. constexpr const auto& to_json = detail::static_const<detail::to_json_fn>::value;
  3667. } // namespace
  3668. } // namespace nlohmann
  3669. namespace nlohmann
  3670. {
  3671. template<typename, typename>
  3672. struct adl_serializer
  3673. {
  3674. /*!
  3675. @brief convert a JSON value to any value type
  3676. This function is usually called by the `get()` function of the
  3677. @ref basic_json class (either explicit or via conversion operators).
  3678. @param[in] j JSON value to read from
  3679. @param[in,out] val value to write to
  3680. */
  3681. template<typename BasicJsonType, typename ValueType>
  3682. static auto from_json(BasicJsonType&& j, ValueType& val) noexcept(
  3683. noexcept(::nlohmann::from_json(std::forward<BasicJsonType>(j), val)))
  3684. -> decltype(::nlohmann::from_json(std::forward<BasicJsonType>(j), val), void())
  3685. {
  3686. ::nlohmann::from_json(std::forward<BasicJsonType>(j), val);
  3687. }
  3688. /*!
  3689. @brief convert any value type to a JSON value
  3690. This function is usually called by the constructors of the @ref basic_json
  3691. class.
  3692. @param[in,out] j JSON value to write to
  3693. @param[in] val value to read from
  3694. */
  3695. template <typename BasicJsonType, typename ValueType>
  3696. static auto to_json(BasicJsonType& j, ValueType&& val) noexcept(
  3697. noexcept(::nlohmann::to_json(j, std::forward<ValueType>(val))))
  3698. -> decltype(::nlohmann::to_json(j, std::forward<ValueType>(val)), void())
  3699. {
  3700. ::nlohmann::to_json(j, std::forward<ValueType>(val));
  3701. }
  3702. };
  3703. } // namespace nlohmann
  3704. // #include <nlohmann/detail/conversions/from_json.hpp>
  3705. // #include <nlohmann/detail/conversions/to_json.hpp>
  3706. // #include <nlohmann/detail/exceptions.hpp>
  3707. // #include <nlohmann/detail/input/binary_reader.hpp>
  3708. #include <algorithm> // generate_n
  3709. #include <array> // array
  3710. #include <cassert> // assert
  3711. #include <cmath> // ldexp
  3712. #include <cstddef> // size_t
  3713. #include <cstdint> // uint8_t, uint16_t, uint32_t, uint64_t
  3714. #include <cstdio> // snprintf
  3715. #include <cstring> // memcpy
  3716. #include <iterator> // back_inserter
  3717. #include <limits> // numeric_limits
  3718. #include <string> // char_traits, string
  3719. #include <utility> // make_pair, move
  3720. // #include <nlohmann/detail/exceptions.hpp>
  3721. // #include <nlohmann/detail/input/input_adapters.hpp>
  3722. #include <array> // array
  3723. #include <cassert> // assert
  3724. #include <cstddef> // size_t
  3725. #include <cstdio> //FILE *
  3726. #include <cstring> // strlen
  3727. #include <istream> // istream
  3728. #include <iterator> // begin, end, iterator_traits, random_access_iterator_tag, distance, next
  3729. #include <memory> // shared_ptr, make_shared, addressof
  3730. #include <numeric> // accumulate
  3731. #include <string> // string, char_traits
  3732. #include <type_traits> // enable_if, is_base_of, is_pointer, is_integral, remove_pointer
  3733. #include <utility> // pair, declval
  3734. // #include <nlohmann/detail/iterators/iterator_traits.hpp>
  3735. // #include <nlohmann/detail/macro_scope.hpp>
  3736. namespace nlohmann
  3737. {
  3738. namespace detail
  3739. {
  3740. /// the supported input formats
  3741. enum class input_format_t { json, cbor, msgpack, ubjson, bson };
  3742. ////////////////////
  3743. // input adapters //
  3744. ////////////////////
  3745. /*!
  3746. Input adapter for stdio file access. This adapter read only 1 byte and do not use any
  3747. buffer. This adapter is a very low level adapter.
  3748. */
  3749. class file_input_adapter
  3750. {
  3751. public:
  3752. JSON_HEDLEY_NON_NULL(2)
  3753. explicit file_input_adapter(std::FILE* f) noexcept
  3754. : m_file(f)
  3755. {}
  3756. // make class move-only
  3757. file_input_adapter(const file_input_adapter&) = delete;
  3758. file_input_adapter(file_input_adapter&&) = default;
  3759. file_input_adapter& operator=(const file_input_adapter&) = delete;
  3760. file_input_adapter& operator=(file_input_adapter&&) = delete;
  3761. std::char_traits<char>::int_type get_character() noexcept
  3762. {
  3763. return std::fgetc(m_file);
  3764. }
  3765. private:
  3766. /// the file pointer to read from
  3767. std::FILE* m_file;
  3768. };
  3769. /*!
  3770. Input adapter for a (caching) istream. Ignores a UFT Byte Order Mark at
  3771. beginning of input. Does not support changing the underlying std::streambuf
  3772. in mid-input. Maintains underlying std::istream and std::streambuf to support
  3773. subsequent use of standard std::istream operations to process any input
  3774. characters following those used in parsing the JSON input. Clears the
  3775. std::istream flags; any input errors (e.g., EOF) will be detected by the first
  3776. subsequent call for input from the std::istream.
  3777. */
  3778. class input_stream_adapter
  3779. {
  3780. public:
  3781. ~input_stream_adapter()
  3782. {
  3783. // clear stream flags; we use underlying streambuf I/O, do not
  3784. // maintain ifstream flags, except eof
  3785. if (is)
  3786. {
  3787. is->clear(is->rdstate() & std::ios::eofbit);
  3788. }
  3789. }
  3790. explicit input_stream_adapter(std::istream& i)
  3791. : is(&i), sb(i.rdbuf())
  3792. {}
  3793. // delete because of pointer members
  3794. input_stream_adapter(const input_stream_adapter&) = delete;
  3795. input_stream_adapter& operator=(input_stream_adapter&) = delete;
  3796. input_stream_adapter& operator=(input_stream_adapter&& rhs) = delete;
  3797. input_stream_adapter(input_stream_adapter&& rhs) : is(rhs.is), sb(rhs.sb)
  3798. {
  3799. rhs.is = nullptr;
  3800. rhs.sb = nullptr;
  3801. }
  3802. // std::istream/std::streambuf use std::char_traits<char>::to_int_type, to
  3803. // ensure that std::char_traits<char>::eof() and the character 0xFF do not
  3804. // end up as the same value, eg. 0xFFFFFFFF.
  3805. std::char_traits<char>::int_type get_character()
  3806. {
  3807. auto res = sb->sbumpc();
  3808. // set eof manually, as we don't use the istream interface.
  3809. if (res == EOF)
  3810. {
  3811. is->clear(is->rdstate() | std::ios::eofbit);
  3812. }
  3813. return res;
  3814. }
  3815. private:
  3816. /// the associated input stream
  3817. std::istream* is = nullptr;
  3818. std::streambuf* sb = nullptr;
  3819. };
  3820. /// input adapter for buffer input
  3821. class input_buffer_adapter
  3822. {
  3823. public:
  3824. input_buffer_adapter(const char* b, const std::size_t l) noexcept
  3825. : cursor(b), limit(b == nullptr ? nullptr : (b + l))
  3826. {}
  3827. // delete because of pointer members
  3828. input_buffer_adapter(const input_buffer_adapter&) = delete;
  3829. input_buffer_adapter& operator=(input_buffer_adapter&) = delete;
  3830. input_buffer_adapter(input_buffer_adapter&&) = default;
  3831. input_buffer_adapter& operator=(input_buffer_adapter&&) = delete;
  3832. std::char_traits<char>::int_type get_character() noexcept
  3833. {
  3834. if (JSON_HEDLEY_LIKELY(cursor < limit))
  3835. {
  3836. assert(cursor != nullptr and limit != nullptr);
  3837. return std::char_traits<char>::to_int_type(*(cursor++));
  3838. }
  3839. return std::char_traits<char>::eof();
  3840. }
  3841. private:
  3842. /// pointer to the current character
  3843. const char* cursor;
  3844. /// pointer past the last character
  3845. const char* const limit;
  3846. };
  3847. template<typename WideStringType, size_t T>
  3848. struct wide_string_input_helper
  3849. {
  3850. // UTF-32
  3851. static void fill_buffer(const WideStringType& str,
  3852. size_t& current_wchar,
  3853. std::array<std::char_traits<char>::int_type, 4>& utf8_bytes,
  3854. size_t& utf8_bytes_index,
  3855. size_t& utf8_bytes_filled)
  3856. {
  3857. utf8_bytes_index = 0;
  3858. if (current_wchar == str.size())
  3859. {
  3860. utf8_bytes[0] = std::char_traits<char>::eof();
  3861. utf8_bytes_filled = 1;
  3862. }
  3863. else
  3864. {
  3865. // get the current character
  3866. const auto wc = static_cast<unsigned int>(str[current_wchar++]);
  3867. // UTF-32 to UTF-8 encoding
  3868. if (wc < 0x80)
  3869. {
  3870. utf8_bytes[0] = static_cast<std::char_traits<char>::int_type>(wc);
  3871. utf8_bytes_filled = 1;
  3872. }
  3873. else if (wc <= 0x7FF)
  3874. {
  3875. utf8_bytes[0] = static_cast<std::char_traits<char>::int_type>(0xC0u | ((wc >> 6u) & 0x1Fu));
  3876. utf8_bytes[1] = static_cast<std::char_traits<char>::int_type>(0x80u | (wc & 0x3Fu));
  3877. utf8_bytes_filled = 2;
  3878. }
  3879. else if (wc <= 0xFFFF)
  3880. {
  3881. utf8_bytes[0] = static_cast<std::char_traits<char>::int_type>(0xE0u | ((wc >> 12u) & 0x0Fu));
  3882. utf8_bytes[1] = static_cast<std::char_traits<char>::int_type>(0x80u | ((wc >> 6u) & 0x3Fu));
  3883. utf8_bytes[2] = static_cast<std::char_traits<char>::int_type>(0x80u | (wc & 0x3Fu));
  3884. utf8_bytes_filled = 3;
  3885. }
  3886. else if (wc <= 0x10FFFF)
  3887. {
  3888. utf8_bytes[0] = static_cast<std::char_traits<char>::int_type>(0xF0u | ((wc >> 18u) & 0x07u));
  3889. utf8_bytes[1] = static_cast<std::char_traits<char>::int_type>(0x80u | ((wc >> 12u) & 0x3Fu));
  3890. utf8_bytes[2] = static_cast<std::char_traits<char>::int_type>(0x80u | ((wc >> 6u) & 0x3Fu));
  3891. utf8_bytes[3] = static_cast<std::char_traits<char>::int_type>(0x80u | (wc & 0x3Fu));
  3892. utf8_bytes_filled = 4;
  3893. }
  3894. else
  3895. {
  3896. // unknown character
  3897. utf8_bytes[0] = static_cast<std::char_traits<char>::int_type>(wc);
  3898. utf8_bytes_filled = 1;
  3899. }
  3900. }
  3901. }
  3902. };
  3903. template<typename WideStringType>
  3904. struct wide_string_input_helper<WideStringType, 2>
  3905. {
  3906. // UTF-16
  3907. static void fill_buffer(const WideStringType& str,
  3908. size_t& current_wchar,
  3909. std::array<std::char_traits<char>::int_type, 4>& utf8_bytes,
  3910. size_t& utf8_bytes_index,
  3911. size_t& utf8_bytes_filled)
  3912. {
  3913. utf8_bytes_index = 0;
  3914. if (current_wchar == str.size())
  3915. {
  3916. utf8_bytes[0] = std::char_traits<char>::eof();
  3917. utf8_bytes_filled = 1;
  3918. }
  3919. else
  3920. {
  3921. // get the current character
  3922. const auto wc = static_cast<unsigned int>(str[current_wchar++]);
  3923. // UTF-16 to UTF-8 encoding
  3924. if (wc < 0x80)
  3925. {
  3926. utf8_bytes[0] = static_cast<std::char_traits<char>::int_type>(wc);
  3927. utf8_bytes_filled = 1;
  3928. }
  3929. else if (wc <= 0x7FF)
  3930. {
  3931. utf8_bytes[0] = static_cast<std::char_traits<char>::int_type>(0xC0u | ((wc >> 6u)));
  3932. utf8_bytes[1] = static_cast<std::char_traits<char>::int_type>(0x80u | (wc & 0x3Fu));
  3933. utf8_bytes_filled = 2;
  3934. }
  3935. else if (0xD800 > wc or wc >= 0xE000)
  3936. {
  3937. utf8_bytes[0] = static_cast<std::char_traits<char>::int_type>(0xE0u | ((wc >> 12u)));
  3938. utf8_bytes[1] = static_cast<std::char_traits<char>::int_type>(0x80u | ((wc >> 6u) & 0x3Fu));
  3939. utf8_bytes[2] = static_cast<std::char_traits<char>::int_type>(0x80u | (wc & 0x3Fu));
  3940. utf8_bytes_filled = 3;
  3941. }
  3942. else
  3943. {
  3944. if (current_wchar < str.size())
  3945. {
  3946. const auto wc2 = static_cast<unsigned int>(str[current_wchar++]);
  3947. const auto charcode = 0x10000u + (((wc & 0x3FFu) << 10u) | (wc2 & 0x3FFu));
  3948. utf8_bytes[0] = static_cast<std::char_traits<char>::int_type>(0xF0u | (charcode >> 18u));
  3949. utf8_bytes[1] = static_cast<std::char_traits<char>::int_type>(0x80u | ((charcode >> 12u) & 0x3Fu));
  3950. utf8_bytes[2] = static_cast<std::char_traits<char>::int_type>(0x80u | ((charcode >> 6u) & 0x3Fu));
  3951. utf8_bytes[3] = static_cast<std::char_traits<char>::int_type>(0x80u | (charcode & 0x3Fu));
  3952. utf8_bytes_filled = 4;
  3953. }
  3954. else
  3955. {
  3956. // unknown character
  3957. ++current_wchar;
  3958. utf8_bytes[0] = static_cast<std::char_traits<char>::int_type>(wc);
  3959. utf8_bytes_filled = 1;
  3960. }
  3961. }
  3962. }
  3963. }
  3964. };
  3965. template<typename WideStringType>
  3966. class wide_string_input_adapter
  3967. {
  3968. public:
  3969. explicit wide_string_input_adapter(const WideStringType& w) noexcept
  3970. : str(w)
  3971. {}
  3972. std::char_traits<char>::int_type get_character() noexcept
  3973. {
  3974. // check if buffer needs to be filled
  3975. if (utf8_bytes_index == utf8_bytes_filled)
  3976. {
  3977. fill_buffer<sizeof(typename WideStringType::value_type)>();
  3978. assert(utf8_bytes_filled > 0);
  3979. assert(utf8_bytes_index == 0);
  3980. }
  3981. // use buffer
  3982. assert(utf8_bytes_filled > 0);
  3983. assert(utf8_bytes_index < utf8_bytes_filled);
  3984. return utf8_bytes[utf8_bytes_index++];
  3985. }
  3986. private:
  3987. template<size_t T>
  3988. void fill_buffer()
  3989. {
  3990. wide_string_input_helper<WideStringType, T>::fill_buffer(str, current_wchar, utf8_bytes, utf8_bytes_index, utf8_bytes_filled);
  3991. }
  3992. /// the wstring to process
  3993. const WideStringType& str;
  3994. /// index of the current wchar in str
  3995. std::size_t current_wchar = 0;
  3996. /// a buffer for UTF-8 bytes
  3997. std::array<std::char_traits<char>::int_type, 4> utf8_bytes = {{0, 0, 0, 0}};
  3998. /// index to the utf8_codes array for the next valid byte
  3999. std::size_t utf8_bytes_index = 0;
  4000. /// number of valid bytes in the utf8_codes array
  4001. std::size_t utf8_bytes_filled = 0;
  4002. };
  4003. inline file_input_adapter input_adapter(std::FILE* file)
  4004. {
  4005. return file_input_adapter(file);
  4006. }
  4007. inline input_stream_adapter input_adapter(std::istream& stream)
  4008. {
  4009. return input_stream_adapter(stream);
  4010. }
  4011. inline input_stream_adapter input_adapter(std::istream&& stream)
  4012. {
  4013. return input_stream_adapter(stream);
  4014. }
  4015. template<typename CharT,
  4016. typename std::enable_if<
  4017. std::is_pointer<CharT>::value and
  4018. std::is_integral<typename std::remove_pointer<CharT>::type>::value and
  4019. sizeof(typename std::remove_pointer<CharT>::type) == 1,
  4020. int>::type = 0>
  4021. input_buffer_adapter input_adapter(CharT b, std::size_t l)
  4022. {
  4023. return input_buffer_adapter(reinterpret_cast<const char*>(b), l);
  4024. }
  4025. template<typename CharT,
  4026. typename std::enable_if<
  4027. std::is_pointer<CharT>::value and
  4028. std::is_integral<typename std::remove_pointer<CharT>::type>::value and
  4029. sizeof(typename std::remove_pointer<CharT>::type) == 1,
  4030. int>::type = 0>
  4031. input_buffer_adapter input_adapter(CharT b)
  4032. {
  4033. return input_adapter(reinterpret_cast<const char*>(b),
  4034. std::strlen(reinterpret_cast<const char*>(b)));
  4035. }
  4036. template<class IteratorType,
  4037. typename std::enable_if<
  4038. std::is_same<typename iterator_traits<IteratorType>::iterator_category, std::random_access_iterator_tag>::value,
  4039. int>::type = 0>
  4040. input_buffer_adapter input_adapter(IteratorType first, IteratorType last)
  4041. {
  4042. #ifndef NDEBUG
  4043. // assertion to check that the iterator range is indeed contiguous,
  4044. // see https://stackoverflow.com/a/35008842/266378 for more discussion
  4045. const auto is_contiguous = std::accumulate(
  4046. first, last, std::pair<bool, int>(true, 0),
  4047. [&first](std::pair<bool, int> res, decltype(*first) val)
  4048. {
  4049. res.first &= (val == *(std::next(std::addressof(*first), res.second++)));
  4050. return res;
  4051. }).first;
  4052. assert(is_contiguous);
  4053. #endif
  4054. // assertion to check that each element is 1 byte long
  4055. static_assert(
  4056. sizeof(typename iterator_traits<IteratorType>::value_type) == 1,
  4057. "each element in the iterator range must have the size of 1 byte");
  4058. const auto len = static_cast<size_t>(std::distance(first, last));
  4059. if (JSON_HEDLEY_LIKELY(len > 0))
  4060. {
  4061. // there is at least one element: use the address of first
  4062. return input_buffer_adapter(reinterpret_cast<const char*>(&(*first)), len);
  4063. }
  4064. else
  4065. {
  4066. // the address of first cannot be used: use nullptr
  4067. return input_buffer_adapter(nullptr, len);
  4068. }
  4069. }
  4070. inline wide_string_input_adapter<std::wstring> input_adapter(const std::wstring& ws)
  4071. {
  4072. return wide_string_input_adapter<std::wstring>(ws);
  4073. }
  4074. inline wide_string_input_adapter<std::u16string> input_adapter(const std::u16string& ws)
  4075. {
  4076. return wide_string_input_adapter<std::u16string>(ws);
  4077. }
  4078. inline wide_string_input_adapter<std::u32string> input_adapter(const std::u32string& ws)
  4079. {
  4080. return wide_string_input_adapter<std::u32string>(ws);
  4081. }
  4082. template<class ContiguousContainer, typename
  4083. std::enable_if<not std::is_pointer<ContiguousContainer>::value and
  4084. std::is_base_of<std::random_access_iterator_tag, typename iterator_traits<decltype(std::begin(std::declval<ContiguousContainer const>()))>::iterator_category>::value,
  4085. int>::type = 0>
  4086. input_buffer_adapter input_adapter(const ContiguousContainer& c)
  4087. {
  4088. return input_adapter(std::begin(c), std::end(c));
  4089. }
  4090. template<class T, std::size_t N>
  4091. input_buffer_adapter input_adapter(T (&array)[N])
  4092. {
  4093. return input_adapter(std::begin(array), std::end(array));
  4094. }
  4095. // This class only handles inputs of input_buffer_adapter type.
  4096. // It's required so that expressions like {ptr, len} can be implicitely casted
  4097. // to the correct adapter.
  4098. class span_input_adapter
  4099. {
  4100. public:
  4101. template<typename CharT,
  4102. typename std::enable_if<
  4103. std::is_pointer<CharT>::value and
  4104. std::is_integral<typename std::remove_pointer<CharT>::type>::value and
  4105. sizeof(typename std::remove_pointer<CharT>::type) == 1,
  4106. int>::type = 0>
  4107. span_input_adapter(CharT b, std::size_t l)
  4108. : ia(reinterpret_cast<const char*>(b), l) {}
  4109. template<typename CharT,
  4110. typename std::enable_if<
  4111. std::is_pointer<CharT>::value and
  4112. std::is_integral<typename std::remove_pointer<CharT>::type>::value and
  4113. sizeof(typename std::remove_pointer<CharT>::type) == 1,
  4114. int>::type = 0>
  4115. span_input_adapter(CharT b)
  4116. : span_input_adapter(reinterpret_cast<const char*>(b),
  4117. std::strlen(reinterpret_cast<const char*>(b))) {}
  4118. template<class IteratorType,
  4119. typename std::enable_if<
  4120. std::is_same<typename iterator_traits<IteratorType>::iterator_category, std::random_access_iterator_tag>::value,
  4121. int>::type = 0>
  4122. span_input_adapter(IteratorType first, IteratorType last)
  4123. : ia(input_adapter(first, last)) {}
  4124. template<class T, std::size_t N>
  4125. span_input_adapter(T (&array)[N])
  4126. : span_input_adapter(std::begin(array), std::end(array)) {}
  4127. /// input adapter for contiguous container
  4128. template<class ContiguousContainer, typename
  4129. std::enable_if<not std::is_pointer<ContiguousContainer>::value and
  4130. std::is_base_of<std::random_access_iterator_tag, typename iterator_traits<decltype(std::begin(std::declval<ContiguousContainer const>()))>::iterator_category>::value,
  4131. int>::type = 0>
  4132. span_input_adapter(const ContiguousContainer& c)
  4133. : span_input_adapter(std::begin(c), std::end(c)) {}
  4134. input_buffer_adapter&& get()
  4135. {
  4136. return std::move(ia);
  4137. }
  4138. private:
  4139. input_buffer_adapter ia;
  4140. };
  4141. } // namespace detail
  4142. } // namespace nlohmann
  4143. // #include <nlohmann/detail/input/json_sax.hpp>
  4144. #include <cassert> // assert
  4145. #include <cstddef>
  4146. #include <string> // string
  4147. #include <utility> // move
  4148. #include <vector> // vector
  4149. // #include <nlohmann/detail/exceptions.hpp>
  4150. // #include <nlohmann/detail/macro_scope.hpp>
  4151. namespace nlohmann
  4152. {
  4153. /*!
  4154. @brief SAX interface
  4155. This class describes the SAX interface used by @ref nlohmann::json::sax_parse.
  4156. Each function is called in different situations while the input is parsed. The
  4157. boolean return value informs the parser whether to continue processing the
  4158. input.
  4159. */
  4160. template<typename BasicJsonType>
  4161. struct json_sax
  4162. {
  4163. /// type for (signed) integers
  4164. using number_integer_t = typename BasicJsonType::number_integer_t;
  4165. /// type for unsigned integers
  4166. using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
  4167. /// type for floating-point numbers
  4168. using number_float_t = typename BasicJsonType::number_float_t;
  4169. /// type for strings
  4170. using string_t = typename BasicJsonType::string_t;
  4171. using binary_t = typename BasicJsonType::binary_t;
  4172. /*!
  4173. @brief a null value was read
  4174. @return whether parsing should proceed
  4175. */
  4176. virtual bool null() = 0;
  4177. /*!
  4178. @brief a boolean value was read
  4179. @param[in] val boolean value
  4180. @return whether parsing should proceed
  4181. */
  4182. virtual bool boolean(bool val) = 0;
  4183. /*!
  4184. @brief an integer number was read
  4185. @param[in] val integer value
  4186. @return whether parsing should proceed
  4187. */
  4188. virtual bool number_integer(number_integer_t val) = 0;
  4189. /*!
  4190. @brief an unsigned integer number was read
  4191. @param[in] val unsigned integer value
  4192. @return whether parsing should proceed
  4193. */
  4194. virtual bool number_unsigned(number_unsigned_t val) = 0;
  4195. /*!
  4196. @brief an floating-point number was read
  4197. @param[in] val floating-point value
  4198. @param[in] s raw token value
  4199. @return whether parsing should proceed
  4200. */
  4201. virtual bool number_float(number_float_t val, const string_t& s) = 0;
  4202. /*!
  4203. @brief a string was read
  4204. @param[in] val string value
  4205. @return whether parsing should proceed
  4206. @note It is safe to move the passed string.
  4207. */
  4208. virtual bool string(string_t& val) = 0;
  4209. /*!
  4210. @brief a binary string was read
  4211. @param[in] val binary value
  4212. @return whether parsing should proceed
  4213. @note It is safe to move the passed binary.
  4214. */
  4215. virtual bool binary(binary_t& val) = 0;
  4216. /*!
  4217. @brief the beginning of an object was read
  4218. @param[in] elements number of object elements or -1 if unknown
  4219. @return whether parsing should proceed
  4220. @note binary formats may report the number of elements
  4221. */
  4222. virtual bool start_object(std::size_t elements) = 0;
  4223. /*!
  4224. @brief an object key was read
  4225. @param[in] val object key
  4226. @return whether parsing should proceed
  4227. @note It is safe to move the passed string.
  4228. */
  4229. virtual bool key(string_t& val) = 0;
  4230. /*!
  4231. @brief the end of an object was read
  4232. @return whether parsing should proceed
  4233. */
  4234. virtual bool end_object() = 0;
  4235. /*!
  4236. @brief the beginning of an array was read
  4237. @param[in] elements number of array elements or -1 if unknown
  4238. @return whether parsing should proceed
  4239. @note binary formats may report the number of elements
  4240. */
  4241. virtual bool start_array(std::size_t elements) = 0;
  4242. /*!
  4243. @brief the end of an array was read
  4244. @return whether parsing should proceed
  4245. */
  4246. virtual bool end_array() = 0;
  4247. /*!
  4248. @brief a parse error occurred
  4249. @param[in] position the position in the input where the error occurs
  4250. @param[in] last_token the last read token
  4251. @param[in] ex an exception object describing the error
  4252. @return whether parsing should proceed (must return false)
  4253. */
  4254. virtual bool parse_error(std::size_t position,
  4255. const std::string& last_token,
  4256. const detail::exception& ex) = 0;
  4257. virtual ~json_sax() = default;
  4258. };
  4259. namespace detail
  4260. {
  4261. /*!
  4262. @brief SAX implementation to create a JSON value from SAX events
  4263. This class implements the @ref json_sax interface and processes the SAX events
  4264. to create a JSON value which makes it basically a DOM parser. The structure or
  4265. hierarchy of the JSON value is managed by the stack `ref_stack` which contains
  4266. a pointer to the respective array or object for each recursion depth.
  4267. After successful parsing, the value that is passed by reference to the
  4268. constructor contains the parsed value.
  4269. @tparam BasicJsonType the JSON type
  4270. */
  4271. template<typename BasicJsonType>
  4272. class json_sax_dom_parser
  4273. {
  4274. public:
  4275. using number_integer_t = typename BasicJsonType::number_integer_t;
  4276. using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
  4277. using number_float_t = typename BasicJsonType::number_float_t;
  4278. using string_t = typename BasicJsonType::string_t;
  4279. using binary_t = typename BasicJsonType::binary_t;
  4280. /*!
  4281. @param[in, out] r reference to a JSON value that is manipulated while
  4282. parsing
  4283. @param[in] allow_exceptions_ whether parse errors yield exceptions
  4284. */
  4285. explicit json_sax_dom_parser(BasicJsonType& r, const bool allow_exceptions_ = true)
  4286. : root(r), allow_exceptions(allow_exceptions_)
  4287. {}
  4288. // make class move-only
  4289. json_sax_dom_parser(const json_sax_dom_parser&) = delete;
  4290. json_sax_dom_parser(json_sax_dom_parser&&) = default;
  4291. json_sax_dom_parser& operator=(const json_sax_dom_parser&) = delete;
  4292. json_sax_dom_parser& operator=(json_sax_dom_parser&&) = default;
  4293. ~json_sax_dom_parser() = default;
  4294. bool null()
  4295. {
  4296. handle_value(nullptr);
  4297. return true;
  4298. }
  4299. bool boolean(bool val)
  4300. {
  4301. handle_value(val);
  4302. return true;
  4303. }
  4304. bool number_integer(number_integer_t val)
  4305. {
  4306. handle_value(val);
  4307. return true;
  4308. }
  4309. bool number_unsigned(number_unsigned_t val)
  4310. {
  4311. handle_value(val);
  4312. return true;
  4313. }
  4314. bool number_float(number_float_t val, const string_t& /*unused*/)
  4315. {
  4316. handle_value(val);
  4317. return true;
  4318. }
  4319. bool string(string_t& val)
  4320. {
  4321. handle_value(val);
  4322. return true;
  4323. }
  4324. bool binary(binary_t& val)
  4325. {
  4326. handle_value(BasicJsonType::binary_array(std::move(val)));
  4327. return true;
  4328. }
  4329. bool start_object(std::size_t len)
  4330. {
  4331. ref_stack.push_back(handle_value(BasicJsonType::value_t::object));
  4332. if (JSON_HEDLEY_UNLIKELY(len != std::size_t(-1) and len > ref_stack.back()->max_size()))
  4333. {
  4334. JSON_THROW(out_of_range::create(408,
  4335. "excessive object size: " + std::to_string(len)));
  4336. }
  4337. return true;
  4338. }
  4339. bool key(string_t& val)
  4340. {
  4341. // add null at given key and store the reference for later
  4342. object_element = &(ref_stack.back()->m_value.object->operator[](val));
  4343. return true;
  4344. }
  4345. bool end_object()
  4346. {
  4347. ref_stack.pop_back();
  4348. return true;
  4349. }
  4350. bool start_array(std::size_t len)
  4351. {
  4352. ref_stack.push_back(handle_value(BasicJsonType::value_t::array));
  4353. if (JSON_HEDLEY_UNLIKELY(len != std::size_t(-1) and len > ref_stack.back()->max_size()))
  4354. {
  4355. JSON_THROW(out_of_range::create(408,
  4356. "excessive array size: " + std::to_string(len)));
  4357. }
  4358. return true;
  4359. }
  4360. bool end_array()
  4361. {
  4362. ref_stack.pop_back();
  4363. return true;
  4364. }
  4365. bool parse_error(std::size_t /*unused*/, const std::string& /*unused*/,
  4366. const detail::exception& ex)
  4367. {
  4368. errored = true;
  4369. if (allow_exceptions)
  4370. {
  4371. // determine the proper exception type from the id
  4372. switch ((ex.id / 100) % 100)
  4373. {
  4374. case 1:
  4375. JSON_THROW(*static_cast<const detail::parse_error*>(&ex));
  4376. case 4:
  4377. JSON_THROW(*static_cast<const detail::out_of_range*>(&ex));
  4378. // LCOV_EXCL_START
  4379. case 2:
  4380. JSON_THROW(*static_cast<const detail::invalid_iterator*>(&ex));
  4381. case 3:
  4382. JSON_THROW(*static_cast<const detail::type_error*>(&ex));
  4383. case 5:
  4384. JSON_THROW(*static_cast<const detail::other_error*>(&ex));
  4385. default:
  4386. assert(false);
  4387. // LCOV_EXCL_STOP
  4388. }
  4389. }
  4390. return false;
  4391. }
  4392. constexpr bool is_errored() const
  4393. {
  4394. return errored;
  4395. }
  4396. private:
  4397. /*!
  4398. @invariant If the ref stack is empty, then the passed value will be the new
  4399. root.
  4400. @invariant If the ref stack contains a value, then it is an array or an
  4401. object to which we can add elements
  4402. */
  4403. template<typename Value>
  4404. JSON_HEDLEY_RETURNS_NON_NULL
  4405. BasicJsonType* handle_value(Value&& v)
  4406. {
  4407. if (ref_stack.empty())
  4408. {
  4409. root = BasicJsonType(std::forward<Value>(v));
  4410. return &root;
  4411. }
  4412. assert(ref_stack.back()->is_array() or ref_stack.back()->is_object());
  4413. if (ref_stack.back()->is_array())
  4414. {
  4415. ref_stack.back()->m_value.array->emplace_back(std::forward<Value>(v));
  4416. return &(ref_stack.back()->m_value.array->back());
  4417. }
  4418. assert(ref_stack.back()->is_object());
  4419. assert(object_element);
  4420. *object_element = BasicJsonType(std::forward<Value>(v));
  4421. return object_element;
  4422. }
  4423. /// the parsed JSON value
  4424. BasicJsonType& root;
  4425. /// stack to model hierarchy of values
  4426. std::vector<BasicJsonType*> ref_stack {};
  4427. /// helper to hold the reference for the next object element
  4428. BasicJsonType* object_element = nullptr;
  4429. /// whether a syntax error occurred
  4430. bool errored = false;
  4431. /// whether to throw exceptions in case of errors
  4432. const bool allow_exceptions = true;
  4433. };
  4434. template<typename BasicJsonType>
  4435. class json_sax_dom_callback_parser
  4436. {
  4437. public:
  4438. using number_integer_t = typename BasicJsonType::number_integer_t;
  4439. using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
  4440. using number_float_t = typename BasicJsonType::number_float_t;
  4441. using string_t = typename BasicJsonType::string_t;
  4442. using binary_t = typename BasicJsonType::binary_t;
  4443. using parser_callback_t = typename BasicJsonType::parser_callback_t;
  4444. using parse_event_t = typename BasicJsonType::parse_event_t;
  4445. json_sax_dom_callback_parser(BasicJsonType& r,
  4446. const parser_callback_t cb,
  4447. const bool allow_exceptions_ = true)
  4448. : root(r), callback(cb), allow_exceptions(allow_exceptions_)
  4449. {
  4450. keep_stack.push_back(true);
  4451. }
  4452. // make class move-only
  4453. json_sax_dom_callback_parser(const json_sax_dom_callback_parser&) = delete;
  4454. json_sax_dom_callback_parser(json_sax_dom_callback_parser&&) = default;
  4455. json_sax_dom_callback_parser& operator=(const json_sax_dom_callback_parser&) = delete;
  4456. json_sax_dom_callback_parser& operator=(json_sax_dom_callback_parser&&) = default;
  4457. ~json_sax_dom_callback_parser() = default;
  4458. bool null()
  4459. {
  4460. handle_value(nullptr);
  4461. return true;
  4462. }
  4463. bool boolean(bool val)
  4464. {
  4465. handle_value(val);
  4466. return true;
  4467. }
  4468. bool number_integer(number_integer_t val)
  4469. {
  4470. handle_value(val);
  4471. return true;
  4472. }
  4473. bool number_unsigned(number_unsigned_t val)
  4474. {
  4475. handle_value(val);
  4476. return true;
  4477. }
  4478. bool number_float(number_float_t val, const string_t& /*unused*/)
  4479. {
  4480. handle_value(val);
  4481. return true;
  4482. }
  4483. bool string(string_t& val)
  4484. {
  4485. handle_value(val);
  4486. return true;
  4487. }
  4488. bool binary(binary_t& val)
  4489. {
  4490. handle_value(BasicJsonType::binary_array(val));
  4491. return true;
  4492. }
  4493. bool start_object(std::size_t len)
  4494. {
  4495. // check callback for object start
  4496. const bool keep = callback(static_cast<int>(ref_stack.size()), parse_event_t::object_start, discarded);
  4497. keep_stack.push_back(keep);
  4498. auto val = handle_value(BasicJsonType::value_t::object, true);
  4499. ref_stack.push_back(val.second);
  4500. // check object limit
  4501. if (ref_stack.back() and JSON_HEDLEY_UNLIKELY(len != std::size_t(-1) and len > ref_stack.back()->max_size()))
  4502. {
  4503. JSON_THROW(out_of_range::create(408, "excessive object size: " + std::to_string(len)));
  4504. }
  4505. return true;
  4506. }
  4507. bool key(string_t& val)
  4508. {
  4509. BasicJsonType k = BasicJsonType(val);
  4510. // check callback for key
  4511. const bool keep = callback(static_cast<int>(ref_stack.size()), parse_event_t::key, k);
  4512. key_keep_stack.push_back(keep);
  4513. // add discarded value at given key and store the reference for later
  4514. if (keep and ref_stack.back())
  4515. {
  4516. object_element = &(ref_stack.back()->m_value.object->operator[](val) = discarded);
  4517. }
  4518. return true;
  4519. }
  4520. bool end_object()
  4521. {
  4522. if (ref_stack.back() and not callback(static_cast<int>(ref_stack.size()) - 1, parse_event_t::object_end, *ref_stack.back()))
  4523. {
  4524. // discard object
  4525. *ref_stack.back() = discarded;
  4526. }
  4527. assert(not ref_stack.empty());
  4528. assert(not keep_stack.empty());
  4529. ref_stack.pop_back();
  4530. keep_stack.pop_back();
  4531. if (not ref_stack.empty() and ref_stack.back() and ref_stack.back()->is_object())
  4532. {
  4533. // remove discarded value
  4534. for (auto it = ref_stack.back()->begin(); it != ref_stack.back()->end(); ++it)
  4535. {
  4536. if (it->is_discarded())
  4537. {
  4538. ref_stack.back()->erase(it);
  4539. break;
  4540. }
  4541. }
  4542. }
  4543. return true;
  4544. }
  4545. bool start_array(std::size_t len)
  4546. {
  4547. const bool keep = callback(static_cast<int>(ref_stack.size()), parse_event_t::array_start, discarded);
  4548. keep_stack.push_back(keep);
  4549. auto val = handle_value(BasicJsonType::value_t::array, true);
  4550. ref_stack.push_back(val.second);
  4551. // check array limit
  4552. if (ref_stack.back() and JSON_HEDLEY_UNLIKELY(len != std::size_t(-1) and len > ref_stack.back()->max_size()))
  4553. {
  4554. JSON_THROW(out_of_range::create(408, "excessive array size: " + std::to_string(len)));
  4555. }
  4556. return true;
  4557. }
  4558. bool end_array()
  4559. {
  4560. bool keep = true;
  4561. if (ref_stack.back())
  4562. {
  4563. keep = callback(static_cast<int>(ref_stack.size()) - 1, parse_event_t::array_end, *ref_stack.back());
  4564. if (not keep)
  4565. {
  4566. // discard array
  4567. *ref_stack.back() = discarded;
  4568. }
  4569. }
  4570. assert(not ref_stack.empty());
  4571. assert(not keep_stack.empty());
  4572. ref_stack.pop_back();
  4573. keep_stack.pop_back();
  4574. // remove discarded value
  4575. if (not keep and not ref_stack.empty() and ref_stack.back()->is_array())
  4576. {
  4577. ref_stack.back()->m_value.array->pop_back();
  4578. }
  4579. return true;
  4580. }
  4581. bool parse_error(std::size_t /*unused*/, const std::string& /*unused*/,
  4582. const detail::exception& ex)
  4583. {
  4584. errored = true;
  4585. if (allow_exceptions)
  4586. {
  4587. // determine the proper exception type from the id
  4588. switch ((ex.id / 100) % 100)
  4589. {
  4590. case 1:
  4591. JSON_THROW(*static_cast<const detail::parse_error*>(&ex));
  4592. case 4:
  4593. JSON_THROW(*static_cast<const detail::out_of_range*>(&ex));
  4594. // LCOV_EXCL_START
  4595. case 2:
  4596. JSON_THROW(*static_cast<const detail::invalid_iterator*>(&ex));
  4597. case 3:
  4598. JSON_THROW(*static_cast<const detail::type_error*>(&ex));
  4599. case 5:
  4600. JSON_THROW(*static_cast<const detail::other_error*>(&ex));
  4601. default:
  4602. assert(false);
  4603. // LCOV_EXCL_STOP
  4604. }
  4605. }
  4606. return false;
  4607. }
  4608. constexpr bool is_errored() const
  4609. {
  4610. return errored;
  4611. }
  4612. private:
  4613. /*!
  4614. @param[in] v value to add to the JSON value we build during parsing
  4615. @param[in] skip_callback whether we should skip calling the callback
  4616. function; this is required after start_array() and
  4617. start_object() SAX events, because otherwise we would call the
  4618. callback function with an empty array or object, respectively.
  4619. @invariant If the ref stack is empty, then the passed value will be the new
  4620. root.
  4621. @invariant If the ref stack contains a value, then it is an array or an
  4622. object to which we can add elements
  4623. @return pair of boolean (whether value should be kept) and pointer (to the
  4624. passed value in the ref_stack hierarchy; nullptr if not kept)
  4625. */
  4626. template<typename Value>
  4627. std::pair<bool, BasicJsonType*> handle_value(Value&& v, const bool skip_callback = false)
  4628. {
  4629. assert(not keep_stack.empty());
  4630. // do not handle this value if we know it would be added to a discarded
  4631. // container
  4632. if (not keep_stack.back())
  4633. {
  4634. return {false, nullptr};
  4635. }
  4636. // create value
  4637. auto value = BasicJsonType(std::forward<Value>(v));
  4638. // check callback
  4639. const bool keep = skip_callback or callback(static_cast<int>(ref_stack.size()), parse_event_t::value, value);
  4640. // do not handle this value if we just learnt it shall be discarded
  4641. if (not keep)
  4642. {
  4643. return {false, nullptr};
  4644. }
  4645. if (ref_stack.empty())
  4646. {
  4647. root = std::move(value);
  4648. return {true, &root};
  4649. }
  4650. // skip this value if we already decided to skip the parent
  4651. // (https://github.com/nlohmann/json/issues/971#issuecomment-413678360)
  4652. if (not ref_stack.back())
  4653. {
  4654. return {false, nullptr};
  4655. }
  4656. // we now only expect arrays and objects
  4657. assert(ref_stack.back()->is_array() or ref_stack.back()->is_object());
  4658. // array
  4659. if (ref_stack.back()->is_array())
  4660. {
  4661. ref_stack.back()->m_value.array->push_back(std::move(value));
  4662. return {true, &(ref_stack.back()->m_value.array->back())};
  4663. }
  4664. // object
  4665. assert(ref_stack.back()->is_object());
  4666. // check if we should store an element for the current key
  4667. assert(not key_keep_stack.empty());
  4668. const bool store_element = key_keep_stack.back();
  4669. key_keep_stack.pop_back();
  4670. if (not store_element)
  4671. {
  4672. return {false, nullptr};
  4673. }
  4674. assert(object_element);
  4675. *object_element = std::move(value);
  4676. return {true, object_element};
  4677. }
  4678. /// the parsed JSON value
  4679. BasicJsonType& root;
  4680. /// stack to model hierarchy of values
  4681. std::vector<BasicJsonType*> ref_stack {};
  4682. /// stack to manage which values to keep
  4683. std::vector<bool> keep_stack {};
  4684. /// stack to manage which object keys to keep
  4685. std::vector<bool> key_keep_stack {};
  4686. /// helper to hold the reference for the next object element
  4687. BasicJsonType* object_element = nullptr;
  4688. /// whether a syntax error occurred
  4689. bool errored = false;
  4690. /// callback function
  4691. const parser_callback_t callback = nullptr;
  4692. /// whether to throw exceptions in case of errors
  4693. const bool allow_exceptions = true;
  4694. /// a discarded value for the callback
  4695. BasicJsonType discarded = BasicJsonType::value_t::discarded;
  4696. };
  4697. template<typename BasicJsonType>
  4698. class json_sax_acceptor
  4699. {
  4700. public:
  4701. using number_integer_t = typename BasicJsonType::number_integer_t;
  4702. using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
  4703. using number_float_t = typename BasicJsonType::number_float_t;
  4704. using string_t = typename BasicJsonType::string_t;
  4705. using binary_t = typename BasicJsonType::binary_t;
  4706. bool null()
  4707. {
  4708. return true;
  4709. }
  4710. bool boolean(bool /*unused*/)
  4711. {
  4712. return true;
  4713. }
  4714. bool number_integer(number_integer_t /*unused*/)
  4715. {
  4716. return true;
  4717. }
  4718. bool number_unsigned(number_unsigned_t /*unused*/)
  4719. {
  4720. return true;
  4721. }
  4722. bool number_float(number_float_t /*unused*/, const string_t& /*unused*/)
  4723. {
  4724. return true;
  4725. }
  4726. bool string(string_t& /*unused*/)
  4727. {
  4728. return true;
  4729. }
  4730. bool binary(binary_t& /*unused*/)
  4731. {
  4732. return true;
  4733. }
  4734. bool start_object(std::size_t /*unused*/ = std::size_t(-1))
  4735. {
  4736. return true;
  4737. }
  4738. bool key(string_t& /*unused*/)
  4739. {
  4740. return true;
  4741. }
  4742. bool end_object()
  4743. {
  4744. return true;
  4745. }
  4746. bool start_array(std::size_t /*unused*/ = std::size_t(-1))
  4747. {
  4748. return true;
  4749. }
  4750. bool end_array()
  4751. {
  4752. return true;
  4753. }
  4754. bool parse_error(std::size_t /*unused*/, const std::string& /*unused*/, const detail::exception& /*unused*/)
  4755. {
  4756. return false;
  4757. }
  4758. };
  4759. } // namespace detail
  4760. } // namespace nlohmann
  4761. // #include <nlohmann/detail/macro_scope.hpp>
  4762. // #include <nlohmann/detail/meta/is_sax.hpp>
  4763. #include <cstdint> // size_t
  4764. #include <utility> // declval
  4765. #include <string> // string
  4766. // #include <nlohmann/detail/meta/detected.hpp>
  4767. // #include <nlohmann/detail/meta/type_traits.hpp>
  4768. namespace nlohmann
  4769. {
  4770. namespace detail
  4771. {
  4772. template <typename T>
  4773. using null_function_t = decltype(std::declval<T&>().null());
  4774. template <typename T>
  4775. using boolean_function_t =
  4776. decltype(std::declval<T&>().boolean(std::declval<bool>()));
  4777. template <typename T, typename Integer>
  4778. using number_integer_function_t =
  4779. decltype(std::declval<T&>().number_integer(std::declval<Integer>()));
  4780. template <typename T, typename Unsigned>
  4781. using number_unsigned_function_t =
  4782. decltype(std::declval<T&>().number_unsigned(std::declval<Unsigned>()));
  4783. template <typename T, typename Float, typename String>
  4784. using number_float_function_t = decltype(std::declval<T&>().number_float(
  4785. std::declval<Float>(), std::declval<const String&>()));
  4786. template <typename T, typename String>
  4787. using string_function_t =
  4788. decltype(std::declval<T&>().string(std::declval<String&>()));
  4789. template <typename T>
  4790. using start_object_function_t =
  4791. decltype(std::declval<T&>().start_object(std::declval<std::size_t>()));
  4792. template <typename T, typename String>
  4793. using key_function_t =
  4794. decltype(std::declval<T&>().key(std::declval<String&>()));
  4795. template <typename T>
  4796. using end_object_function_t = decltype(std::declval<T&>().end_object());
  4797. template <typename T>
  4798. using start_array_function_t =
  4799. decltype(std::declval<T&>().start_array(std::declval<std::size_t>()));
  4800. template <typename T>
  4801. using end_array_function_t = decltype(std::declval<T&>().end_array());
  4802. template <typename T, typename Exception>
  4803. using parse_error_function_t = decltype(std::declval<T&>().parse_error(
  4804. std::declval<std::size_t>(), std::declval<const std::string&>(),
  4805. std::declval<const Exception&>()));
  4806. template <typename SAX, typename BasicJsonType>
  4807. struct is_sax
  4808. {
  4809. private:
  4810. static_assert(is_basic_json<BasicJsonType>::value,
  4811. "BasicJsonType must be of type basic_json<...>");
  4812. using number_integer_t = typename BasicJsonType::number_integer_t;
  4813. using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
  4814. using number_float_t = typename BasicJsonType::number_float_t;
  4815. using string_t = typename BasicJsonType::string_t;
  4816. using exception_t = typename BasicJsonType::exception;
  4817. public:
  4818. static constexpr bool value =
  4819. is_detected_exact<bool, null_function_t, SAX>::value &&
  4820. is_detected_exact<bool, boolean_function_t, SAX>::value &&
  4821. is_detected_exact<bool, number_integer_function_t, SAX,
  4822. number_integer_t>::value &&
  4823. is_detected_exact<bool, number_unsigned_function_t, SAX,
  4824. number_unsigned_t>::value &&
  4825. is_detected_exact<bool, number_float_function_t, SAX, number_float_t,
  4826. string_t>::value &&
  4827. is_detected_exact<bool, string_function_t, SAX, string_t>::value &&
  4828. is_detected_exact<bool, start_object_function_t, SAX>::value &&
  4829. is_detected_exact<bool, key_function_t, SAX, string_t>::value &&
  4830. is_detected_exact<bool, end_object_function_t, SAX>::value &&
  4831. is_detected_exact<bool, start_array_function_t, SAX>::value &&
  4832. is_detected_exact<bool, end_array_function_t, SAX>::value &&
  4833. is_detected_exact<bool, parse_error_function_t, SAX, exception_t>::value;
  4834. };
  4835. template <typename SAX, typename BasicJsonType>
  4836. struct is_sax_static_asserts
  4837. {
  4838. private:
  4839. static_assert(is_basic_json<BasicJsonType>::value,
  4840. "BasicJsonType must be of type basic_json<...>");
  4841. using number_integer_t = typename BasicJsonType::number_integer_t;
  4842. using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
  4843. using number_float_t = typename BasicJsonType::number_float_t;
  4844. using string_t = typename BasicJsonType::string_t;
  4845. using exception_t = typename BasicJsonType::exception;
  4846. public:
  4847. static_assert(is_detected_exact<bool, null_function_t, SAX>::value,
  4848. "Missing/invalid function: bool null()");
  4849. static_assert(is_detected_exact<bool, boolean_function_t, SAX>::value,
  4850. "Missing/invalid function: bool boolean(bool)");
  4851. static_assert(is_detected_exact<bool, boolean_function_t, SAX>::value,
  4852. "Missing/invalid function: bool boolean(bool)");
  4853. static_assert(
  4854. is_detected_exact<bool, number_integer_function_t, SAX,
  4855. number_integer_t>::value,
  4856. "Missing/invalid function: bool number_integer(number_integer_t)");
  4857. static_assert(
  4858. is_detected_exact<bool, number_unsigned_function_t, SAX,
  4859. number_unsigned_t>::value,
  4860. "Missing/invalid function: bool number_unsigned(number_unsigned_t)");
  4861. static_assert(is_detected_exact<bool, number_float_function_t, SAX,
  4862. number_float_t, string_t>::value,
  4863. "Missing/invalid function: bool number_float(number_float_t, const string_t&)");
  4864. static_assert(
  4865. is_detected_exact<bool, string_function_t, SAX, string_t>::value,
  4866. "Missing/invalid function: bool string(string_t&)");
  4867. static_assert(is_detected_exact<bool, start_object_function_t, SAX>::value,
  4868. "Missing/invalid function: bool start_object(std::size_t)");
  4869. static_assert(is_detected_exact<bool, key_function_t, SAX, string_t>::value,
  4870. "Missing/invalid function: bool key(string_t&)");
  4871. static_assert(is_detected_exact<bool, end_object_function_t, SAX>::value,
  4872. "Missing/invalid function: bool end_object()");
  4873. static_assert(is_detected_exact<bool, start_array_function_t, SAX>::value,
  4874. "Missing/invalid function: bool start_array(std::size_t)");
  4875. static_assert(is_detected_exact<bool, end_array_function_t, SAX>::value,
  4876. "Missing/invalid function: bool end_array()");
  4877. static_assert(
  4878. is_detected_exact<bool, parse_error_function_t, SAX, exception_t>::value,
  4879. "Missing/invalid function: bool parse_error(std::size_t, const "
  4880. "std::string&, const exception&)");
  4881. };
  4882. } // namespace detail
  4883. } // namespace nlohmann
  4884. // #include <nlohmann/detail/value_t.hpp>
  4885. namespace nlohmann
  4886. {
  4887. namespace detail
  4888. {
  4889. /*!
  4890. @brief determine system byte order
  4891. @return true if and only if system's byte order is little endian
  4892. @note from https://stackoverflow.com/a/1001328/266378
  4893. */
  4894. static bool little_endianess(int num = 1) noexcept
  4895. {
  4896. return *reinterpret_cast<char*>(&num) == 1;
  4897. }
  4898. ///////////////////
  4899. // binary reader //
  4900. ///////////////////
  4901. /*!
  4902. @brief deserialization of CBOR, MessagePack, and UBJSON values
  4903. */
  4904. template<typename BasicJsonType, typename InputAdapterType, typename SAX = json_sax_dom_parser<BasicJsonType>>
  4905. class binary_reader
  4906. {
  4907. using number_integer_t = typename BasicJsonType::number_integer_t;
  4908. using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
  4909. using number_float_t = typename BasicJsonType::number_float_t;
  4910. using string_t = typename BasicJsonType::string_t;
  4911. using internal_binary_t = typename BasicJsonType::internal_binary_t;
  4912. using json_sax_t = SAX;
  4913. public:
  4914. /*!
  4915. @brief create a binary reader
  4916. @param[in] adapter input adapter to read from
  4917. */
  4918. explicit binary_reader(InputAdapterType&& adapter) : ia(std::move(adapter))
  4919. {
  4920. (void)detail::is_sax_static_asserts<SAX, BasicJsonType> {};
  4921. }
  4922. // make class move-only
  4923. binary_reader(const binary_reader&) = delete;
  4924. binary_reader(binary_reader&&) = default;
  4925. binary_reader& operator=(const binary_reader&) = delete;
  4926. binary_reader& operator=(binary_reader&&) = default;
  4927. ~binary_reader() = default;
  4928. /*!
  4929. @param[in] format the binary format to parse
  4930. @param[in] sax_ a SAX event processor
  4931. @param[in] strict whether to expect the input to be consumed completed
  4932. @return
  4933. */
  4934. JSON_HEDLEY_NON_NULL(3)
  4935. bool sax_parse(const input_format_t format,
  4936. json_sax_t* sax_,
  4937. const bool strict = true)
  4938. {
  4939. sax = sax_;
  4940. bool result = false;
  4941. switch (format)
  4942. {
  4943. case input_format_t::bson:
  4944. result = parse_bson_internal();
  4945. break;
  4946. case input_format_t::cbor:
  4947. result = parse_cbor_internal();
  4948. break;
  4949. case input_format_t::msgpack:
  4950. result = parse_msgpack_internal();
  4951. break;
  4952. case input_format_t::ubjson:
  4953. result = parse_ubjson_internal();
  4954. break;
  4955. default: // LCOV_EXCL_LINE
  4956. assert(false); // LCOV_EXCL_LINE
  4957. }
  4958. // strict mode: next byte must be EOF
  4959. if (result and strict)
  4960. {
  4961. if (format == input_format_t::ubjson)
  4962. {
  4963. get_ignore_noop();
  4964. }
  4965. else
  4966. {
  4967. get();
  4968. }
  4969. if (JSON_HEDLEY_UNLIKELY(current != std::char_traits<char>::eof()))
  4970. {
  4971. return sax->parse_error(chars_read, get_token_string(),
  4972. parse_error::create(110, chars_read, exception_message(format, "expected end of input; last byte: 0x" + get_token_string(), "value")));
  4973. }
  4974. }
  4975. return result;
  4976. }
  4977. private:
  4978. //////////
  4979. // BSON //
  4980. //////////
  4981. /*!
  4982. @brief Reads in a BSON-object and passes it to the SAX-parser.
  4983. @return whether a valid BSON-value was passed to the SAX parser
  4984. */
  4985. bool parse_bson_internal()
  4986. {
  4987. std::int32_t document_size;
  4988. get_number<std::int32_t, true>(input_format_t::bson, document_size);
  4989. if (JSON_HEDLEY_UNLIKELY(not sax->start_object(std::size_t(-1))))
  4990. {
  4991. return false;
  4992. }
  4993. if (JSON_HEDLEY_UNLIKELY(not parse_bson_element_list(/*is_array*/false)))
  4994. {
  4995. return false;
  4996. }
  4997. return sax->end_object();
  4998. }
  4999. /*!
  5000. @brief Parses a C-style string from the BSON input.
  5001. @param[in, out] result A reference to the string variable where the read
  5002. string is to be stored.
  5003. @return `true` if the \x00-byte indicating the end of the string was
  5004. encountered before the EOF; false` indicates an unexpected EOF.
  5005. */
  5006. bool get_bson_cstr(string_t& result)
  5007. {
  5008. auto out = std::back_inserter(result);
  5009. while (true)
  5010. {
  5011. get();
  5012. if (JSON_HEDLEY_UNLIKELY(not unexpect_eof(input_format_t::bson, "cstring")))
  5013. {
  5014. return false;
  5015. }
  5016. if (current == 0x00)
  5017. {
  5018. return true;
  5019. }
  5020. *out++ = static_cast<char>(current);
  5021. }
  5022. return true;
  5023. }
  5024. /*!
  5025. @brief Parses a zero-terminated string of length @a len from the BSON
  5026. input.
  5027. @param[in] len The length (including the zero-byte at the end) of the
  5028. string to be read.
  5029. @param[in, out] result A reference to the string variable where the read
  5030. string is to be stored.
  5031. @tparam NumberType The type of the length @a len
  5032. @pre len >= 1
  5033. @return `true` if the string was successfully parsed
  5034. */
  5035. template<typename NumberType>
  5036. bool get_bson_string(const NumberType len, string_t& result)
  5037. {
  5038. if (JSON_HEDLEY_UNLIKELY(len < 1))
  5039. {
  5040. auto last_token = get_token_string();
  5041. 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")));
  5042. }
  5043. return get_string(input_format_t::bson, len - static_cast<NumberType>(1), result) and get() != std::char_traits<char>::eof();
  5044. }
  5045. /*!
  5046. @brief Parses a byte array input of length @a len from the BSON input.
  5047. @param[in] len The length of the byte array to be read.
  5048. @param[in, out] result A reference to the binary variable where the read
  5049. array is to be stored.
  5050. @tparam NumberType The type of the length @a len
  5051. @pre len >= 0
  5052. @return `true` if the byte array was successfully parsed
  5053. */
  5054. template<typename NumberType>
  5055. bool get_bson_binary(const NumberType len, internal_binary_t& result)
  5056. {
  5057. if (JSON_HEDLEY_UNLIKELY(len < 0))
  5058. {
  5059. auto last_token = get_token_string();
  5060. return sax->parse_error(chars_read, last_token, parse_error::create(112, chars_read, exception_message(input_format_t::bson, "byte array length cannot be negative, is " + std::to_string(len), "binary")));
  5061. }
  5062. result.has_subtype = true; // All BSON binary values have a subtype
  5063. get_number<std::uint8_t>(input_format_t::bson, result.subtype);
  5064. return get_binary(input_format_t::bson, len, result);
  5065. }
  5066. /*!
  5067. @brief Read a BSON document element of the given @a element_type.
  5068. @param[in] element_type The BSON element type, c.f. http://bsonspec.org/spec.html
  5069. @param[in] element_type_parse_position The position in the input stream,
  5070. where the `element_type` was read.
  5071. @warning Not all BSON element types are supported yet. An unsupported
  5072. @a element_type will give rise to a parse_error.114:
  5073. Unsupported BSON record type 0x...
  5074. @return whether a valid BSON-object/array was passed to the SAX parser
  5075. */
  5076. bool parse_bson_element_internal(const int element_type,
  5077. const std::size_t element_type_parse_position)
  5078. {
  5079. switch (element_type)
  5080. {
  5081. case 0x01: // double
  5082. {
  5083. double number;
  5084. return get_number<double, true>(input_format_t::bson, number) and sax->number_float(static_cast<number_float_t>(number), "");
  5085. }
  5086. case 0x02: // string
  5087. {
  5088. std::int32_t len;
  5089. string_t value;
  5090. return get_number<std::int32_t, true>(input_format_t::bson, len) and get_bson_string(len, value) and sax->string(value);
  5091. }
  5092. case 0x03: // object
  5093. {
  5094. return parse_bson_internal();
  5095. }
  5096. case 0x04: // array
  5097. {
  5098. return parse_bson_array();
  5099. }
  5100. case 0x05: // binary
  5101. {
  5102. std::int32_t len;
  5103. internal_binary_t value;
  5104. return get_number<std::int32_t, true>(input_format_t::bson, len) and get_bson_binary(len, value) and sax->binary(value);
  5105. }
  5106. case 0x08: // boolean
  5107. {
  5108. return sax->boolean(get() != 0);
  5109. }
  5110. case 0x0A: // null
  5111. {
  5112. return sax->null();
  5113. }
  5114. case 0x10: // int32
  5115. {
  5116. std::int32_t value;
  5117. return get_number<std::int32_t, true>(input_format_t::bson, value) and sax->number_integer(value);
  5118. }
  5119. case 0x12: // int64
  5120. {
  5121. std::int64_t value;
  5122. return get_number<std::int64_t, true>(input_format_t::bson, value) and sax->number_integer(value);
  5123. }
  5124. default: // anything else not supported (yet)
  5125. {
  5126. std::array<char, 3> cr{{}};
  5127. (std::snprintf)(cr.data(), cr.size(), "%.2hhX", static_cast<unsigned char>(element_type));
  5128. 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())));
  5129. }
  5130. }
  5131. }
  5132. /*!
  5133. @brief Read a BSON element list (as specified in the BSON-spec)
  5134. The same binary layout is used for objects and arrays, hence it must be
  5135. indicated with the argument @a is_array which one is expected
  5136. (true --> array, false --> object).
  5137. @param[in] is_array Determines if the element list being read is to be
  5138. treated as an object (@a is_array == false), or as an
  5139. array (@a is_array == true).
  5140. @return whether a valid BSON-object/array was passed to the SAX parser
  5141. */
  5142. bool parse_bson_element_list(const bool is_array)
  5143. {
  5144. string_t key;
  5145. while (int element_type = get())
  5146. {
  5147. if (JSON_HEDLEY_UNLIKELY(not unexpect_eof(input_format_t::bson, "element list")))
  5148. {
  5149. return false;
  5150. }
  5151. const std::size_t element_type_parse_position = chars_read;
  5152. if (JSON_HEDLEY_UNLIKELY(not get_bson_cstr(key)))
  5153. {
  5154. return false;
  5155. }
  5156. if (not is_array and not sax->key(key))
  5157. {
  5158. return false;
  5159. }
  5160. if (JSON_HEDLEY_UNLIKELY(not parse_bson_element_internal(element_type, element_type_parse_position)))
  5161. {
  5162. return false;
  5163. }
  5164. // get_bson_cstr only appends
  5165. key.clear();
  5166. }
  5167. return true;
  5168. }
  5169. /*!
  5170. @brief Reads an array from the BSON input and passes it to the SAX-parser.
  5171. @return whether a valid BSON-array was passed to the SAX parser
  5172. */
  5173. bool parse_bson_array()
  5174. {
  5175. std::int32_t document_size;
  5176. get_number<std::int32_t, true>(input_format_t::bson, document_size);
  5177. if (JSON_HEDLEY_UNLIKELY(not sax->start_array(std::size_t(-1))))
  5178. {
  5179. return false;
  5180. }
  5181. if (JSON_HEDLEY_UNLIKELY(not parse_bson_element_list(/*is_array*/true)))
  5182. {
  5183. return false;
  5184. }
  5185. return sax->end_array();
  5186. }
  5187. //////////
  5188. // CBOR //
  5189. //////////
  5190. /*!
  5191. @param[in] get_char whether a new character should be retrieved from the
  5192. input (true, default) or whether the last read
  5193. character should be considered instead
  5194. @return whether a valid CBOR value was passed to the SAX parser
  5195. */
  5196. bool parse_cbor_internal(const bool get_char = true)
  5197. {
  5198. switch (get_char ? get() : current)
  5199. {
  5200. // EOF
  5201. case std::char_traits<char>::eof():
  5202. return unexpect_eof(input_format_t::cbor, "value");
  5203. // Integer 0x00..0x17 (0..23)
  5204. case 0x00:
  5205. case 0x01:
  5206. case 0x02:
  5207. case 0x03:
  5208. case 0x04:
  5209. case 0x05:
  5210. case 0x06:
  5211. case 0x07:
  5212. case 0x08:
  5213. case 0x09:
  5214. case 0x0A:
  5215. case 0x0B:
  5216. case 0x0C:
  5217. case 0x0D:
  5218. case 0x0E:
  5219. case 0x0F:
  5220. case 0x10:
  5221. case 0x11:
  5222. case 0x12:
  5223. case 0x13:
  5224. case 0x14:
  5225. case 0x15:
  5226. case 0x16:
  5227. case 0x17:
  5228. return sax->number_unsigned(static_cast<number_unsigned_t>(current));
  5229. case 0x18: // Unsigned integer (one-byte uint8_t follows)
  5230. {
  5231. std::uint8_t number;
  5232. return get_number(input_format_t::cbor, number) and sax->number_unsigned(number);
  5233. }
  5234. case 0x19: // Unsigned integer (two-byte uint16_t follows)
  5235. {
  5236. std::uint16_t number;
  5237. return get_number(input_format_t::cbor, number) and sax->number_unsigned(number);
  5238. }
  5239. case 0x1A: // Unsigned integer (four-byte uint32_t follows)
  5240. {
  5241. std::uint32_t number;
  5242. return get_number(input_format_t::cbor, number) and sax->number_unsigned(number);
  5243. }
  5244. case 0x1B: // Unsigned integer (eight-byte uint64_t follows)
  5245. {
  5246. std::uint64_t number;
  5247. return get_number(input_format_t::cbor, number) and sax->number_unsigned(number);
  5248. }
  5249. // Negative integer -1-0x00..-1-0x17 (-1..-24)
  5250. case 0x20:
  5251. case 0x21:
  5252. case 0x22:
  5253. case 0x23:
  5254. case 0x24:
  5255. case 0x25:
  5256. case 0x26:
  5257. case 0x27:
  5258. case 0x28:
  5259. case 0x29:
  5260. case 0x2A:
  5261. case 0x2B:
  5262. case 0x2C:
  5263. case 0x2D:
  5264. case 0x2E:
  5265. case 0x2F:
  5266. case 0x30:
  5267. case 0x31:
  5268. case 0x32:
  5269. case 0x33:
  5270. case 0x34:
  5271. case 0x35:
  5272. case 0x36:
  5273. case 0x37:
  5274. return sax->number_integer(static_cast<std::int8_t>(0x20 - 1 - current));
  5275. case 0x38: // Negative integer (one-byte uint8_t follows)
  5276. {
  5277. std::uint8_t number;
  5278. return get_number(input_format_t::cbor, number) and sax->number_integer(static_cast<number_integer_t>(-1) - number);
  5279. }
  5280. case 0x39: // Negative integer -1-n (two-byte uint16_t follows)
  5281. {
  5282. std::uint16_t number;
  5283. return get_number(input_format_t::cbor, number) and sax->number_integer(static_cast<number_integer_t>(-1) - number);
  5284. }
  5285. case 0x3A: // Negative integer -1-n (four-byte uint32_t follows)
  5286. {
  5287. std::uint32_t number;
  5288. return get_number(input_format_t::cbor, number) and sax->number_integer(static_cast<number_integer_t>(-1) - number);
  5289. }
  5290. case 0x3B: // Negative integer -1-n (eight-byte uint64_t follows)
  5291. {
  5292. std::uint64_t number;
  5293. return get_number(input_format_t::cbor, number) and sax->number_integer(static_cast<number_integer_t>(-1)
  5294. - static_cast<number_integer_t>(number));
  5295. }
  5296. // Binary data (0x00..0x17 bytes follow)
  5297. case 0x40:
  5298. case 0x41:
  5299. case 0x42:
  5300. case 0x43:
  5301. case 0x44:
  5302. case 0x45:
  5303. case 0x46:
  5304. case 0x47:
  5305. case 0x48:
  5306. case 0x49:
  5307. case 0x4A:
  5308. case 0x4B:
  5309. case 0x4C:
  5310. case 0x4D:
  5311. case 0x4E:
  5312. case 0x4F:
  5313. case 0x50:
  5314. case 0x51:
  5315. case 0x52:
  5316. case 0x53:
  5317. case 0x54:
  5318. case 0x55:
  5319. case 0x56:
  5320. case 0x57:
  5321. case 0x58: // Binary data (one-byte uint8_t for n follows)
  5322. case 0x59: // Binary data (two-byte uint16_t for n follow)
  5323. case 0x5A: // Binary data (four-byte uint32_t for n follow)
  5324. case 0x5B: // Binary data (eight-byte uint64_t for n follow)
  5325. case 0x5F: // Binary data (indefinite length)
  5326. {
  5327. internal_binary_t b;
  5328. return get_cbor_binary(b) and sax->binary(b);
  5329. }
  5330. // UTF-8 string (0x00..0x17 bytes follow)
  5331. case 0x60:
  5332. case 0x61:
  5333. case 0x62:
  5334. case 0x63:
  5335. case 0x64:
  5336. case 0x65:
  5337. case 0x66:
  5338. case 0x67:
  5339. case 0x68:
  5340. case 0x69:
  5341. case 0x6A:
  5342. case 0x6B:
  5343. case 0x6C:
  5344. case 0x6D:
  5345. case 0x6E:
  5346. case 0x6F:
  5347. case 0x70:
  5348. case 0x71:
  5349. case 0x72:
  5350. case 0x73:
  5351. case 0x74:
  5352. case 0x75:
  5353. case 0x76:
  5354. case 0x77:
  5355. case 0x78: // UTF-8 string (one-byte uint8_t for n follows)
  5356. case 0x79: // UTF-8 string (two-byte uint16_t for n follow)
  5357. case 0x7A: // UTF-8 string (four-byte uint32_t for n follow)
  5358. case 0x7B: // UTF-8 string (eight-byte uint64_t for n follow)
  5359. case 0x7F: // UTF-8 string (indefinite length)
  5360. {
  5361. string_t s;
  5362. return get_cbor_string(s) and sax->string(s);
  5363. }
  5364. // array (0x00..0x17 data items follow)
  5365. case 0x80:
  5366. case 0x81:
  5367. case 0x82:
  5368. case 0x83:
  5369. case 0x84:
  5370. case 0x85:
  5371. case 0x86:
  5372. case 0x87:
  5373. case 0x88:
  5374. case 0x89:
  5375. case 0x8A:
  5376. case 0x8B:
  5377. case 0x8C:
  5378. case 0x8D:
  5379. case 0x8E:
  5380. case 0x8F:
  5381. case 0x90:
  5382. case 0x91:
  5383. case 0x92:
  5384. case 0x93:
  5385. case 0x94:
  5386. case 0x95:
  5387. case 0x96:
  5388. case 0x97:
  5389. return get_cbor_array(static_cast<std::size_t>(static_cast<unsigned int>(current) & 0x1Fu));
  5390. case 0x98: // array (one-byte uint8_t for n follows)
  5391. {
  5392. std::uint8_t len;
  5393. return get_number(input_format_t::cbor, len) and get_cbor_array(static_cast<std::size_t>(len));
  5394. }
  5395. case 0x99: // array (two-byte uint16_t for n follow)
  5396. {
  5397. std::uint16_t len;
  5398. return get_number(input_format_t::cbor, len) and get_cbor_array(static_cast<std::size_t>(len));
  5399. }
  5400. case 0x9A: // array (four-byte uint32_t for n follow)
  5401. {
  5402. std::uint32_t len;
  5403. return get_number(input_format_t::cbor, len) and get_cbor_array(static_cast<std::size_t>(len));
  5404. }
  5405. case 0x9B: // array (eight-byte uint64_t for n follow)
  5406. {
  5407. std::uint64_t len;
  5408. return get_number(input_format_t::cbor, len) and get_cbor_array(static_cast<std::size_t>(len));
  5409. }
  5410. case 0x9F: // array (indefinite length)
  5411. return get_cbor_array(std::size_t(-1));
  5412. // map (0x00..0x17 pairs of data items follow)
  5413. case 0xA0:
  5414. case 0xA1:
  5415. case 0xA2:
  5416. case 0xA3:
  5417. case 0xA4:
  5418. case 0xA5:
  5419. case 0xA6:
  5420. case 0xA7:
  5421. case 0xA8:
  5422. case 0xA9:
  5423. case 0xAA:
  5424. case 0xAB:
  5425. case 0xAC:
  5426. case 0xAD:
  5427. case 0xAE:
  5428. case 0xAF:
  5429. case 0xB0:
  5430. case 0xB1:
  5431. case 0xB2:
  5432. case 0xB3:
  5433. case 0xB4:
  5434. case 0xB5:
  5435. case 0xB6:
  5436. case 0xB7:
  5437. return get_cbor_object(static_cast<std::size_t>(static_cast<unsigned int>(current) & 0x1Fu));
  5438. case 0xB8: // map (one-byte uint8_t for n follows)
  5439. {
  5440. std::uint8_t len;
  5441. return get_number(input_format_t::cbor, len) and get_cbor_object(static_cast<std::size_t>(len));
  5442. }
  5443. case 0xB9: // map (two-byte uint16_t for n follow)
  5444. {
  5445. std::uint16_t len;
  5446. return get_number(input_format_t::cbor, len) and get_cbor_object(static_cast<std::size_t>(len));
  5447. }
  5448. case 0xBA: // map (four-byte uint32_t for n follow)
  5449. {
  5450. std::uint32_t len;
  5451. return get_number(input_format_t::cbor, len) and get_cbor_object(static_cast<std::size_t>(len));
  5452. }
  5453. case 0xBB: // map (eight-byte uint64_t for n follow)
  5454. {
  5455. std::uint64_t len;
  5456. return get_number(input_format_t::cbor, len) and get_cbor_object(static_cast<std::size_t>(len));
  5457. }
  5458. case 0xBF: // map (indefinite length)
  5459. return get_cbor_object(std::size_t(-1));
  5460. case 0xF4: // false
  5461. return sax->boolean(false);
  5462. case 0xF5: // true
  5463. return sax->boolean(true);
  5464. case 0xF6: // null
  5465. return sax->null();
  5466. case 0xF9: // Half-Precision Float (two-byte IEEE 754)
  5467. {
  5468. const int byte1_raw = get();
  5469. if (JSON_HEDLEY_UNLIKELY(not unexpect_eof(input_format_t::cbor, "number")))
  5470. {
  5471. return false;
  5472. }
  5473. const int byte2_raw = get();
  5474. if (JSON_HEDLEY_UNLIKELY(not unexpect_eof(input_format_t::cbor, "number")))
  5475. {
  5476. return false;
  5477. }
  5478. const auto byte1 = static_cast<unsigned char>(byte1_raw);
  5479. const auto byte2 = static_cast<unsigned char>(byte2_raw);
  5480. // code from RFC 7049, Appendix D, Figure 3:
  5481. // As half-precision floating-point numbers were only added
  5482. // to IEEE 754 in 2008, today's programming platforms often
  5483. // still only have limited support for them. It is very
  5484. // easy to include at least decoding support for them even
  5485. // without such support. An example of a small decoder for
  5486. // half-precision floating-point numbers in the C language
  5487. // is shown in Fig. 3.
  5488. const auto half = static_cast<unsigned int>((byte1 << 8u) + byte2);
  5489. const double val = [&half]
  5490. {
  5491. const int exp = (half >> 10u) & 0x1Fu;
  5492. const unsigned int mant = half & 0x3FFu;
  5493. assert(0 <= exp and exp <= 32);
  5494. assert(mant <= 1024);
  5495. switch (exp)
  5496. {
  5497. case 0:
  5498. return std::ldexp(mant, -24);
  5499. case 31:
  5500. return (mant == 0)
  5501. ? std::numeric_limits<double>::infinity()
  5502. : std::numeric_limits<double>::quiet_NaN();
  5503. default:
  5504. return std::ldexp(mant + 1024, exp - 25);
  5505. }
  5506. }();
  5507. return sax->number_float((half & 0x8000u) != 0
  5508. ? static_cast<number_float_t>(-val)
  5509. : static_cast<number_float_t>(val), "");
  5510. }
  5511. case 0xFA: // Single-Precision Float (four-byte IEEE 754)
  5512. {
  5513. float number;
  5514. return get_number(input_format_t::cbor, number) and sax->number_float(static_cast<number_float_t>(number), "");
  5515. }
  5516. case 0xFB: // Double-Precision Float (eight-byte IEEE 754)
  5517. {
  5518. double number;
  5519. return get_number(input_format_t::cbor, number) and sax->number_float(static_cast<number_float_t>(number), "");
  5520. }
  5521. default: // anything else (0xFF is handled inside the other types)
  5522. {
  5523. auto last_token = get_token_string();
  5524. 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")));
  5525. }
  5526. }
  5527. }
  5528. /*!
  5529. @brief reads a CBOR string
  5530. This function first reads starting bytes to determine the expected
  5531. string length and then copies this number of bytes into a string.
  5532. Additionally, CBOR's strings with indefinite lengths are supported.
  5533. @param[out] result created string
  5534. @return whether string creation completed
  5535. */
  5536. bool get_cbor_string(string_t& result)
  5537. {
  5538. if (JSON_HEDLEY_UNLIKELY(not unexpect_eof(input_format_t::cbor, "string")))
  5539. {
  5540. return false;
  5541. }
  5542. switch (current)
  5543. {
  5544. // UTF-8 string (0x00..0x17 bytes follow)
  5545. case 0x60:
  5546. case 0x61:
  5547. case 0x62:
  5548. case 0x63:
  5549. case 0x64:
  5550. case 0x65:
  5551. case 0x66:
  5552. case 0x67:
  5553. case 0x68:
  5554. case 0x69:
  5555. case 0x6A:
  5556. case 0x6B:
  5557. case 0x6C:
  5558. case 0x6D:
  5559. case 0x6E:
  5560. case 0x6F:
  5561. case 0x70:
  5562. case 0x71:
  5563. case 0x72:
  5564. case 0x73:
  5565. case 0x74:
  5566. case 0x75:
  5567. case 0x76:
  5568. case 0x77:
  5569. {
  5570. return get_string(input_format_t::cbor, static_cast<unsigned int>(current) & 0x1Fu, result);
  5571. }
  5572. case 0x78: // UTF-8 string (one-byte uint8_t for n follows)
  5573. {
  5574. std::uint8_t len;
  5575. return get_number(input_format_t::cbor, len) and get_string(input_format_t::cbor, len, result);
  5576. }
  5577. case 0x79: // UTF-8 string (two-byte uint16_t for n follow)
  5578. {
  5579. std::uint16_t len;
  5580. return get_number(input_format_t::cbor, len) and get_string(input_format_t::cbor, len, result);
  5581. }
  5582. case 0x7A: // UTF-8 string (four-byte uint32_t for n follow)
  5583. {
  5584. std::uint32_t len;
  5585. return get_number(input_format_t::cbor, len) and get_string(input_format_t::cbor, len, result);
  5586. }
  5587. case 0x7B: // UTF-8 string (eight-byte uint64_t for n follow)
  5588. {
  5589. std::uint64_t len;
  5590. return get_number(input_format_t::cbor, len) and get_string(input_format_t::cbor, len, result);
  5591. }
  5592. case 0x7F: // UTF-8 string (indefinite length)
  5593. {
  5594. while (get() != 0xFF)
  5595. {
  5596. string_t chunk;
  5597. if (not get_cbor_string(chunk))
  5598. {
  5599. return false;
  5600. }
  5601. result.append(chunk);
  5602. }
  5603. return true;
  5604. }
  5605. default:
  5606. {
  5607. auto last_token = get_token_string();
  5608. 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")));
  5609. }
  5610. }
  5611. }
  5612. /*!
  5613. @brief reads a CBOR byte array
  5614. This function first reads starting bytes to determine the expected
  5615. byte array length and then copies this number of bytes into the byte array.
  5616. Additionally, CBOR's byte arrays with indefinite lengths are supported.
  5617. @param[out] result created byte array
  5618. @return whether byte array creation completed
  5619. */
  5620. bool get_cbor_binary(internal_binary_t& result)
  5621. {
  5622. if (JSON_HEDLEY_UNLIKELY(not unexpect_eof(input_format_t::cbor, "binary")))
  5623. {
  5624. return false;
  5625. }
  5626. switch (current)
  5627. {
  5628. // Binary data (0x00..0x17 bytes follow)
  5629. case 0x40:
  5630. case 0x41:
  5631. case 0x42:
  5632. case 0x43:
  5633. case 0x44:
  5634. case 0x45:
  5635. case 0x46:
  5636. case 0x47:
  5637. case 0x48:
  5638. case 0x49:
  5639. case 0x4A:
  5640. case 0x4B:
  5641. case 0x4C:
  5642. case 0x4D:
  5643. case 0x4E:
  5644. case 0x4F:
  5645. case 0x50:
  5646. case 0x51:
  5647. case 0x52:
  5648. case 0x53:
  5649. case 0x54:
  5650. case 0x55:
  5651. case 0x56:
  5652. case 0x57:
  5653. {
  5654. return get_binary(input_format_t::cbor, static_cast<unsigned int>(current) & 0x1Fu, result);
  5655. }
  5656. case 0x58: // Binary data (one-byte uint8_t for n follows)
  5657. {
  5658. std::uint8_t len;
  5659. return get_number(input_format_t::cbor, len) and get_binary(input_format_t::cbor, len, result);
  5660. }
  5661. case 0x59: // Binary data (two-byte uint16_t for n follow)
  5662. {
  5663. std::uint16_t len;
  5664. return get_number(input_format_t::cbor, len) and get_binary(input_format_t::cbor, len, result);
  5665. }
  5666. case 0x5A: // Binary data (four-byte uint32_t for n follow)
  5667. {
  5668. std::uint32_t len;
  5669. return get_number(input_format_t::cbor, len) and get_binary(input_format_t::cbor, len, result);
  5670. }
  5671. case 0x5B: // Binary data (eight-byte uint64_t for n follow)
  5672. {
  5673. std::uint64_t len;
  5674. return get_number(input_format_t::cbor, len) and get_binary(input_format_t::cbor, len, result);
  5675. }
  5676. case 0x5F: // Binary data (indefinite length)
  5677. {
  5678. while (get() != 0xFF)
  5679. {
  5680. internal_binary_t chunk;
  5681. if (not get_cbor_binary(chunk))
  5682. {
  5683. return false;
  5684. }
  5685. result.insert(result.end(), chunk.begin(), chunk.end());
  5686. }
  5687. return true;
  5688. }
  5689. default:
  5690. {
  5691. auto last_token = get_token_string();
  5692. return sax->parse_error(chars_read, last_token, parse_error::create(113, chars_read, exception_message(input_format_t::cbor, "expected length specification (0x40-0x5B) or indefinite binary array type (0x5F); last byte: 0x" + last_token, "binary")));
  5693. }
  5694. }
  5695. }
  5696. /*!
  5697. @param[in] len the length of the array or std::size_t(-1) for an
  5698. array of indefinite size
  5699. @return whether array creation completed
  5700. */
  5701. bool get_cbor_array(const std::size_t len)
  5702. {
  5703. if (JSON_HEDLEY_UNLIKELY(not sax->start_array(len)))
  5704. {
  5705. return false;
  5706. }
  5707. if (len != std::size_t(-1))
  5708. {
  5709. for (std::size_t i = 0; i < len; ++i)
  5710. {
  5711. if (JSON_HEDLEY_UNLIKELY(not parse_cbor_internal()))
  5712. {
  5713. return false;
  5714. }
  5715. }
  5716. }
  5717. else
  5718. {
  5719. while (get() != 0xFF)
  5720. {
  5721. if (JSON_HEDLEY_UNLIKELY(not parse_cbor_internal(false)))
  5722. {
  5723. return false;
  5724. }
  5725. }
  5726. }
  5727. return sax->end_array();
  5728. }
  5729. /*!
  5730. @param[in] len the length of the object or std::size_t(-1) for an
  5731. object of indefinite size
  5732. @return whether object creation completed
  5733. */
  5734. bool get_cbor_object(const std::size_t len)
  5735. {
  5736. if (JSON_HEDLEY_UNLIKELY(not sax->start_object(len)))
  5737. {
  5738. return false;
  5739. }
  5740. string_t key;
  5741. if (len != std::size_t(-1))
  5742. {
  5743. for (std::size_t i = 0; i < len; ++i)
  5744. {
  5745. get();
  5746. if (JSON_HEDLEY_UNLIKELY(not get_cbor_string(key) or not sax->key(key)))
  5747. {
  5748. return false;
  5749. }
  5750. if (JSON_HEDLEY_UNLIKELY(not parse_cbor_internal()))
  5751. {
  5752. return false;
  5753. }
  5754. key.clear();
  5755. }
  5756. }
  5757. else
  5758. {
  5759. while (get() != 0xFF)
  5760. {
  5761. if (JSON_HEDLEY_UNLIKELY(not get_cbor_string(key) or not sax->key(key)))
  5762. {
  5763. return false;
  5764. }
  5765. if (JSON_HEDLEY_UNLIKELY(not parse_cbor_internal()))
  5766. {
  5767. return false;
  5768. }
  5769. key.clear();
  5770. }
  5771. }
  5772. return sax->end_object();
  5773. }
  5774. /////////////
  5775. // MsgPack //
  5776. /////////////
  5777. /*!
  5778. @return whether a valid MessagePack value was passed to the SAX parser
  5779. */
  5780. bool parse_msgpack_internal()
  5781. {
  5782. switch (get())
  5783. {
  5784. // EOF
  5785. case std::char_traits<char>::eof():
  5786. return unexpect_eof(input_format_t::msgpack, "value");
  5787. // positive fixint
  5788. case 0x00:
  5789. case 0x01:
  5790. case 0x02:
  5791. case 0x03:
  5792. case 0x04:
  5793. case 0x05:
  5794. case 0x06:
  5795. case 0x07:
  5796. case 0x08:
  5797. case 0x09:
  5798. case 0x0A:
  5799. case 0x0B:
  5800. case 0x0C:
  5801. case 0x0D:
  5802. case 0x0E:
  5803. case 0x0F:
  5804. case 0x10:
  5805. case 0x11:
  5806. case 0x12:
  5807. case 0x13:
  5808. case 0x14:
  5809. case 0x15:
  5810. case 0x16:
  5811. case 0x17:
  5812. case 0x18:
  5813. case 0x19:
  5814. case 0x1A:
  5815. case 0x1B:
  5816. case 0x1C:
  5817. case 0x1D:
  5818. case 0x1E:
  5819. case 0x1F:
  5820. case 0x20:
  5821. case 0x21:
  5822. case 0x22:
  5823. case 0x23:
  5824. case 0x24:
  5825. case 0x25:
  5826. case 0x26:
  5827. case 0x27:
  5828. case 0x28:
  5829. case 0x29:
  5830. case 0x2A:
  5831. case 0x2B:
  5832. case 0x2C:
  5833. case 0x2D:
  5834. case 0x2E:
  5835. case 0x2F:
  5836. case 0x30:
  5837. case 0x31:
  5838. case 0x32:
  5839. case 0x33:
  5840. case 0x34:
  5841. case 0x35:
  5842. case 0x36:
  5843. case 0x37:
  5844. case 0x38:
  5845. case 0x39:
  5846. case 0x3A:
  5847. case 0x3B:
  5848. case 0x3C:
  5849. case 0x3D:
  5850. case 0x3E:
  5851. case 0x3F:
  5852. case 0x40:
  5853. case 0x41:
  5854. case 0x42:
  5855. case 0x43:
  5856. case 0x44:
  5857. case 0x45:
  5858. case 0x46:
  5859. case 0x47:
  5860. case 0x48:
  5861. case 0x49:
  5862. case 0x4A:
  5863. case 0x4B:
  5864. case 0x4C:
  5865. case 0x4D:
  5866. case 0x4E:
  5867. case 0x4F:
  5868. case 0x50:
  5869. case 0x51:
  5870. case 0x52:
  5871. case 0x53:
  5872. case 0x54:
  5873. case 0x55:
  5874. case 0x56:
  5875. case 0x57:
  5876. case 0x58:
  5877. case 0x59:
  5878. case 0x5A:
  5879. case 0x5B:
  5880. case 0x5C:
  5881. case 0x5D:
  5882. case 0x5E:
  5883. case 0x5F:
  5884. case 0x60:
  5885. case 0x61:
  5886. case 0x62:
  5887. case 0x63:
  5888. case 0x64:
  5889. case 0x65:
  5890. case 0x66:
  5891. case 0x67:
  5892. case 0x68:
  5893. case 0x69:
  5894. case 0x6A:
  5895. case 0x6B:
  5896. case 0x6C:
  5897. case 0x6D:
  5898. case 0x6E:
  5899. case 0x6F:
  5900. case 0x70:
  5901. case 0x71:
  5902. case 0x72:
  5903. case 0x73:
  5904. case 0x74:
  5905. case 0x75:
  5906. case 0x76:
  5907. case 0x77:
  5908. case 0x78:
  5909. case 0x79:
  5910. case 0x7A:
  5911. case 0x7B:
  5912. case 0x7C:
  5913. case 0x7D:
  5914. case 0x7E:
  5915. case 0x7F:
  5916. return sax->number_unsigned(static_cast<number_unsigned_t>(current));
  5917. // fixmap
  5918. case 0x80:
  5919. case 0x81:
  5920. case 0x82:
  5921. case 0x83:
  5922. case 0x84:
  5923. case 0x85:
  5924. case 0x86:
  5925. case 0x87:
  5926. case 0x88:
  5927. case 0x89:
  5928. case 0x8A:
  5929. case 0x8B:
  5930. case 0x8C:
  5931. case 0x8D:
  5932. case 0x8E:
  5933. case 0x8F:
  5934. return get_msgpack_object(static_cast<std::size_t>(static_cast<unsigned int>(current) & 0x0Fu));
  5935. // fixarray
  5936. case 0x90:
  5937. case 0x91:
  5938. case 0x92:
  5939. case 0x93:
  5940. case 0x94:
  5941. case 0x95:
  5942. case 0x96:
  5943. case 0x97:
  5944. case 0x98:
  5945. case 0x99:
  5946. case 0x9A:
  5947. case 0x9B:
  5948. case 0x9C:
  5949. case 0x9D:
  5950. case 0x9E:
  5951. case 0x9F:
  5952. return get_msgpack_array(static_cast<std::size_t>(static_cast<unsigned int>(current) & 0x0Fu));
  5953. // fixstr
  5954. case 0xA0:
  5955. case 0xA1:
  5956. case 0xA2:
  5957. case 0xA3:
  5958. case 0xA4:
  5959. case 0xA5:
  5960. case 0xA6:
  5961. case 0xA7:
  5962. case 0xA8:
  5963. case 0xA9:
  5964. case 0xAA:
  5965. case 0xAB:
  5966. case 0xAC:
  5967. case 0xAD:
  5968. case 0xAE:
  5969. case 0xAF:
  5970. case 0xB0:
  5971. case 0xB1:
  5972. case 0xB2:
  5973. case 0xB3:
  5974. case 0xB4:
  5975. case 0xB5:
  5976. case 0xB6:
  5977. case 0xB7:
  5978. case 0xB8:
  5979. case 0xB9:
  5980. case 0xBA:
  5981. case 0xBB:
  5982. case 0xBC:
  5983. case 0xBD:
  5984. case 0xBE:
  5985. case 0xBF:
  5986. case 0xD9: // str 8
  5987. case 0xDA: // str 16
  5988. case 0xDB: // str 32
  5989. {
  5990. string_t s;
  5991. return get_msgpack_string(s) and sax->string(s);
  5992. }
  5993. case 0xC0: // nil
  5994. return sax->null();
  5995. case 0xC2: // false
  5996. return sax->boolean(false);
  5997. case 0xC3: // true
  5998. return sax->boolean(true);
  5999. case 0xC4: // bin 8
  6000. case 0xC5: // bin 16
  6001. case 0xC6: // bin 32
  6002. case 0xC7: // ext 8
  6003. case 0xC8: // ext 16
  6004. case 0xC9: // ext 32
  6005. case 0xD4: // fixext 1
  6006. case 0xD5: // fixext 2
  6007. case 0xD6: // fixext 4
  6008. case 0xD7: // fixext 8
  6009. case 0xD8: // fixext 16
  6010. {
  6011. internal_binary_t b;
  6012. return get_msgpack_binary(b) and sax->binary(b);
  6013. }
  6014. case 0xCA: // float 32
  6015. {
  6016. float number;
  6017. return get_number(input_format_t::msgpack, number) and sax->number_float(static_cast<number_float_t>(number), "");
  6018. }
  6019. case 0xCB: // float 64
  6020. {
  6021. double number;
  6022. return get_number(input_format_t::msgpack, number) and sax->number_float(static_cast<number_float_t>(number), "");
  6023. }
  6024. case 0xCC: // uint 8
  6025. {
  6026. std::uint8_t number;
  6027. return get_number(input_format_t::msgpack, number) and sax->number_unsigned(number);
  6028. }
  6029. case 0xCD: // uint 16
  6030. {
  6031. std::uint16_t number;
  6032. return get_number(input_format_t::msgpack, number) and sax->number_unsigned(number);
  6033. }
  6034. case 0xCE: // uint 32
  6035. {
  6036. std::uint32_t number;
  6037. return get_number(input_format_t::msgpack, number) and sax->number_unsigned(number);
  6038. }
  6039. case 0xCF: // uint 64
  6040. {
  6041. std::uint64_t number;
  6042. return get_number(input_format_t::msgpack, number) and sax->number_unsigned(number);
  6043. }
  6044. case 0xD0: // int 8
  6045. {
  6046. std::int8_t number;
  6047. return get_number(input_format_t::msgpack, number) and sax->number_integer(number);
  6048. }
  6049. case 0xD1: // int 16
  6050. {
  6051. std::int16_t number;
  6052. return get_number(input_format_t::msgpack, number) and sax->number_integer(number);
  6053. }
  6054. case 0xD2: // int 32
  6055. {
  6056. std::int32_t number;
  6057. return get_number(input_format_t::msgpack, number) and sax->number_integer(number);
  6058. }
  6059. case 0xD3: // int 64
  6060. {
  6061. std::int64_t number;
  6062. return get_number(input_format_t::msgpack, number) and sax->number_integer(number);
  6063. }
  6064. case 0xDC: // array 16
  6065. {
  6066. std::uint16_t len;
  6067. return get_number(input_format_t::msgpack, len) and get_msgpack_array(static_cast<std::size_t>(len));
  6068. }
  6069. case 0xDD: // array 32
  6070. {
  6071. std::uint32_t len;
  6072. return get_number(input_format_t::msgpack, len) and get_msgpack_array(static_cast<std::size_t>(len));
  6073. }
  6074. case 0xDE: // map 16
  6075. {
  6076. std::uint16_t len;
  6077. return get_number(input_format_t::msgpack, len) and get_msgpack_object(static_cast<std::size_t>(len));
  6078. }
  6079. case 0xDF: // map 32
  6080. {
  6081. std::uint32_t len;
  6082. return get_number(input_format_t::msgpack, len) and get_msgpack_object(static_cast<std::size_t>(len));
  6083. }
  6084. // negative fixint
  6085. case 0xE0:
  6086. case 0xE1:
  6087. case 0xE2:
  6088. case 0xE3:
  6089. case 0xE4:
  6090. case 0xE5:
  6091. case 0xE6:
  6092. case 0xE7:
  6093. case 0xE8:
  6094. case 0xE9:
  6095. case 0xEA:
  6096. case 0xEB:
  6097. case 0xEC:
  6098. case 0xED:
  6099. case 0xEE:
  6100. case 0xEF:
  6101. case 0xF0:
  6102. case 0xF1:
  6103. case 0xF2:
  6104. case 0xF3:
  6105. case 0xF4:
  6106. case 0xF5:
  6107. case 0xF6:
  6108. case 0xF7:
  6109. case 0xF8:
  6110. case 0xF9:
  6111. case 0xFA:
  6112. case 0xFB:
  6113. case 0xFC:
  6114. case 0xFD:
  6115. case 0xFE:
  6116. case 0xFF:
  6117. return sax->number_integer(static_cast<std::int8_t>(current));
  6118. default: // anything else
  6119. {
  6120. auto last_token = get_token_string();
  6121. 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")));
  6122. }
  6123. }
  6124. }
  6125. /*!
  6126. @brief reads a MessagePack string
  6127. This function first reads starting bytes to determine the expected
  6128. string length and then copies this number of bytes into a string.
  6129. @param[out] result created string
  6130. @return whether string creation completed
  6131. */
  6132. bool get_msgpack_string(string_t& result)
  6133. {
  6134. if (JSON_HEDLEY_UNLIKELY(not unexpect_eof(input_format_t::msgpack, "string")))
  6135. {
  6136. return false;
  6137. }
  6138. switch (current)
  6139. {
  6140. // fixstr
  6141. case 0xA0:
  6142. case 0xA1:
  6143. case 0xA2:
  6144. case 0xA3:
  6145. case 0xA4:
  6146. case 0xA5:
  6147. case 0xA6:
  6148. case 0xA7:
  6149. case 0xA8:
  6150. case 0xA9:
  6151. case 0xAA:
  6152. case 0xAB:
  6153. case 0xAC:
  6154. case 0xAD:
  6155. case 0xAE:
  6156. case 0xAF:
  6157. case 0xB0:
  6158. case 0xB1:
  6159. case 0xB2:
  6160. case 0xB3:
  6161. case 0xB4:
  6162. case 0xB5:
  6163. case 0xB6:
  6164. case 0xB7:
  6165. case 0xB8:
  6166. case 0xB9:
  6167. case 0xBA:
  6168. case 0xBB:
  6169. case 0xBC:
  6170. case 0xBD:
  6171. case 0xBE:
  6172. case 0xBF:
  6173. {
  6174. return get_string(input_format_t::msgpack, static_cast<unsigned int>(current) & 0x1Fu, result);
  6175. }
  6176. case 0xD9: // str 8
  6177. {
  6178. std::uint8_t len;
  6179. return get_number(input_format_t::msgpack, len) and get_string(input_format_t::msgpack, len, result);
  6180. }
  6181. case 0xDA: // str 16
  6182. {
  6183. std::uint16_t len;
  6184. return get_number(input_format_t::msgpack, len) and get_string(input_format_t::msgpack, len, result);
  6185. }
  6186. case 0xDB: // str 32
  6187. {
  6188. std::uint32_t len;
  6189. return get_number(input_format_t::msgpack, len) and get_string(input_format_t::msgpack, len, result);
  6190. }
  6191. default:
  6192. {
  6193. auto last_token = get_token_string();
  6194. 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")));
  6195. }
  6196. }
  6197. }
  6198. /*!
  6199. @brief reads a MessagePack byte array
  6200. This function first reads starting bytes to determine the expected
  6201. byte array length and then copies this number of bytes into a byte array.
  6202. @param[out] result created byte array
  6203. @return whether byte array creation completed
  6204. */
  6205. bool get_msgpack_binary(internal_binary_t& result)
  6206. {
  6207. switch (current)
  6208. {
  6209. case 0xC4: // bin 8
  6210. {
  6211. std::uint8_t len;
  6212. return get_number(input_format_t::msgpack, len) and get_binary(input_format_t::msgpack, len, result);
  6213. }
  6214. case 0xC5: // bin 16
  6215. {
  6216. std::uint16_t len;
  6217. return get_number(input_format_t::msgpack, len) and get_binary(input_format_t::msgpack, len, result);
  6218. }
  6219. case 0xC6: // bin 32
  6220. {
  6221. std::uint32_t len;
  6222. return get_number(input_format_t::msgpack, len) and get_binary(input_format_t::msgpack, len, result);
  6223. }
  6224. case 0xC7: // ext 8
  6225. {
  6226. std::uint8_t len;
  6227. result.has_subtype = true;
  6228. return get_number(input_format_t::msgpack, len) and
  6229. get_number(input_format_t::msgpack, result.subtype) and
  6230. get_binary(input_format_t::msgpack, len, result);
  6231. }
  6232. case 0xC8: // ext 16
  6233. {
  6234. std::uint16_t len;
  6235. result.has_subtype = true;
  6236. return get_number(input_format_t::msgpack, len) and
  6237. get_number(input_format_t::msgpack, result.subtype) and
  6238. get_binary(input_format_t::msgpack, len, result);
  6239. }
  6240. case 0xC9: // ext 32
  6241. {
  6242. std::uint32_t len;
  6243. result.has_subtype = true;
  6244. return get_number(input_format_t::msgpack, len) and
  6245. get_number(input_format_t::msgpack, result.subtype) and
  6246. get_binary(input_format_t::msgpack, len, result);
  6247. }
  6248. case 0xD4: // fixext 1
  6249. {
  6250. result.has_subtype = true;
  6251. return get_number(input_format_t::msgpack, result.subtype) and get_binary(input_format_t::msgpack, 1, result);
  6252. }
  6253. case 0xD5: // fixext 2
  6254. {
  6255. result.has_subtype = true;
  6256. return get_number(input_format_t::msgpack, result.subtype) and get_binary(input_format_t::msgpack, 2, result);
  6257. }
  6258. case 0xD6: // fixext 4
  6259. {
  6260. result.has_subtype = true;
  6261. return get_number(input_format_t::msgpack, result.subtype) and get_binary(input_format_t::msgpack, 4, result);
  6262. }
  6263. case 0xD7: // fixext 8
  6264. {
  6265. result.has_subtype = true;
  6266. return get_number(input_format_t::msgpack, result.subtype) and get_binary(input_format_t::msgpack, 8, result);
  6267. }
  6268. case 0xD8: // fixext 16
  6269. {
  6270. result.has_subtype = true;
  6271. return get_number(input_format_t::msgpack, result.subtype) and get_binary(input_format_t::msgpack, 16, result);
  6272. }
  6273. default: // LCOV_EXCL_LINE
  6274. return false; // LCOV_EXCL_LINE
  6275. }
  6276. }
  6277. /*!
  6278. @param[in] len the length of the array
  6279. @return whether array creation completed
  6280. */
  6281. bool get_msgpack_array(const std::size_t len)
  6282. {
  6283. if (JSON_HEDLEY_UNLIKELY(not sax->start_array(len)))
  6284. {
  6285. return false;
  6286. }
  6287. for (std::size_t i = 0; i < len; ++i)
  6288. {
  6289. if (JSON_HEDLEY_UNLIKELY(not parse_msgpack_internal()))
  6290. {
  6291. return false;
  6292. }
  6293. }
  6294. return sax->end_array();
  6295. }
  6296. /*!
  6297. @param[in] len the length of the object
  6298. @return whether object creation completed
  6299. */
  6300. bool get_msgpack_object(const std::size_t len)
  6301. {
  6302. if (JSON_HEDLEY_UNLIKELY(not sax->start_object(len)))
  6303. {
  6304. return false;
  6305. }
  6306. string_t key;
  6307. for (std::size_t i = 0; i < len; ++i)
  6308. {
  6309. get();
  6310. if (JSON_HEDLEY_UNLIKELY(not get_msgpack_string(key) or not sax->key(key)))
  6311. {
  6312. return false;
  6313. }
  6314. if (JSON_HEDLEY_UNLIKELY(not parse_msgpack_internal()))
  6315. {
  6316. return false;
  6317. }
  6318. key.clear();
  6319. }
  6320. return sax->end_object();
  6321. }
  6322. ////////////
  6323. // UBJSON //
  6324. ////////////
  6325. /*!
  6326. @param[in] get_char whether a new character should be retrieved from the
  6327. input (true, default) or whether the last read
  6328. character should be considered instead
  6329. @return whether a valid UBJSON value was passed to the SAX parser
  6330. */
  6331. bool parse_ubjson_internal(const bool get_char = true)
  6332. {
  6333. return get_ubjson_value(get_char ? get_ignore_noop() : current);
  6334. }
  6335. /*!
  6336. @brief reads a UBJSON string
  6337. This function is either called after reading the 'S' byte explicitly
  6338. indicating a string, or in case of an object key where the 'S' byte can be
  6339. left out.
  6340. @param[out] result created string
  6341. @param[in] get_char whether a new character should be retrieved from the
  6342. input (true, default) or whether the last read
  6343. character should be considered instead
  6344. @return whether string creation completed
  6345. */
  6346. bool get_ubjson_string(string_t& result, const bool get_char = true)
  6347. {
  6348. if (get_char)
  6349. {
  6350. get(); // TODO(niels): may we ignore N here?
  6351. }
  6352. if (JSON_HEDLEY_UNLIKELY(not unexpect_eof(input_format_t::ubjson, "value")))
  6353. {
  6354. return false;
  6355. }
  6356. switch (current)
  6357. {
  6358. case 'U':
  6359. {
  6360. std::uint8_t len;
  6361. return get_number(input_format_t::ubjson, len) and get_string(input_format_t::ubjson, len, result);
  6362. }
  6363. case 'i':
  6364. {
  6365. std::int8_t len;
  6366. return get_number(input_format_t::ubjson, len) and get_string(input_format_t::ubjson, len, result);
  6367. }
  6368. case 'I':
  6369. {
  6370. std::int16_t len;
  6371. return get_number(input_format_t::ubjson, len) and get_string(input_format_t::ubjson, len, result);
  6372. }
  6373. case 'l':
  6374. {
  6375. std::int32_t len;
  6376. return get_number(input_format_t::ubjson, len) and get_string(input_format_t::ubjson, len, result);
  6377. }
  6378. case 'L':
  6379. {
  6380. std::int64_t len;
  6381. return get_number(input_format_t::ubjson, len) and get_string(input_format_t::ubjson, len, result);
  6382. }
  6383. default:
  6384. auto last_token = get_token_string();
  6385. 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")));
  6386. }
  6387. }
  6388. /*!
  6389. @param[out] result determined size
  6390. @return whether size determination completed
  6391. */
  6392. bool get_ubjson_size_value(std::size_t& result)
  6393. {
  6394. switch (get_ignore_noop())
  6395. {
  6396. case 'U':
  6397. {
  6398. std::uint8_t number;
  6399. if (JSON_HEDLEY_UNLIKELY(not get_number(input_format_t::ubjson, number)))
  6400. {
  6401. return false;
  6402. }
  6403. result = static_cast<std::size_t>(number);
  6404. return true;
  6405. }
  6406. case 'i':
  6407. {
  6408. std::int8_t number;
  6409. if (JSON_HEDLEY_UNLIKELY(not get_number(input_format_t::ubjson, number)))
  6410. {
  6411. return false;
  6412. }
  6413. result = static_cast<std::size_t>(number);
  6414. return true;
  6415. }
  6416. case 'I':
  6417. {
  6418. std::int16_t number;
  6419. if (JSON_HEDLEY_UNLIKELY(not get_number(input_format_t::ubjson, number)))
  6420. {
  6421. return false;
  6422. }
  6423. result = static_cast<std::size_t>(number);
  6424. return true;
  6425. }
  6426. case 'l':
  6427. {
  6428. std::int32_t number;
  6429. if (JSON_HEDLEY_UNLIKELY(not get_number(input_format_t::ubjson, number)))
  6430. {
  6431. return false;
  6432. }
  6433. result = static_cast<std::size_t>(number);
  6434. return true;
  6435. }
  6436. case 'L':
  6437. {
  6438. std::int64_t number;
  6439. if (JSON_HEDLEY_UNLIKELY(not get_number(input_format_t::ubjson, number)))
  6440. {
  6441. return false;
  6442. }
  6443. result = static_cast<std::size_t>(number);
  6444. return true;
  6445. }
  6446. default:
  6447. {
  6448. auto last_token = get_token_string();
  6449. 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")));
  6450. }
  6451. }
  6452. }
  6453. /*!
  6454. @brief determine the type and size for a container
  6455. In the optimized UBJSON format, a type and a size can be provided to allow
  6456. for a more compact representation.
  6457. @param[out] result pair of the size and the type
  6458. @return whether pair creation completed
  6459. */
  6460. bool get_ubjson_size_type(std::pair<std::size_t, int>& result)
  6461. {
  6462. result.first = string_t::npos; // size
  6463. result.second = 0; // type
  6464. get_ignore_noop();
  6465. if (current == '$')
  6466. {
  6467. result.second = get(); // must not ignore 'N', because 'N' maybe the type
  6468. if (JSON_HEDLEY_UNLIKELY(not unexpect_eof(input_format_t::ubjson, "type")))
  6469. {
  6470. return false;
  6471. }
  6472. get_ignore_noop();
  6473. if (JSON_HEDLEY_UNLIKELY(current != '#'))
  6474. {
  6475. if (JSON_HEDLEY_UNLIKELY(not unexpect_eof(input_format_t::ubjson, "value")))
  6476. {
  6477. return false;
  6478. }
  6479. auto last_token = get_token_string();
  6480. 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")));
  6481. }
  6482. return get_ubjson_size_value(result.first);
  6483. }
  6484. if (current == '#')
  6485. {
  6486. return get_ubjson_size_value(result.first);
  6487. }
  6488. return true;
  6489. }
  6490. /*!
  6491. @param prefix the previously read or set type prefix
  6492. @return whether value creation completed
  6493. */
  6494. bool get_ubjson_value(const int prefix)
  6495. {
  6496. switch (prefix)
  6497. {
  6498. case std::char_traits<char>::eof(): // EOF
  6499. return unexpect_eof(input_format_t::ubjson, "value");
  6500. case 'T': // true
  6501. return sax->boolean(true);
  6502. case 'F': // false
  6503. return sax->boolean(false);
  6504. case 'Z': // null
  6505. return sax->null();
  6506. case 'U':
  6507. {
  6508. std::uint8_t number;
  6509. return get_number(input_format_t::ubjson, number) and sax->number_unsigned(number);
  6510. }
  6511. case 'i':
  6512. {
  6513. std::int8_t number;
  6514. return get_number(input_format_t::ubjson, number) and sax->number_integer(number);
  6515. }
  6516. case 'I':
  6517. {
  6518. std::int16_t number;
  6519. return get_number(input_format_t::ubjson, number) and sax->number_integer(number);
  6520. }
  6521. case 'l':
  6522. {
  6523. std::int32_t number;
  6524. return get_number(input_format_t::ubjson, number) and sax->number_integer(number);
  6525. }
  6526. case 'L':
  6527. {
  6528. std::int64_t number;
  6529. return get_number(input_format_t::ubjson, number) and sax->number_integer(number);
  6530. }
  6531. case 'd':
  6532. {
  6533. float number;
  6534. return get_number(input_format_t::ubjson, number) and sax->number_float(static_cast<number_float_t>(number), "");
  6535. }
  6536. case 'D':
  6537. {
  6538. double number;
  6539. return get_number(input_format_t::ubjson, number) and sax->number_float(static_cast<number_float_t>(number), "");
  6540. }
  6541. case 'C': // char
  6542. {
  6543. get();
  6544. if (JSON_HEDLEY_UNLIKELY(not unexpect_eof(input_format_t::ubjson, "char")))
  6545. {
  6546. return false;
  6547. }
  6548. if (JSON_HEDLEY_UNLIKELY(current > 127))
  6549. {
  6550. auto last_token = get_token_string();
  6551. 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")));
  6552. }
  6553. string_t s(1, static_cast<char>(current));
  6554. return sax->string(s);
  6555. }
  6556. case 'S': // string
  6557. {
  6558. string_t s;
  6559. return get_ubjson_string(s) and sax->string(s);
  6560. }
  6561. case '[': // array
  6562. return get_ubjson_array();
  6563. case '{': // object
  6564. return get_ubjson_object();
  6565. default: // anything else
  6566. {
  6567. auto last_token = get_token_string();
  6568. 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")));
  6569. }
  6570. }
  6571. }
  6572. /*!
  6573. @return whether array creation completed
  6574. */
  6575. bool get_ubjson_array()
  6576. {
  6577. std::pair<std::size_t, int> size_and_type;
  6578. if (JSON_HEDLEY_UNLIKELY(not get_ubjson_size_type(size_and_type)))
  6579. {
  6580. return false;
  6581. }
  6582. if (size_and_type.first != string_t::npos)
  6583. {
  6584. if (JSON_HEDLEY_UNLIKELY(not sax->start_array(size_and_type.first)))
  6585. {
  6586. return false;
  6587. }
  6588. if (size_and_type.second != 0)
  6589. {
  6590. if (size_and_type.second != 'N')
  6591. {
  6592. for (std::size_t i = 0; i < size_and_type.first; ++i)
  6593. {
  6594. if (JSON_HEDLEY_UNLIKELY(not get_ubjson_value(size_and_type.second)))
  6595. {
  6596. return false;
  6597. }
  6598. }
  6599. }
  6600. }
  6601. else
  6602. {
  6603. for (std::size_t i = 0; i < size_and_type.first; ++i)
  6604. {
  6605. if (JSON_HEDLEY_UNLIKELY(not parse_ubjson_internal()))
  6606. {
  6607. return false;
  6608. }
  6609. }
  6610. }
  6611. }
  6612. else
  6613. {
  6614. if (JSON_HEDLEY_UNLIKELY(not sax->start_array(std::size_t(-1))))
  6615. {
  6616. return false;
  6617. }
  6618. while (current != ']')
  6619. {
  6620. if (JSON_HEDLEY_UNLIKELY(not parse_ubjson_internal(false)))
  6621. {
  6622. return false;
  6623. }
  6624. get_ignore_noop();
  6625. }
  6626. }
  6627. return sax->end_array();
  6628. }
  6629. /*!
  6630. @return whether object creation completed
  6631. */
  6632. bool get_ubjson_object()
  6633. {
  6634. std::pair<std::size_t, int> size_and_type;
  6635. if (JSON_HEDLEY_UNLIKELY(not get_ubjson_size_type(size_and_type)))
  6636. {
  6637. return false;
  6638. }
  6639. string_t key;
  6640. if (size_and_type.first != string_t::npos)
  6641. {
  6642. if (JSON_HEDLEY_UNLIKELY(not sax->start_object(size_and_type.first)))
  6643. {
  6644. return false;
  6645. }
  6646. if (size_and_type.second != 0)
  6647. {
  6648. for (std::size_t i = 0; i < size_and_type.first; ++i)
  6649. {
  6650. if (JSON_HEDLEY_UNLIKELY(not get_ubjson_string(key) or not sax->key(key)))
  6651. {
  6652. return false;
  6653. }
  6654. if (JSON_HEDLEY_UNLIKELY(not get_ubjson_value(size_and_type.second)))
  6655. {
  6656. return false;
  6657. }
  6658. key.clear();
  6659. }
  6660. }
  6661. else
  6662. {
  6663. for (std::size_t i = 0; i < size_and_type.first; ++i)
  6664. {
  6665. if (JSON_HEDLEY_UNLIKELY(not get_ubjson_string(key) or not sax->key(key)))
  6666. {
  6667. return false;
  6668. }
  6669. if (JSON_HEDLEY_UNLIKELY(not parse_ubjson_internal()))
  6670. {
  6671. return false;
  6672. }
  6673. key.clear();
  6674. }
  6675. }
  6676. }
  6677. else
  6678. {
  6679. if (JSON_HEDLEY_UNLIKELY(not sax->start_object(std::size_t(-1))))
  6680. {
  6681. return false;
  6682. }
  6683. while (current != '}')
  6684. {
  6685. if (JSON_HEDLEY_UNLIKELY(not get_ubjson_string(key, false) or not sax->key(key)))
  6686. {
  6687. return false;
  6688. }
  6689. if (JSON_HEDLEY_UNLIKELY(not parse_ubjson_internal()))
  6690. {
  6691. return false;
  6692. }
  6693. get_ignore_noop();
  6694. key.clear();
  6695. }
  6696. }
  6697. return sax->end_object();
  6698. }
  6699. // Note, no reader for UBJSON binary types is implemented because they do
  6700. // not exist
  6701. ///////////////////////
  6702. // Utility functions //
  6703. ///////////////////////
  6704. /*!
  6705. @brief get next character from the input
  6706. This function provides the interface to the used input adapter. It does
  6707. not throw in case the input reached EOF, but returns a -'ve valued
  6708. `std::char_traits<char>::eof()` in that case.
  6709. @return character read from the input
  6710. */
  6711. int get()
  6712. {
  6713. ++chars_read;
  6714. return current = ia.get_character();
  6715. }
  6716. /*!
  6717. @return character read from the input after ignoring all 'N' entries
  6718. */
  6719. int get_ignore_noop()
  6720. {
  6721. do
  6722. {
  6723. get();
  6724. }
  6725. while (current == 'N');
  6726. return current;
  6727. }
  6728. /*
  6729. @brief read a number from the input
  6730. @tparam NumberType the type of the number
  6731. @param[in] format the current format (for diagnostics)
  6732. @param[out] result number of type @a NumberType
  6733. @return whether conversion completed
  6734. @note This function needs to respect the system's endianess, because
  6735. bytes in CBOR, MessagePack, and UBJSON are stored in network order
  6736. (big endian) and therefore need reordering on little endian systems.
  6737. */
  6738. template<typename NumberType, bool InputIsLittleEndian = false>
  6739. bool get_number(const input_format_t format, NumberType& result)
  6740. {
  6741. // step 1: read input into array with system's byte order
  6742. std::array<std::uint8_t, sizeof(NumberType)> vec;
  6743. for (std::size_t i = 0; i < sizeof(NumberType); ++i)
  6744. {
  6745. get();
  6746. if (JSON_HEDLEY_UNLIKELY(not unexpect_eof(format, "number")))
  6747. {
  6748. return false;
  6749. }
  6750. // reverse byte order prior to conversion if necessary
  6751. if (is_little_endian != InputIsLittleEndian)
  6752. {
  6753. vec[sizeof(NumberType) - i - 1] = static_cast<std::uint8_t>(current);
  6754. }
  6755. else
  6756. {
  6757. vec[i] = static_cast<std::uint8_t>(current); // LCOV_EXCL_LINE
  6758. }
  6759. }
  6760. // step 2: convert array into number of type T and return
  6761. std::memcpy(&result, vec.data(), sizeof(NumberType));
  6762. return true;
  6763. }
  6764. /*!
  6765. @brief create a string by reading characters from the input
  6766. @tparam NumberType the type of the number
  6767. @param[in] format the current format (for diagnostics)
  6768. @param[in] len number of characters to read
  6769. @param[out] result string created by reading @a len bytes
  6770. @return whether string creation completed
  6771. @note We can not reserve @a len bytes for the result, because @a len
  6772. may be too large. Usually, @ref unexpect_eof() detects the end of
  6773. the input before we run out of string memory.
  6774. */
  6775. template<typename NumberType>
  6776. bool get_string(const input_format_t format,
  6777. const NumberType len,
  6778. string_t& result)
  6779. {
  6780. bool success = true;
  6781. std::generate_n(std::back_inserter(result), len, [this, &success, &format]()
  6782. {
  6783. get();
  6784. if (JSON_HEDLEY_UNLIKELY(not unexpect_eof(format, "string")))
  6785. {
  6786. success = false;
  6787. }
  6788. return static_cast<char>(current);
  6789. });
  6790. return success;
  6791. }
  6792. /*!
  6793. @brief create a byte array by reading bytes from the input
  6794. @tparam NumberType the type of the number
  6795. @param[in] format the current format (for diagnostics)
  6796. @param[in] len number of bytes to read
  6797. @param[out] result byte array created by reading @a len bytes
  6798. @return whether byte array creation completed
  6799. @note We can not reserve @a len bytes for the result, because @a len
  6800. may be too large. Usually, @ref unexpect_eof() detects the end of
  6801. the input before we run out of memory.
  6802. */
  6803. template<typename NumberType>
  6804. bool get_binary(const input_format_t format,
  6805. const NumberType len,
  6806. internal_binary_t& result)
  6807. {
  6808. bool success = true;
  6809. std::generate_n(std::back_inserter(result), len, [this, &success, &format]()
  6810. {
  6811. get();
  6812. if (JSON_HEDLEY_UNLIKELY(not unexpect_eof(format, "binary")))
  6813. {
  6814. success = false;
  6815. }
  6816. return static_cast<std::uint8_t>(current);
  6817. });
  6818. return success;
  6819. }
  6820. /*!
  6821. @param[in] format the current format (for diagnostics)
  6822. @param[in] context further context information (for diagnostics)
  6823. @return whether the last read character is not EOF
  6824. */
  6825. JSON_HEDLEY_NON_NULL(3)
  6826. bool unexpect_eof(const input_format_t format, const char* context) const
  6827. {
  6828. if (JSON_HEDLEY_UNLIKELY(current == std::char_traits<char>::eof()))
  6829. {
  6830. return sax->parse_error(chars_read, "<end of file>",
  6831. parse_error::create(110, chars_read, exception_message(format, "unexpected end of input", context)));
  6832. }
  6833. return true;
  6834. }
  6835. /*!
  6836. @return a string representation of the last read byte
  6837. */
  6838. std::string get_token_string() const
  6839. {
  6840. std::array<char, 3> cr{{}};
  6841. (std::snprintf)(cr.data(), cr.size(), "%.2hhX", static_cast<unsigned char>(current));
  6842. return std::string{cr.data()};
  6843. }
  6844. /*!
  6845. @param[in] format the current format
  6846. @param[in] detail a detailed error message
  6847. @param[in] context further context information
  6848. @return a message string to use in the parse_error exceptions
  6849. */
  6850. std::string exception_message(const input_format_t format,
  6851. const std::string& detail,
  6852. const std::string& context) const
  6853. {
  6854. std::string error_msg = "syntax error while parsing ";
  6855. switch (format)
  6856. {
  6857. case input_format_t::cbor:
  6858. error_msg += "CBOR";
  6859. break;
  6860. case input_format_t::msgpack:
  6861. error_msg += "MessagePack";
  6862. break;
  6863. case input_format_t::ubjson:
  6864. error_msg += "UBJSON";
  6865. break;
  6866. case input_format_t::bson:
  6867. error_msg += "BSON";
  6868. break;
  6869. default: // LCOV_EXCL_LINE
  6870. assert(false); // LCOV_EXCL_LINE
  6871. }
  6872. return error_msg + " " + context + ": " + detail;
  6873. }
  6874. private:
  6875. /// input adapter
  6876. InputAdapterType ia;
  6877. /// the current character
  6878. int current = std::char_traits<char>::eof();
  6879. /// the number of characters read
  6880. std::size_t chars_read = 0;
  6881. /// whether we can assume little endianess
  6882. const bool is_little_endian = little_endianess();
  6883. /// the SAX parser
  6884. json_sax_t* sax = nullptr;
  6885. };
  6886. } // namespace detail
  6887. } // namespace nlohmann
  6888. // #include <nlohmann/detail/input/input_adapters.hpp>
  6889. // #include <nlohmann/detail/input/lexer.hpp>
  6890. #include <array> // array
  6891. #include <clocale> // localeconv
  6892. #include <cstddef> // size_t
  6893. #include <cstdio> // snprintf
  6894. #include <cstdlib> // strtof, strtod, strtold, strtoll, strtoull
  6895. #include <initializer_list> // initializer_list
  6896. #include <string> // char_traits, string
  6897. #include <utility> // move
  6898. #include <vector> // vector
  6899. // #include <nlohmann/detail/input/input_adapters.hpp>
  6900. // #include <nlohmann/detail/input/position_t.hpp>
  6901. // #include <nlohmann/detail/macro_scope.hpp>
  6902. namespace nlohmann
  6903. {
  6904. namespace detail
  6905. {
  6906. ///////////
  6907. // lexer //
  6908. ///////////
  6909. template<typename BasicJsonType>
  6910. class lexer_base
  6911. {
  6912. public:
  6913. /// token types for the parser
  6914. enum class token_type
  6915. {
  6916. uninitialized, ///< indicating the scanner is uninitialized
  6917. literal_true, ///< the `true` literal
  6918. literal_false, ///< the `false` literal
  6919. literal_null, ///< the `null` literal
  6920. value_string, ///< a string -- use get_string() for actual value
  6921. value_unsigned, ///< an unsigned integer -- use get_number_unsigned() for actual value
  6922. value_integer, ///< a signed integer -- use get_number_integer() for actual value
  6923. value_float, ///< an floating point number -- use get_number_float() for actual value
  6924. begin_array, ///< the character for array begin `[`
  6925. begin_object, ///< the character for object begin `{`
  6926. end_array, ///< the character for array end `]`
  6927. end_object, ///< the character for object end `}`
  6928. name_separator, ///< the name separator `:`
  6929. value_separator, ///< the value separator `,`
  6930. parse_error, ///< indicating a parse error
  6931. end_of_input, ///< indicating the end of the input buffer
  6932. literal_or_value ///< a literal or the begin of a value (only for diagnostics)
  6933. };
  6934. /// return name of values of type token_type (only used for errors)
  6935. JSON_HEDLEY_RETURNS_NON_NULL
  6936. JSON_HEDLEY_CONST
  6937. static const char* token_type_name(const token_type t) noexcept
  6938. {
  6939. switch (t)
  6940. {
  6941. case token_type::uninitialized:
  6942. return "<uninitialized>";
  6943. case token_type::literal_true:
  6944. return "true literal";
  6945. case token_type::literal_false:
  6946. return "false literal";
  6947. case token_type::literal_null:
  6948. return "null literal";
  6949. case token_type::value_string:
  6950. return "string literal";
  6951. case token_type::value_unsigned:
  6952. case token_type::value_integer:
  6953. case token_type::value_float:
  6954. return "number literal";
  6955. case token_type::begin_array:
  6956. return "'['";
  6957. case token_type::begin_object:
  6958. return "'{'";
  6959. case token_type::end_array:
  6960. return "']'";
  6961. case token_type::end_object:
  6962. return "'}'";
  6963. case token_type::name_separator:
  6964. return "':'";
  6965. case token_type::value_separator:
  6966. return "','";
  6967. case token_type::parse_error:
  6968. return "<parse error>";
  6969. case token_type::end_of_input:
  6970. return "end of input";
  6971. case token_type::literal_or_value:
  6972. return "'[', '{', or a literal";
  6973. // LCOV_EXCL_START
  6974. default: // catch non-enum values
  6975. return "unknown token";
  6976. // LCOV_EXCL_STOP
  6977. }
  6978. }
  6979. };
  6980. /*!
  6981. @brief lexical analysis
  6982. This class organizes the lexical analysis during JSON deserialization.
  6983. */
  6984. template<typename BasicJsonType, typename InputAdapterType>
  6985. class lexer : public lexer_base<BasicJsonType>
  6986. {
  6987. using number_integer_t = typename BasicJsonType::number_integer_t;
  6988. using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
  6989. using number_float_t = typename BasicJsonType::number_float_t;
  6990. using string_t = typename BasicJsonType::string_t;
  6991. public:
  6992. using token_type = typename lexer_base<BasicJsonType>::token_type;
  6993. explicit lexer(InputAdapterType&& adapter)
  6994. : ia(std::move(adapter)), decimal_point_char(get_decimal_point()) {}
  6995. // delete because of pointer members
  6996. lexer(const lexer&) = delete;
  6997. lexer(lexer&&) = default;
  6998. lexer& operator=(lexer&) = delete;
  6999. lexer& operator=(lexer&&) = default;
  7000. ~lexer() = default;
  7001. private:
  7002. /////////////////////
  7003. // locales
  7004. /////////////////////
  7005. /// return the locale-dependent decimal point
  7006. JSON_HEDLEY_PURE
  7007. static char get_decimal_point() noexcept
  7008. {
  7009. const auto loc = localeconv();
  7010. assert(loc != nullptr);
  7011. return (loc->decimal_point == nullptr) ? '.' : *(loc->decimal_point);
  7012. }
  7013. /////////////////////
  7014. // scan functions
  7015. /////////////////////
  7016. /*!
  7017. @brief get codepoint from 4 hex characters following `\u`
  7018. For input "\u c1 c2 c3 c4" the codepoint is:
  7019. (c1 * 0x1000) + (c2 * 0x0100) + (c3 * 0x0010) + c4
  7020. = (c1 << 12) + (c2 << 8) + (c3 << 4) + (c4 << 0)
  7021. Furthermore, the possible characters '0'..'9', 'A'..'F', and 'a'..'f'
  7022. must be converted to the integers 0x0..0x9, 0xA..0xF, 0xA..0xF, resp. The
  7023. conversion is done by subtracting the offset (0x30, 0x37, and 0x57)
  7024. between the ASCII value of the character and the desired integer value.
  7025. @return codepoint (0x0000..0xFFFF) or -1 in case of an error (e.g. EOF or
  7026. non-hex character)
  7027. */
  7028. int get_codepoint()
  7029. {
  7030. // this function only makes sense after reading `\u`
  7031. assert(current == 'u');
  7032. int codepoint = 0;
  7033. const auto factors = { 12u, 8u, 4u, 0u };
  7034. for (const auto factor : factors)
  7035. {
  7036. get();
  7037. if (current >= '0' and current <= '9')
  7038. {
  7039. codepoint += static_cast<int>((static_cast<unsigned int>(current) - 0x30u) << factor);
  7040. }
  7041. else if (current >= 'A' and current <= 'F')
  7042. {
  7043. codepoint += static_cast<int>((static_cast<unsigned int>(current) - 0x37u) << factor);
  7044. }
  7045. else if (current >= 'a' and current <= 'f')
  7046. {
  7047. codepoint += static_cast<int>((static_cast<unsigned int>(current) - 0x57u) << factor);
  7048. }
  7049. else
  7050. {
  7051. return -1;
  7052. }
  7053. }
  7054. assert(0x0000 <= codepoint and codepoint <= 0xFFFF);
  7055. return codepoint;
  7056. }
  7057. /*!
  7058. @brief check if the next byte(s) are inside a given range
  7059. Adds the current byte and, for each passed range, reads a new byte and
  7060. checks if it is inside the range. If a violation was detected, set up an
  7061. error message and return false. Otherwise, return true.
  7062. @param[in] ranges list of integers; interpreted as list of pairs of
  7063. inclusive lower and upper bound, respectively
  7064. @pre The passed list @a ranges must have 2, 4, or 6 elements; that is,
  7065. 1, 2, or 3 pairs. This precondition is enforced by an assertion.
  7066. @return true if and only if no range violation was detected
  7067. */
  7068. bool next_byte_in_range(std::initializer_list<int> ranges)
  7069. {
  7070. assert(ranges.size() == 2 or ranges.size() == 4 or ranges.size() == 6);
  7071. add(current);
  7072. for (auto range = ranges.begin(); range != ranges.end(); ++range)
  7073. {
  7074. get();
  7075. if (JSON_HEDLEY_LIKELY(*range <= current and current <= *(++range)))
  7076. {
  7077. add(current);
  7078. }
  7079. else
  7080. {
  7081. error_message = "invalid string: ill-formed UTF-8 byte";
  7082. return false;
  7083. }
  7084. }
  7085. return true;
  7086. }
  7087. /*!
  7088. @brief scan a string literal
  7089. This function scans a string according to Sect. 7 of RFC 7159. While
  7090. scanning, bytes are escaped and copied into buffer token_buffer. Then the
  7091. function returns successfully, token_buffer is *not* null-terminated (as it
  7092. may contain \0 bytes), and token_buffer.size() is the number of bytes in the
  7093. string.
  7094. @return token_type::value_string if string could be successfully scanned,
  7095. token_type::parse_error otherwise
  7096. @note In case of errors, variable error_message contains a textual
  7097. description.
  7098. */
  7099. token_type scan_string()
  7100. {
  7101. // reset token_buffer (ignore opening quote)
  7102. reset();
  7103. // we entered the function by reading an open quote
  7104. assert(current == '\"');
  7105. while (true)
  7106. {
  7107. // get next character
  7108. switch (get())
  7109. {
  7110. // end of file while parsing string
  7111. case std::char_traits<char>::eof():
  7112. {
  7113. error_message = "invalid string: missing closing quote";
  7114. return token_type::parse_error;
  7115. }
  7116. // closing quote
  7117. case '\"':
  7118. {
  7119. return token_type::value_string;
  7120. }
  7121. // escapes
  7122. case '\\':
  7123. {
  7124. switch (get())
  7125. {
  7126. // quotation mark
  7127. case '\"':
  7128. add('\"');
  7129. break;
  7130. // reverse solidus
  7131. case '\\':
  7132. add('\\');
  7133. break;
  7134. // solidus
  7135. case '/':
  7136. add('/');
  7137. break;
  7138. // backspace
  7139. case 'b':
  7140. add('\b');
  7141. break;
  7142. // form feed
  7143. case 'f':
  7144. add('\f');
  7145. break;
  7146. // line feed
  7147. case 'n':
  7148. add('\n');
  7149. break;
  7150. // carriage return
  7151. case 'r':
  7152. add('\r');
  7153. break;
  7154. // tab
  7155. case 't':
  7156. add('\t');
  7157. break;
  7158. // unicode escapes
  7159. case 'u':
  7160. {
  7161. const int codepoint1 = get_codepoint();
  7162. int codepoint = codepoint1; // start with codepoint1
  7163. if (JSON_HEDLEY_UNLIKELY(codepoint1 == -1))
  7164. {
  7165. error_message = "invalid string: '\\u' must be followed by 4 hex digits";
  7166. return token_type::parse_error;
  7167. }
  7168. // check if code point is a high surrogate
  7169. if (0xD800 <= codepoint1 and codepoint1 <= 0xDBFF)
  7170. {
  7171. // expect next \uxxxx entry
  7172. if (JSON_HEDLEY_LIKELY(get() == '\\' and get() == 'u'))
  7173. {
  7174. const int codepoint2 = get_codepoint();
  7175. if (JSON_HEDLEY_UNLIKELY(codepoint2 == -1))
  7176. {
  7177. error_message = "invalid string: '\\u' must be followed by 4 hex digits";
  7178. return token_type::parse_error;
  7179. }
  7180. // check if codepoint2 is a low surrogate
  7181. if (JSON_HEDLEY_LIKELY(0xDC00 <= codepoint2 and codepoint2 <= 0xDFFF))
  7182. {
  7183. // overwrite codepoint
  7184. codepoint = static_cast<int>(
  7185. // high surrogate occupies the most significant 22 bits
  7186. (static_cast<unsigned int>(codepoint1) << 10u)
  7187. // low surrogate occupies the least significant 15 bits
  7188. + static_cast<unsigned int>(codepoint2)
  7189. // there is still the 0xD800, 0xDC00 and 0x10000 noise
  7190. // in the result so we have to subtract with:
  7191. // (0xD800 << 10) + DC00 - 0x10000 = 0x35FDC00
  7192. - 0x35FDC00u);
  7193. }
  7194. else
  7195. {
  7196. error_message = "invalid string: surrogate U+D800..U+DBFF must be followed by U+DC00..U+DFFF";
  7197. return token_type::parse_error;
  7198. }
  7199. }
  7200. else
  7201. {
  7202. error_message = "invalid string: surrogate U+D800..U+DBFF must be followed by U+DC00..U+DFFF";
  7203. return token_type::parse_error;
  7204. }
  7205. }
  7206. else
  7207. {
  7208. if (JSON_HEDLEY_UNLIKELY(0xDC00 <= codepoint1 and codepoint1 <= 0xDFFF))
  7209. {
  7210. error_message = "invalid string: surrogate U+DC00..U+DFFF must follow U+D800..U+DBFF";
  7211. return token_type::parse_error;
  7212. }
  7213. }
  7214. // result of the above calculation yields a proper codepoint
  7215. assert(0x00 <= codepoint and codepoint <= 0x10FFFF);
  7216. // translate codepoint into bytes
  7217. if (codepoint < 0x80)
  7218. {
  7219. // 1-byte characters: 0xxxxxxx (ASCII)
  7220. add(codepoint);
  7221. }
  7222. else if (codepoint <= 0x7FF)
  7223. {
  7224. // 2-byte characters: 110xxxxx 10xxxxxx
  7225. add(static_cast<int>(0xC0u | (static_cast<unsigned int>(codepoint) >> 6u)));
  7226. add(static_cast<int>(0x80u | (static_cast<unsigned int>(codepoint) & 0x3Fu)));
  7227. }
  7228. else if (codepoint <= 0xFFFF)
  7229. {
  7230. // 3-byte characters: 1110xxxx 10xxxxxx 10xxxxxx
  7231. add(static_cast<int>(0xE0u | (static_cast<unsigned int>(codepoint) >> 12u)));
  7232. add(static_cast<int>(0x80u | ((static_cast<unsigned int>(codepoint) >> 6u) & 0x3Fu)));
  7233. add(static_cast<int>(0x80u | (static_cast<unsigned int>(codepoint) & 0x3Fu)));
  7234. }
  7235. else
  7236. {
  7237. // 4-byte characters: 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
  7238. add(static_cast<int>(0xF0u | (static_cast<unsigned int>(codepoint) >> 18u)));
  7239. add(static_cast<int>(0x80u | ((static_cast<unsigned int>(codepoint) >> 12u) & 0x3Fu)));
  7240. add(static_cast<int>(0x80u | ((static_cast<unsigned int>(codepoint) >> 6u) & 0x3Fu)));
  7241. add(static_cast<int>(0x80u | (static_cast<unsigned int>(codepoint) & 0x3Fu)));
  7242. }
  7243. break;
  7244. }
  7245. // other characters after escape
  7246. default:
  7247. error_message = "invalid string: forbidden character after backslash";
  7248. return token_type::parse_error;
  7249. }
  7250. break;
  7251. }
  7252. // invalid control characters
  7253. case 0x00:
  7254. {
  7255. error_message = "invalid string: control character U+0000 (NUL) must be escaped to \\u0000";
  7256. return token_type::parse_error;
  7257. }
  7258. case 0x01:
  7259. {
  7260. error_message = "invalid string: control character U+0001 (SOH) must be escaped to \\u0001";
  7261. return token_type::parse_error;
  7262. }
  7263. case 0x02:
  7264. {
  7265. error_message = "invalid string: control character U+0002 (STX) must be escaped to \\u0002";
  7266. return token_type::parse_error;
  7267. }
  7268. case 0x03:
  7269. {
  7270. error_message = "invalid string: control character U+0003 (ETX) must be escaped to \\u0003";
  7271. return token_type::parse_error;
  7272. }
  7273. case 0x04:
  7274. {
  7275. error_message = "invalid string: control character U+0004 (EOT) must be escaped to \\u0004";
  7276. return token_type::parse_error;
  7277. }
  7278. case 0x05:
  7279. {
  7280. error_message = "invalid string: control character U+0005 (ENQ) must be escaped to \\u0005";
  7281. return token_type::parse_error;
  7282. }
  7283. case 0x06:
  7284. {
  7285. error_message = "invalid string: control character U+0006 (ACK) must be escaped to \\u0006";
  7286. return token_type::parse_error;
  7287. }
  7288. case 0x07:
  7289. {
  7290. error_message = "invalid string: control character U+0007 (BEL) must be escaped to \\u0007";
  7291. return token_type::parse_error;
  7292. }
  7293. case 0x08:
  7294. {
  7295. error_message = "invalid string: control character U+0008 (BS) must be escaped to \\u0008 or \\b";
  7296. return token_type::parse_error;
  7297. }
  7298. case 0x09:
  7299. {
  7300. error_message = "invalid string: control character U+0009 (HT) must be escaped to \\u0009 or \\t";
  7301. return token_type::parse_error;
  7302. }
  7303. case 0x0A:
  7304. {
  7305. error_message = "invalid string: control character U+000A (LF) must be escaped to \\u000A or \\n";
  7306. return token_type::parse_error;
  7307. }
  7308. case 0x0B:
  7309. {
  7310. error_message = "invalid string: control character U+000B (VT) must be escaped to \\u000B";
  7311. return token_type::parse_error;
  7312. }
  7313. case 0x0C:
  7314. {
  7315. error_message = "invalid string: control character U+000C (FF) must be escaped to \\u000C or \\f";
  7316. return token_type::parse_error;
  7317. }
  7318. case 0x0D:
  7319. {
  7320. error_message = "invalid string: control character U+000D (CR) must be escaped to \\u000D or \\r";
  7321. return token_type::parse_error;
  7322. }
  7323. case 0x0E:
  7324. {
  7325. error_message = "invalid string: control character U+000E (SO) must be escaped to \\u000E";
  7326. return token_type::parse_error;
  7327. }
  7328. case 0x0F:
  7329. {
  7330. error_message = "invalid string: control character U+000F (SI) must be escaped to \\u000F";
  7331. return token_type::parse_error;
  7332. }
  7333. case 0x10:
  7334. {
  7335. error_message = "invalid string: control character U+0010 (DLE) must be escaped to \\u0010";
  7336. return token_type::parse_error;
  7337. }
  7338. case 0x11:
  7339. {
  7340. error_message = "invalid string: control character U+0011 (DC1) must be escaped to \\u0011";
  7341. return token_type::parse_error;
  7342. }
  7343. case 0x12:
  7344. {
  7345. error_message = "invalid string: control character U+0012 (DC2) must be escaped to \\u0012";
  7346. return token_type::parse_error;
  7347. }
  7348. case 0x13:
  7349. {
  7350. error_message = "invalid string: control character U+0013 (DC3) must be escaped to \\u0013";
  7351. return token_type::parse_error;
  7352. }
  7353. case 0x14:
  7354. {
  7355. error_message = "invalid string: control character U+0014 (DC4) must be escaped to \\u0014";
  7356. return token_type::parse_error;
  7357. }
  7358. case 0x15:
  7359. {
  7360. error_message = "invalid string: control character U+0015 (NAK) must be escaped to \\u0015";
  7361. return token_type::parse_error;
  7362. }
  7363. case 0x16:
  7364. {
  7365. error_message = "invalid string: control character U+0016 (SYN) must be escaped to \\u0016";
  7366. return token_type::parse_error;
  7367. }
  7368. case 0x17:
  7369. {
  7370. error_message = "invalid string: control character U+0017 (ETB) must be escaped to \\u0017";
  7371. return token_type::parse_error;
  7372. }
  7373. case 0x18:
  7374. {
  7375. error_message = "invalid string: control character U+0018 (CAN) must be escaped to \\u0018";
  7376. return token_type::parse_error;
  7377. }
  7378. case 0x19:
  7379. {
  7380. error_message = "invalid string: control character U+0019 (EM) must be escaped to \\u0019";
  7381. return token_type::parse_error;
  7382. }
  7383. case 0x1A:
  7384. {
  7385. error_message = "invalid string: control character U+001A (SUB) must be escaped to \\u001A";
  7386. return token_type::parse_error;
  7387. }
  7388. case 0x1B:
  7389. {
  7390. error_message = "invalid string: control character U+001B (ESC) must be escaped to \\u001B";
  7391. return token_type::parse_error;
  7392. }
  7393. case 0x1C:
  7394. {
  7395. error_message = "invalid string: control character U+001C (FS) must be escaped to \\u001C";
  7396. return token_type::parse_error;
  7397. }
  7398. case 0x1D:
  7399. {
  7400. error_message = "invalid string: control character U+001D (GS) must be escaped to \\u001D";
  7401. return token_type::parse_error;
  7402. }
  7403. case 0x1E:
  7404. {
  7405. error_message = "invalid string: control character U+001E (RS) must be escaped to \\u001E";
  7406. return token_type::parse_error;
  7407. }
  7408. case 0x1F:
  7409. {
  7410. error_message = "invalid string: control character U+001F (US) must be escaped to \\u001F";
  7411. return token_type::parse_error;
  7412. }
  7413. // U+0020..U+007F (except U+0022 (quote) and U+005C (backspace))
  7414. case 0x20:
  7415. case 0x21:
  7416. case 0x23:
  7417. case 0x24:
  7418. case 0x25:
  7419. case 0x26:
  7420. case 0x27:
  7421. case 0x28:
  7422. case 0x29:
  7423. case 0x2A:
  7424. case 0x2B:
  7425. case 0x2C:
  7426. case 0x2D:
  7427. case 0x2E:
  7428. case 0x2F:
  7429. case 0x30:
  7430. case 0x31:
  7431. case 0x32:
  7432. case 0x33:
  7433. case 0x34:
  7434. case 0x35:
  7435. case 0x36:
  7436. case 0x37:
  7437. case 0x38:
  7438. case 0x39:
  7439. case 0x3A:
  7440. case 0x3B:
  7441. case 0x3C:
  7442. case 0x3D:
  7443. case 0x3E:
  7444. case 0x3F:
  7445. case 0x40:
  7446. case 0x41:
  7447. case 0x42:
  7448. case 0x43:
  7449. case 0x44:
  7450. case 0x45:
  7451. case 0x46:
  7452. case 0x47:
  7453. case 0x48:
  7454. case 0x49:
  7455. case 0x4A:
  7456. case 0x4B:
  7457. case 0x4C:
  7458. case 0x4D:
  7459. case 0x4E:
  7460. case 0x4F:
  7461. case 0x50:
  7462. case 0x51:
  7463. case 0x52:
  7464. case 0x53:
  7465. case 0x54:
  7466. case 0x55:
  7467. case 0x56:
  7468. case 0x57:
  7469. case 0x58:
  7470. case 0x59:
  7471. case 0x5A:
  7472. case 0x5B:
  7473. case 0x5D:
  7474. case 0x5E:
  7475. case 0x5F:
  7476. case 0x60:
  7477. case 0x61:
  7478. case 0x62:
  7479. case 0x63:
  7480. case 0x64:
  7481. case 0x65:
  7482. case 0x66:
  7483. case 0x67:
  7484. case 0x68:
  7485. case 0x69:
  7486. case 0x6A:
  7487. case 0x6B:
  7488. case 0x6C:
  7489. case 0x6D:
  7490. case 0x6E:
  7491. case 0x6F:
  7492. case 0x70:
  7493. case 0x71:
  7494. case 0x72:
  7495. case 0x73:
  7496. case 0x74:
  7497. case 0x75:
  7498. case 0x76:
  7499. case 0x77:
  7500. case 0x78:
  7501. case 0x79:
  7502. case 0x7A:
  7503. case 0x7B:
  7504. case 0x7C:
  7505. case 0x7D:
  7506. case 0x7E:
  7507. case 0x7F:
  7508. {
  7509. add(current);
  7510. break;
  7511. }
  7512. // U+0080..U+07FF: bytes C2..DF 80..BF
  7513. case 0xC2:
  7514. case 0xC3:
  7515. case 0xC4:
  7516. case 0xC5:
  7517. case 0xC6:
  7518. case 0xC7:
  7519. case 0xC8:
  7520. case 0xC9:
  7521. case 0xCA:
  7522. case 0xCB:
  7523. case 0xCC:
  7524. case 0xCD:
  7525. case 0xCE:
  7526. case 0xCF:
  7527. case 0xD0:
  7528. case 0xD1:
  7529. case 0xD2:
  7530. case 0xD3:
  7531. case 0xD4:
  7532. case 0xD5:
  7533. case 0xD6:
  7534. case 0xD7:
  7535. case 0xD8:
  7536. case 0xD9:
  7537. case 0xDA:
  7538. case 0xDB:
  7539. case 0xDC:
  7540. case 0xDD:
  7541. case 0xDE:
  7542. case 0xDF:
  7543. {
  7544. if (JSON_HEDLEY_UNLIKELY(not next_byte_in_range({0x80, 0xBF})))
  7545. {
  7546. return token_type::parse_error;
  7547. }
  7548. break;
  7549. }
  7550. // U+0800..U+0FFF: bytes E0 A0..BF 80..BF
  7551. case 0xE0:
  7552. {
  7553. if (JSON_HEDLEY_UNLIKELY(not (next_byte_in_range({0xA0, 0xBF, 0x80, 0xBF}))))
  7554. {
  7555. return token_type::parse_error;
  7556. }
  7557. break;
  7558. }
  7559. // U+1000..U+CFFF: bytes E1..EC 80..BF 80..BF
  7560. // U+E000..U+FFFF: bytes EE..EF 80..BF 80..BF
  7561. case 0xE1:
  7562. case 0xE2:
  7563. case 0xE3:
  7564. case 0xE4:
  7565. case 0xE5:
  7566. case 0xE6:
  7567. case 0xE7:
  7568. case 0xE8:
  7569. case 0xE9:
  7570. case 0xEA:
  7571. case 0xEB:
  7572. case 0xEC:
  7573. case 0xEE:
  7574. case 0xEF:
  7575. {
  7576. if (JSON_HEDLEY_UNLIKELY(not (next_byte_in_range({0x80, 0xBF, 0x80, 0xBF}))))
  7577. {
  7578. return token_type::parse_error;
  7579. }
  7580. break;
  7581. }
  7582. // U+D000..U+D7FF: bytes ED 80..9F 80..BF
  7583. case 0xED:
  7584. {
  7585. if (JSON_HEDLEY_UNLIKELY(not (next_byte_in_range({0x80, 0x9F, 0x80, 0xBF}))))
  7586. {
  7587. return token_type::parse_error;
  7588. }
  7589. break;
  7590. }
  7591. // U+10000..U+3FFFF F0 90..BF 80..BF 80..BF
  7592. case 0xF0:
  7593. {
  7594. if (JSON_HEDLEY_UNLIKELY(not (next_byte_in_range({0x90, 0xBF, 0x80, 0xBF, 0x80, 0xBF}))))
  7595. {
  7596. return token_type::parse_error;
  7597. }
  7598. break;
  7599. }
  7600. // U+40000..U+FFFFF F1..F3 80..BF 80..BF 80..BF
  7601. case 0xF1:
  7602. case 0xF2:
  7603. case 0xF3:
  7604. {
  7605. if (JSON_HEDLEY_UNLIKELY(not (next_byte_in_range({0x80, 0xBF, 0x80, 0xBF, 0x80, 0xBF}))))
  7606. {
  7607. return token_type::parse_error;
  7608. }
  7609. break;
  7610. }
  7611. // U+100000..U+10FFFF F4 80..8F 80..BF 80..BF
  7612. case 0xF4:
  7613. {
  7614. if (JSON_HEDLEY_UNLIKELY(not (next_byte_in_range({0x80, 0x8F, 0x80, 0xBF, 0x80, 0xBF}))))
  7615. {
  7616. return token_type::parse_error;
  7617. }
  7618. break;
  7619. }
  7620. // remaining bytes (80..C1 and F5..FF) are ill-formed
  7621. default:
  7622. {
  7623. error_message = "invalid string: ill-formed UTF-8 byte";
  7624. return token_type::parse_error;
  7625. }
  7626. }
  7627. }
  7628. }
  7629. JSON_HEDLEY_NON_NULL(2)
  7630. static void strtof(float& f, const char* str, char** endptr) noexcept
  7631. {
  7632. f = std::strtof(str, endptr);
  7633. }
  7634. JSON_HEDLEY_NON_NULL(2)
  7635. static void strtof(double& f, const char* str, char** endptr) noexcept
  7636. {
  7637. f = std::strtod(str, endptr);
  7638. }
  7639. JSON_HEDLEY_NON_NULL(2)
  7640. static void strtof(long double& f, const char* str, char** endptr) noexcept
  7641. {
  7642. f = std::strtold(str, endptr);
  7643. }
  7644. /*!
  7645. @brief scan a number literal
  7646. This function scans a string according to Sect. 6 of RFC 7159.
  7647. The function is realized with a deterministic finite state machine derived
  7648. from the grammar described in RFC 7159. Starting in state "init", the
  7649. input is read and used to determined the next state. Only state "done"
  7650. accepts the number. State "error" is a trap state to model errors. In the
  7651. table below, "anything" means any character but the ones listed before.
  7652. state | 0 | 1-9 | e E | + | - | . | anything
  7653. ---------|----------|----------|----------|---------|---------|----------|-----------
  7654. init | zero | any1 | [error] | [error] | minus | [error] | [error]
  7655. minus | zero | any1 | [error] | [error] | [error] | [error] | [error]
  7656. zero | done | done | exponent | done | done | decimal1 | done
  7657. any1 | any1 | any1 | exponent | done | done | decimal1 | done
  7658. decimal1 | decimal2 | decimal2 | [error] | [error] | [error] | [error] | [error]
  7659. decimal2 | decimal2 | decimal2 | exponent | done | done | done | done
  7660. exponent | any2 | any2 | [error] | sign | sign | [error] | [error]
  7661. sign | any2 | any2 | [error] | [error] | [error] | [error] | [error]
  7662. any2 | any2 | any2 | done | done | done | done | done
  7663. The state machine is realized with one label per state (prefixed with
  7664. "scan_number_") and `goto` statements between them. The state machine
  7665. contains cycles, but any cycle can be left when EOF is read. Therefore,
  7666. the function is guaranteed to terminate.
  7667. During scanning, the read bytes are stored in token_buffer. This string is
  7668. then converted to a signed integer, an unsigned integer, or a
  7669. floating-point number.
  7670. @return token_type::value_unsigned, token_type::value_integer, or
  7671. token_type::value_float if number could be successfully scanned,
  7672. token_type::parse_error otherwise
  7673. @note The scanner is independent of the current locale. Internally, the
  7674. locale's decimal point is used instead of `.` to work with the
  7675. locale-dependent converters.
  7676. */
  7677. token_type scan_number() // lgtm [cpp/use-of-goto]
  7678. {
  7679. // reset token_buffer to store the number's bytes
  7680. reset();
  7681. // the type of the parsed number; initially set to unsigned; will be
  7682. // changed if minus sign, decimal point or exponent is read
  7683. token_type number_type = token_type::value_unsigned;
  7684. // state (init): we just found out we need to scan a number
  7685. switch (current)
  7686. {
  7687. case '-':
  7688. {
  7689. add(current);
  7690. goto scan_number_minus;
  7691. }
  7692. case '0':
  7693. {
  7694. add(current);
  7695. goto scan_number_zero;
  7696. }
  7697. case '1':
  7698. case '2':
  7699. case '3':
  7700. case '4':
  7701. case '5':
  7702. case '6':
  7703. case '7':
  7704. case '8':
  7705. case '9':
  7706. {
  7707. add(current);
  7708. goto scan_number_any1;
  7709. }
  7710. // all other characters are rejected outside scan_number()
  7711. default: // LCOV_EXCL_LINE
  7712. assert(false); // LCOV_EXCL_LINE
  7713. }
  7714. scan_number_minus:
  7715. // state: we just parsed a leading minus sign
  7716. number_type = token_type::value_integer;
  7717. switch (get())
  7718. {
  7719. case '0':
  7720. {
  7721. add(current);
  7722. goto scan_number_zero;
  7723. }
  7724. case '1':
  7725. case '2':
  7726. case '3':
  7727. case '4':
  7728. case '5':
  7729. case '6':
  7730. case '7':
  7731. case '8':
  7732. case '9':
  7733. {
  7734. add(current);
  7735. goto scan_number_any1;
  7736. }
  7737. default:
  7738. {
  7739. error_message = "invalid number; expected digit after '-'";
  7740. return token_type::parse_error;
  7741. }
  7742. }
  7743. scan_number_zero:
  7744. // state: we just parse a zero (maybe with a leading minus sign)
  7745. switch (get())
  7746. {
  7747. case '.':
  7748. {
  7749. add(decimal_point_char);
  7750. goto scan_number_decimal1;
  7751. }
  7752. case 'e':
  7753. case 'E':
  7754. {
  7755. add(current);
  7756. goto scan_number_exponent;
  7757. }
  7758. default:
  7759. goto scan_number_done;
  7760. }
  7761. scan_number_any1:
  7762. // state: we just parsed a number 0-9 (maybe with a leading minus sign)
  7763. switch (get())
  7764. {
  7765. case '0':
  7766. case '1':
  7767. case '2':
  7768. case '3':
  7769. case '4':
  7770. case '5':
  7771. case '6':
  7772. case '7':
  7773. case '8':
  7774. case '9':
  7775. {
  7776. add(current);
  7777. goto scan_number_any1;
  7778. }
  7779. case '.':
  7780. {
  7781. add(decimal_point_char);
  7782. goto scan_number_decimal1;
  7783. }
  7784. case 'e':
  7785. case 'E':
  7786. {
  7787. add(current);
  7788. goto scan_number_exponent;
  7789. }
  7790. default:
  7791. goto scan_number_done;
  7792. }
  7793. scan_number_decimal1:
  7794. // state: we just parsed a decimal point
  7795. number_type = token_type::value_float;
  7796. switch (get())
  7797. {
  7798. case '0':
  7799. case '1':
  7800. case '2':
  7801. case '3':
  7802. case '4':
  7803. case '5':
  7804. case '6':
  7805. case '7':
  7806. case '8':
  7807. case '9':
  7808. {
  7809. add(current);
  7810. goto scan_number_decimal2;
  7811. }
  7812. default:
  7813. {
  7814. error_message = "invalid number; expected digit after '.'";
  7815. return token_type::parse_error;
  7816. }
  7817. }
  7818. scan_number_decimal2:
  7819. // we just parsed at least one number after a decimal point
  7820. switch (get())
  7821. {
  7822. case '0':
  7823. case '1':
  7824. case '2':
  7825. case '3':
  7826. case '4':
  7827. case '5':
  7828. case '6':
  7829. case '7':
  7830. case '8':
  7831. case '9':
  7832. {
  7833. add(current);
  7834. goto scan_number_decimal2;
  7835. }
  7836. case 'e':
  7837. case 'E':
  7838. {
  7839. add(current);
  7840. goto scan_number_exponent;
  7841. }
  7842. default:
  7843. goto scan_number_done;
  7844. }
  7845. scan_number_exponent:
  7846. // we just parsed an exponent
  7847. number_type = token_type::value_float;
  7848. switch (get())
  7849. {
  7850. case '+':
  7851. case '-':
  7852. {
  7853. add(current);
  7854. goto scan_number_sign;
  7855. }
  7856. case '0':
  7857. case '1':
  7858. case '2':
  7859. case '3':
  7860. case '4':
  7861. case '5':
  7862. case '6':
  7863. case '7':
  7864. case '8':
  7865. case '9':
  7866. {
  7867. add(current);
  7868. goto scan_number_any2;
  7869. }
  7870. default:
  7871. {
  7872. error_message =
  7873. "invalid number; expected '+', '-', or digit after exponent";
  7874. return token_type::parse_error;
  7875. }
  7876. }
  7877. scan_number_sign:
  7878. // we just parsed an exponent sign
  7879. switch (get())
  7880. {
  7881. case '0':
  7882. case '1':
  7883. case '2':
  7884. case '3':
  7885. case '4':
  7886. case '5':
  7887. case '6':
  7888. case '7':
  7889. case '8':
  7890. case '9':
  7891. {
  7892. add(current);
  7893. goto scan_number_any2;
  7894. }
  7895. default:
  7896. {
  7897. error_message = "invalid number; expected digit after exponent sign";
  7898. return token_type::parse_error;
  7899. }
  7900. }
  7901. scan_number_any2:
  7902. // we just parsed a number after the exponent or exponent sign
  7903. switch (get())
  7904. {
  7905. case '0':
  7906. case '1':
  7907. case '2':
  7908. case '3':
  7909. case '4':
  7910. case '5':
  7911. case '6':
  7912. case '7':
  7913. case '8':
  7914. case '9':
  7915. {
  7916. add(current);
  7917. goto scan_number_any2;
  7918. }
  7919. default:
  7920. goto scan_number_done;
  7921. }
  7922. scan_number_done:
  7923. // unget the character after the number (we only read it to know that
  7924. // we are done scanning a number)
  7925. unget();
  7926. char* endptr = nullptr;
  7927. errno = 0;
  7928. // try to parse integers first and fall back to floats
  7929. if (number_type == token_type::value_unsigned)
  7930. {
  7931. const auto x = std::strtoull(token_buffer.data(), &endptr, 10);
  7932. // we checked the number format before
  7933. assert(endptr == token_buffer.data() + token_buffer.size());
  7934. if (errno == 0)
  7935. {
  7936. value_unsigned = static_cast<number_unsigned_t>(x);
  7937. if (value_unsigned == x)
  7938. {
  7939. return token_type::value_unsigned;
  7940. }
  7941. }
  7942. }
  7943. else if (number_type == token_type::value_integer)
  7944. {
  7945. const auto x = std::strtoll(token_buffer.data(), &endptr, 10);
  7946. // we checked the number format before
  7947. assert(endptr == token_buffer.data() + token_buffer.size());
  7948. if (errno == 0)
  7949. {
  7950. value_integer = static_cast<number_integer_t>(x);
  7951. if (value_integer == x)
  7952. {
  7953. return token_type::value_integer;
  7954. }
  7955. }
  7956. }
  7957. // this code is reached if we parse a floating-point number or if an
  7958. // integer conversion above failed
  7959. strtof(value_float, token_buffer.data(), &endptr);
  7960. // we checked the number format before
  7961. assert(endptr == token_buffer.data() + token_buffer.size());
  7962. return token_type::value_float;
  7963. }
  7964. /*!
  7965. @param[in] literal_text the literal text to expect
  7966. @param[in] length the length of the passed literal text
  7967. @param[in] return_type the token type to return on success
  7968. */
  7969. JSON_HEDLEY_NON_NULL(2)
  7970. token_type scan_literal(const char* literal_text, const std::size_t length,
  7971. token_type return_type)
  7972. {
  7973. assert(current == literal_text[0]);
  7974. for (std::size_t i = 1; i < length; ++i)
  7975. {
  7976. if (JSON_HEDLEY_UNLIKELY(get() != literal_text[i]))
  7977. {
  7978. error_message = "invalid literal";
  7979. return token_type::parse_error;
  7980. }
  7981. }
  7982. return return_type;
  7983. }
  7984. /////////////////////
  7985. // input management
  7986. /////////////////////
  7987. /// reset token_buffer; current character is beginning of token
  7988. void reset() noexcept
  7989. {
  7990. token_buffer.clear();
  7991. token_string.clear();
  7992. token_string.push_back(std::char_traits<char>::to_char_type(current));
  7993. }
  7994. /*
  7995. @brief get next character from the input
  7996. This function provides the interface to the used input adapter. It does
  7997. not throw in case the input reached EOF, but returns a
  7998. `std::char_traits<char>::eof()` in that case. Stores the scanned characters
  7999. for use in error messages.
  8000. @return character read from the input
  8001. */
  8002. std::char_traits<char>::int_type get()
  8003. {
  8004. ++position.chars_read_total;
  8005. ++position.chars_read_current_line;
  8006. if (next_unget)
  8007. {
  8008. // just reset the next_unget variable and work with current
  8009. next_unget = false;
  8010. }
  8011. else
  8012. {
  8013. current = ia.get_character();
  8014. }
  8015. if (JSON_HEDLEY_LIKELY(current != std::char_traits<char>::eof()))
  8016. {
  8017. token_string.push_back(std::char_traits<char>::to_char_type(current));
  8018. }
  8019. if (current == '\n')
  8020. {
  8021. ++position.lines_read;
  8022. position.chars_read_current_line = 0;
  8023. }
  8024. return current;
  8025. }
  8026. /*!
  8027. @brief unget current character (read it again on next get)
  8028. We implement unget by setting variable next_unget to true. The input is not
  8029. changed - we just simulate ungetting by modifying chars_read_total,
  8030. chars_read_current_line, and token_string. The next call to get() will
  8031. behave as if the unget character is read again.
  8032. */
  8033. void unget()
  8034. {
  8035. next_unget = true;
  8036. --position.chars_read_total;
  8037. // in case we "unget" a newline, we have to also decrement the lines_read
  8038. if (position.chars_read_current_line == 0)
  8039. {
  8040. if (position.lines_read > 0)
  8041. {
  8042. --position.lines_read;
  8043. }
  8044. }
  8045. else
  8046. {
  8047. --position.chars_read_current_line;
  8048. }
  8049. if (JSON_HEDLEY_LIKELY(current != std::char_traits<char>::eof()))
  8050. {
  8051. assert(not token_string.empty());
  8052. token_string.pop_back();
  8053. }
  8054. }
  8055. /// add a character to token_buffer
  8056. void add(int c)
  8057. {
  8058. token_buffer.push_back(std::char_traits<char>::to_char_type(c));
  8059. }
  8060. public:
  8061. /////////////////////
  8062. // value getters
  8063. /////////////////////
  8064. /// return integer value
  8065. constexpr number_integer_t get_number_integer() const noexcept
  8066. {
  8067. return value_integer;
  8068. }
  8069. /// return unsigned integer value
  8070. constexpr number_unsigned_t get_number_unsigned() const noexcept
  8071. {
  8072. return value_unsigned;
  8073. }
  8074. /// return floating-point value
  8075. constexpr number_float_t get_number_float() const noexcept
  8076. {
  8077. return value_float;
  8078. }
  8079. /// return current string value (implicitly resets the token; useful only once)
  8080. string_t& get_string()
  8081. {
  8082. return token_buffer;
  8083. }
  8084. /////////////////////
  8085. // diagnostics
  8086. /////////////////////
  8087. /// return position of last read token
  8088. constexpr position_t get_position() const noexcept
  8089. {
  8090. return position;
  8091. }
  8092. /// return the last read token (for errors only). Will never contain EOF
  8093. /// (an arbitrary value that is not a valid char value, often -1), because
  8094. /// 255 may legitimately occur. May contain NUL, which should be escaped.
  8095. std::string get_token_string() const
  8096. {
  8097. // escape control characters
  8098. std::string result;
  8099. for (const auto c : token_string)
  8100. {
  8101. if ('\x00' <= c and c <= '\x1F')
  8102. {
  8103. // escape control characters
  8104. std::array<char, 9> cs{{}};
  8105. (std::snprintf)(cs.data(), cs.size(), "<U+%.4X>", static_cast<unsigned char>(c));
  8106. result += cs.data();
  8107. }
  8108. else
  8109. {
  8110. // add character as is
  8111. result.push_back(c);
  8112. }
  8113. }
  8114. return result;
  8115. }
  8116. /// return syntax error message
  8117. JSON_HEDLEY_RETURNS_NON_NULL
  8118. constexpr const char* get_error_message() const noexcept
  8119. {
  8120. return error_message;
  8121. }
  8122. /////////////////////
  8123. // actual scanner
  8124. /////////////////////
  8125. /*!
  8126. @brief skip the UTF-8 byte order mark
  8127. @return true iff there is no BOM or the correct BOM has been skipped
  8128. */
  8129. bool skip_bom()
  8130. {
  8131. if (get() == 0xEF)
  8132. {
  8133. // check if we completely parse the BOM
  8134. return get() == 0xBB and get() == 0xBF;
  8135. }
  8136. // the first character is not the beginning of the BOM; unget it to
  8137. // process is later
  8138. unget();
  8139. return true;
  8140. }
  8141. token_type scan()
  8142. {
  8143. // initially, skip the BOM
  8144. if (position.chars_read_total == 0 and not skip_bom())
  8145. {
  8146. error_message = "invalid BOM; must be 0xEF 0xBB 0xBF if given";
  8147. return token_type::parse_error;
  8148. }
  8149. // read next character and ignore whitespace
  8150. do
  8151. {
  8152. get();
  8153. }
  8154. while (current == ' ' or current == '\t' or current == '\n' or current == '\r');
  8155. switch (current)
  8156. {
  8157. // structural characters
  8158. case '[':
  8159. return token_type::begin_array;
  8160. case ']':
  8161. return token_type::end_array;
  8162. case '{':
  8163. return token_type::begin_object;
  8164. case '}':
  8165. return token_type::end_object;
  8166. case ':':
  8167. return token_type::name_separator;
  8168. case ',':
  8169. return token_type::value_separator;
  8170. // literals
  8171. case 't':
  8172. return scan_literal("true", 4, token_type::literal_true);
  8173. case 'f':
  8174. return scan_literal("false", 5, token_type::literal_false);
  8175. case 'n':
  8176. return scan_literal("null", 4, token_type::literal_null);
  8177. // string
  8178. case '\"':
  8179. return scan_string();
  8180. // number
  8181. case '-':
  8182. case '0':
  8183. case '1':
  8184. case '2':
  8185. case '3':
  8186. case '4':
  8187. case '5':
  8188. case '6':
  8189. case '7':
  8190. case '8':
  8191. case '9':
  8192. return scan_number();
  8193. // end of input (the null byte is needed when parsing from
  8194. // string literals)
  8195. case '\0':
  8196. case std::char_traits<char>::eof():
  8197. return token_type::end_of_input;
  8198. // error
  8199. default:
  8200. error_message = "invalid literal";
  8201. return token_type::parse_error;
  8202. }
  8203. }
  8204. private:
  8205. /// input adapter
  8206. InputAdapterType ia;
  8207. /// the current character
  8208. std::char_traits<char>::int_type current = std::char_traits<char>::eof();
  8209. /// whether the next get() call should just return current
  8210. bool next_unget = false;
  8211. /// the start position of the current token
  8212. position_t position {};
  8213. /// raw input token string (for error messages)
  8214. std::vector<char> token_string {};
  8215. /// buffer for variable-length tokens (numbers, strings)
  8216. string_t token_buffer {};
  8217. /// a description of occurred lexer errors
  8218. const char* error_message = "";
  8219. // number values
  8220. number_integer_t value_integer = 0;
  8221. number_unsigned_t value_unsigned = 0;
  8222. number_float_t value_float = 0;
  8223. /// the decimal point
  8224. const char decimal_point_char = '.';
  8225. };
  8226. } // namespace detail
  8227. } // namespace nlohmann
  8228. // #include <nlohmann/detail/input/parser.hpp>
  8229. #include <cassert> // assert
  8230. #include <cmath> // isfinite
  8231. #include <cstdint> // uint8_t
  8232. #include <functional> // function
  8233. #include <string> // string
  8234. #include <utility> // move
  8235. #include <vector> // vector
  8236. // #include <nlohmann/detail/exceptions.hpp>
  8237. // #include <nlohmann/detail/input/input_adapters.hpp>
  8238. // #include <nlohmann/detail/input/json_sax.hpp>
  8239. // #include <nlohmann/detail/input/lexer.hpp>
  8240. // #include <nlohmann/detail/macro_scope.hpp>
  8241. // #include <nlohmann/detail/meta/is_sax.hpp>
  8242. // #include <nlohmann/detail/value_t.hpp>
  8243. namespace nlohmann
  8244. {
  8245. namespace detail
  8246. {
  8247. ////////////
  8248. // parser //
  8249. ////////////
  8250. enum class parse_event_t : uint8_t
  8251. {
  8252. /// the parser read `{` and started to process a JSON object
  8253. object_start,
  8254. /// the parser read `}` and finished processing a JSON object
  8255. object_end,
  8256. /// the parser read `[` and started to process a JSON array
  8257. array_start,
  8258. /// the parser read `]` and finished processing a JSON array
  8259. array_end,
  8260. /// the parser read a key of a value in an object
  8261. key,
  8262. /// the parser finished reading a JSON value
  8263. value
  8264. };
  8265. template<typename BasicJsonType>
  8266. using parser_callback_t =
  8267. std::function<bool(int depth, parse_event_t event, BasicJsonType& parsed)>;
  8268. /*!
  8269. @brief syntax analysis
  8270. This class implements a recursive descent parser.
  8271. */
  8272. template<typename BasicJsonType, typename InputAdapterType>
  8273. class parser
  8274. {
  8275. using number_integer_t = typename BasicJsonType::number_integer_t;
  8276. using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
  8277. using number_float_t = typename BasicJsonType::number_float_t;
  8278. using string_t = typename BasicJsonType::string_t;
  8279. using lexer_t = lexer<BasicJsonType, InputAdapterType>;
  8280. using token_type = typename lexer_t::token_type;
  8281. public:
  8282. /// a parser reading from an input adapter
  8283. explicit parser(InputAdapterType&& adapter,
  8284. const parser_callback_t<BasicJsonType> cb = nullptr,
  8285. const bool allow_exceptions_ = true)
  8286. : callback(cb), m_lexer(std::move(adapter)), allow_exceptions(allow_exceptions_)
  8287. {
  8288. // read first token
  8289. get_token();
  8290. }
  8291. /*!
  8292. @brief public parser interface
  8293. @param[in] strict whether to expect the last token to be EOF
  8294. @param[in,out] result parsed JSON value
  8295. @throw parse_error.101 in case of an unexpected token
  8296. @throw parse_error.102 if to_unicode fails or surrogate error
  8297. @throw parse_error.103 if to_unicode fails
  8298. */
  8299. void parse(const bool strict, BasicJsonType& result)
  8300. {
  8301. if (callback)
  8302. {
  8303. json_sax_dom_callback_parser<BasicJsonType> sdp(result, callback, allow_exceptions);
  8304. sax_parse_internal(&sdp);
  8305. result.assert_invariant();
  8306. // in strict mode, input must be completely read
  8307. if (strict and (get_token() != token_type::end_of_input))
  8308. {
  8309. sdp.parse_error(m_lexer.get_position(),
  8310. m_lexer.get_token_string(),
  8311. parse_error::create(101, m_lexer.get_position(),
  8312. exception_message(token_type::end_of_input, "value")));
  8313. }
  8314. // in case of an error, return discarded value
  8315. if (sdp.is_errored())
  8316. {
  8317. result = value_t::discarded;
  8318. return;
  8319. }
  8320. // set top-level value to null if it was discarded by the callback
  8321. // function
  8322. if (result.is_discarded())
  8323. {
  8324. result = nullptr;
  8325. }
  8326. }
  8327. else
  8328. {
  8329. json_sax_dom_parser<BasicJsonType> sdp(result, allow_exceptions);
  8330. sax_parse_internal(&sdp);
  8331. result.assert_invariant();
  8332. // in strict mode, input must be completely read
  8333. if (strict and (get_token() != token_type::end_of_input))
  8334. {
  8335. sdp.parse_error(m_lexer.get_position(),
  8336. m_lexer.get_token_string(),
  8337. parse_error::create(101, m_lexer.get_position(),
  8338. exception_message(token_type::end_of_input, "value")));
  8339. }
  8340. // in case of an error, return discarded value
  8341. if (sdp.is_errored())
  8342. {
  8343. result = value_t::discarded;
  8344. return;
  8345. }
  8346. }
  8347. }
  8348. /*!
  8349. @brief public accept interface
  8350. @param[in] strict whether to expect the last token to be EOF
  8351. @return whether the input is a proper JSON text
  8352. */
  8353. bool accept(const bool strict = true)
  8354. {
  8355. json_sax_acceptor<BasicJsonType> sax_acceptor;
  8356. return sax_parse(&sax_acceptor, strict);
  8357. }
  8358. template <typename SAX>
  8359. JSON_HEDLEY_NON_NULL(2)
  8360. bool sax_parse(SAX* sax, const bool strict = true)
  8361. {
  8362. (void)detail::is_sax_static_asserts<SAX, BasicJsonType> {};
  8363. const bool result = sax_parse_internal(sax);
  8364. // strict mode: next byte must be EOF
  8365. if (result and strict and (get_token() != token_type::end_of_input))
  8366. {
  8367. return sax->parse_error(m_lexer.get_position(),
  8368. m_lexer.get_token_string(),
  8369. parse_error::create(101, m_lexer.get_position(),
  8370. exception_message(token_type::end_of_input, "value")));
  8371. }
  8372. return result;
  8373. }
  8374. private:
  8375. template <typename SAX>
  8376. JSON_HEDLEY_NON_NULL(2)
  8377. bool sax_parse_internal(SAX* sax)
  8378. {
  8379. // stack to remember the hierarchy of structured values we are parsing
  8380. // true = array; false = object
  8381. std::vector<bool> states;
  8382. // value to avoid a goto (see comment where set to true)
  8383. bool skip_to_state_evaluation = false;
  8384. while (true)
  8385. {
  8386. if (not skip_to_state_evaluation)
  8387. {
  8388. // invariant: get_token() was called before each iteration
  8389. switch (last_token)
  8390. {
  8391. case token_type::begin_object:
  8392. {
  8393. if (JSON_HEDLEY_UNLIKELY(not sax->start_object(std::size_t(-1))))
  8394. {
  8395. return false;
  8396. }
  8397. // closing } -> we are done
  8398. if (get_token() == token_type::end_object)
  8399. {
  8400. if (JSON_HEDLEY_UNLIKELY(not sax->end_object()))
  8401. {
  8402. return false;
  8403. }
  8404. break;
  8405. }
  8406. // parse key
  8407. if (JSON_HEDLEY_UNLIKELY(last_token != token_type::value_string))
  8408. {
  8409. return sax->parse_error(m_lexer.get_position(),
  8410. m_lexer.get_token_string(),
  8411. parse_error::create(101, m_lexer.get_position(),
  8412. exception_message(token_type::value_string, "object key")));
  8413. }
  8414. if (JSON_HEDLEY_UNLIKELY(not sax->key(m_lexer.get_string())))
  8415. {
  8416. return false;
  8417. }
  8418. // parse separator (:)
  8419. if (JSON_HEDLEY_UNLIKELY(get_token() != token_type::name_separator))
  8420. {
  8421. return sax->parse_error(m_lexer.get_position(),
  8422. m_lexer.get_token_string(),
  8423. parse_error::create(101, m_lexer.get_position(),
  8424. exception_message(token_type::name_separator, "object separator")));
  8425. }
  8426. // remember we are now inside an object
  8427. states.push_back(false);
  8428. // parse values
  8429. get_token();
  8430. continue;
  8431. }
  8432. case token_type::begin_array:
  8433. {
  8434. if (JSON_HEDLEY_UNLIKELY(not sax->start_array(std::size_t(-1))))
  8435. {
  8436. return false;
  8437. }
  8438. // closing ] -> we are done
  8439. if (get_token() == token_type::end_array)
  8440. {
  8441. if (JSON_HEDLEY_UNLIKELY(not sax->end_array()))
  8442. {
  8443. return false;
  8444. }
  8445. break;
  8446. }
  8447. // remember we are now inside an array
  8448. states.push_back(true);
  8449. // parse values (no need to call get_token)
  8450. continue;
  8451. }
  8452. case token_type::value_float:
  8453. {
  8454. const auto res = m_lexer.get_number_float();
  8455. if (JSON_HEDLEY_UNLIKELY(not std::isfinite(res)))
  8456. {
  8457. return sax->parse_error(m_lexer.get_position(),
  8458. m_lexer.get_token_string(),
  8459. out_of_range::create(406, "number overflow parsing '" + m_lexer.get_token_string() + "'"));
  8460. }
  8461. if (JSON_HEDLEY_UNLIKELY(not sax->number_float(res, m_lexer.get_string())))
  8462. {
  8463. return false;
  8464. }
  8465. break;
  8466. }
  8467. case token_type::literal_false:
  8468. {
  8469. if (JSON_HEDLEY_UNLIKELY(not sax->boolean(false)))
  8470. {
  8471. return false;
  8472. }
  8473. break;
  8474. }
  8475. case token_type::literal_null:
  8476. {
  8477. if (JSON_HEDLEY_UNLIKELY(not sax->null()))
  8478. {
  8479. return false;
  8480. }
  8481. break;
  8482. }
  8483. case token_type::literal_true:
  8484. {
  8485. if (JSON_HEDLEY_UNLIKELY(not sax->boolean(true)))
  8486. {
  8487. return false;
  8488. }
  8489. break;
  8490. }
  8491. case token_type::value_integer:
  8492. {
  8493. if (JSON_HEDLEY_UNLIKELY(not sax->number_integer(m_lexer.get_number_integer())))
  8494. {
  8495. return false;
  8496. }
  8497. break;
  8498. }
  8499. case token_type::value_string:
  8500. {
  8501. if (JSON_HEDLEY_UNLIKELY(not sax->string(m_lexer.get_string())))
  8502. {
  8503. return false;
  8504. }
  8505. break;
  8506. }
  8507. case token_type::value_unsigned:
  8508. {
  8509. if (JSON_HEDLEY_UNLIKELY(not sax->number_unsigned(m_lexer.get_number_unsigned())))
  8510. {
  8511. return false;
  8512. }
  8513. break;
  8514. }
  8515. case token_type::parse_error:
  8516. {
  8517. // using "uninitialized" to avoid "expected" message
  8518. return sax->parse_error(m_lexer.get_position(),
  8519. m_lexer.get_token_string(),
  8520. parse_error::create(101, m_lexer.get_position(),
  8521. exception_message(token_type::uninitialized, "value")));
  8522. }
  8523. default: // the last token was unexpected
  8524. {
  8525. return sax->parse_error(m_lexer.get_position(),
  8526. m_lexer.get_token_string(),
  8527. parse_error::create(101, m_lexer.get_position(),
  8528. exception_message(token_type::literal_or_value, "value")));
  8529. }
  8530. }
  8531. }
  8532. else
  8533. {
  8534. skip_to_state_evaluation = false;
  8535. }
  8536. // we reached this line after we successfully parsed a value
  8537. if (states.empty())
  8538. {
  8539. // empty stack: we reached the end of the hierarchy: done
  8540. return true;
  8541. }
  8542. if (states.back()) // array
  8543. {
  8544. // comma -> next value
  8545. if (get_token() == token_type::value_separator)
  8546. {
  8547. // parse a new value
  8548. get_token();
  8549. continue;
  8550. }
  8551. // closing ]
  8552. if (JSON_HEDLEY_LIKELY(last_token == token_type::end_array))
  8553. {
  8554. if (JSON_HEDLEY_UNLIKELY(not sax->end_array()))
  8555. {
  8556. return false;
  8557. }
  8558. // We are done with this array. Before we can parse a
  8559. // new value, we need to evaluate the new state first.
  8560. // By setting skip_to_state_evaluation to false, we
  8561. // are effectively jumping to the beginning of this if.
  8562. assert(not states.empty());
  8563. states.pop_back();
  8564. skip_to_state_evaluation = true;
  8565. continue;
  8566. }
  8567. return sax->parse_error(m_lexer.get_position(),
  8568. m_lexer.get_token_string(),
  8569. parse_error::create(101, m_lexer.get_position(),
  8570. exception_message(token_type::end_array, "array")));
  8571. }
  8572. else // object
  8573. {
  8574. // comma -> next value
  8575. if (get_token() == token_type::value_separator)
  8576. {
  8577. // parse key
  8578. if (JSON_HEDLEY_UNLIKELY(get_token() != token_type::value_string))
  8579. {
  8580. return sax->parse_error(m_lexer.get_position(),
  8581. m_lexer.get_token_string(),
  8582. parse_error::create(101, m_lexer.get_position(),
  8583. exception_message(token_type::value_string, "object key")));
  8584. }
  8585. if (JSON_HEDLEY_UNLIKELY(not sax->key(m_lexer.get_string())))
  8586. {
  8587. return false;
  8588. }
  8589. // parse separator (:)
  8590. if (JSON_HEDLEY_UNLIKELY(get_token() != token_type::name_separator))
  8591. {
  8592. return sax->parse_error(m_lexer.get_position(),
  8593. m_lexer.get_token_string(),
  8594. parse_error::create(101, m_lexer.get_position(),
  8595. exception_message(token_type::name_separator, "object separator")));
  8596. }
  8597. // parse values
  8598. get_token();
  8599. continue;
  8600. }
  8601. // closing }
  8602. if (JSON_HEDLEY_LIKELY(last_token == token_type::end_object))
  8603. {
  8604. if (JSON_HEDLEY_UNLIKELY(not sax->end_object()))
  8605. {
  8606. return false;
  8607. }
  8608. // We are done with this object. Before we can parse a
  8609. // new value, we need to evaluate the new state first.
  8610. // By setting skip_to_state_evaluation to false, we
  8611. // are effectively jumping to the beginning of this if.
  8612. assert(not states.empty());
  8613. states.pop_back();
  8614. skip_to_state_evaluation = true;
  8615. continue;
  8616. }
  8617. return sax->parse_error(m_lexer.get_position(),
  8618. m_lexer.get_token_string(),
  8619. parse_error::create(101, m_lexer.get_position(),
  8620. exception_message(token_type::end_object, "object")));
  8621. }
  8622. }
  8623. }
  8624. /// get next token from lexer
  8625. token_type get_token()
  8626. {
  8627. return last_token = m_lexer.scan();
  8628. }
  8629. std::string exception_message(const token_type expected, const std::string& context)
  8630. {
  8631. std::string error_msg = "syntax error ";
  8632. if (not context.empty())
  8633. {
  8634. error_msg += "while parsing " + context + " ";
  8635. }
  8636. error_msg += "- ";
  8637. if (last_token == token_type::parse_error)
  8638. {
  8639. error_msg += std::string(m_lexer.get_error_message()) + "; last read: '" +
  8640. m_lexer.get_token_string() + "'";
  8641. }
  8642. else
  8643. {
  8644. error_msg += "unexpected " + std::string(lexer_t::token_type_name(last_token));
  8645. }
  8646. if (expected != token_type::uninitialized)
  8647. {
  8648. error_msg += "; expected " + std::string(lexer_t::token_type_name(expected));
  8649. }
  8650. return error_msg;
  8651. }
  8652. private:
  8653. /// callback function
  8654. const parser_callback_t<BasicJsonType> callback = nullptr;
  8655. /// the type of the last read token
  8656. token_type last_token = token_type::uninitialized;
  8657. /// the lexer
  8658. lexer_t m_lexer;
  8659. /// whether to throw exceptions in case of errors
  8660. const bool allow_exceptions = true;
  8661. };
  8662. } // namespace detail
  8663. } // namespace nlohmann
  8664. // #include <nlohmann/detail/iterators/internal_iterator.hpp>
  8665. // #include <nlohmann/detail/iterators/primitive_iterator.hpp>
  8666. #include <cstddef> // ptrdiff_t
  8667. #include <limits> // numeric_limits
  8668. namespace nlohmann
  8669. {
  8670. namespace detail
  8671. {
  8672. /*
  8673. @brief an iterator for primitive JSON types
  8674. This class models an iterator for primitive JSON types (boolean, number,
  8675. string). It's only purpose is to allow the iterator/const_iterator classes
  8676. to "iterate" over primitive values. Internally, the iterator is modeled by
  8677. a `difference_type` variable. Value begin_value (`0`) models the begin,
  8678. end_value (`1`) models past the end.
  8679. */
  8680. class primitive_iterator_t
  8681. {
  8682. private:
  8683. using difference_type = std::ptrdiff_t;
  8684. static constexpr difference_type begin_value = 0;
  8685. static constexpr difference_type end_value = begin_value + 1;
  8686. /// iterator as signed integer type
  8687. difference_type m_it = (std::numeric_limits<std::ptrdiff_t>::min)();
  8688. public:
  8689. constexpr difference_type get_value() const noexcept
  8690. {
  8691. return m_it;
  8692. }
  8693. /// set iterator to a defined beginning
  8694. void set_begin() noexcept
  8695. {
  8696. m_it = begin_value;
  8697. }
  8698. /// set iterator to a defined past the end
  8699. void set_end() noexcept
  8700. {
  8701. m_it = end_value;
  8702. }
  8703. /// return whether the iterator can be dereferenced
  8704. constexpr bool is_begin() const noexcept
  8705. {
  8706. return m_it == begin_value;
  8707. }
  8708. /// return whether the iterator is at end
  8709. constexpr bool is_end() const noexcept
  8710. {
  8711. return m_it == end_value;
  8712. }
  8713. friend constexpr bool operator==(primitive_iterator_t lhs, primitive_iterator_t rhs) noexcept
  8714. {
  8715. return lhs.m_it == rhs.m_it;
  8716. }
  8717. friend constexpr bool operator<(primitive_iterator_t lhs, primitive_iterator_t rhs) noexcept
  8718. {
  8719. return lhs.m_it < rhs.m_it;
  8720. }
  8721. primitive_iterator_t operator+(difference_type n) noexcept
  8722. {
  8723. auto result = *this;
  8724. result += n;
  8725. return result;
  8726. }
  8727. friend constexpr difference_type operator-(primitive_iterator_t lhs, primitive_iterator_t rhs) noexcept
  8728. {
  8729. return lhs.m_it - rhs.m_it;
  8730. }
  8731. primitive_iterator_t& operator++() noexcept
  8732. {
  8733. ++m_it;
  8734. return *this;
  8735. }
  8736. primitive_iterator_t const operator++(int) noexcept
  8737. {
  8738. auto result = *this;
  8739. ++m_it;
  8740. return result;
  8741. }
  8742. primitive_iterator_t& operator--() noexcept
  8743. {
  8744. --m_it;
  8745. return *this;
  8746. }
  8747. primitive_iterator_t const operator--(int) noexcept
  8748. {
  8749. auto result = *this;
  8750. --m_it;
  8751. return result;
  8752. }
  8753. primitive_iterator_t& operator+=(difference_type n) noexcept
  8754. {
  8755. m_it += n;
  8756. return *this;
  8757. }
  8758. primitive_iterator_t& operator-=(difference_type n) noexcept
  8759. {
  8760. m_it -= n;
  8761. return *this;
  8762. }
  8763. };
  8764. } // namespace detail
  8765. } // namespace nlohmann
  8766. namespace nlohmann
  8767. {
  8768. namespace detail
  8769. {
  8770. /*!
  8771. @brief an iterator value
  8772. @note This structure could easily be a union, but MSVC currently does not allow
  8773. unions members with complex constructors, see https://github.com/nlohmann/json/pull/105.
  8774. */
  8775. template<typename BasicJsonType> struct internal_iterator
  8776. {
  8777. /// iterator for JSON objects
  8778. typename BasicJsonType::object_t::iterator object_iterator {};
  8779. /// iterator for JSON arrays
  8780. typename BasicJsonType::array_t::iterator array_iterator {};
  8781. /// iterator for JSON binary arrays
  8782. typename BasicJsonType::binary_t::iterator binary_iterator {};
  8783. /// generic iterator for all other types
  8784. primitive_iterator_t primitive_iterator {};
  8785. };
  8786. } // namespace detail
  8787. } // namespace nlohmann
  8788. // #include <nlohmann/detail/iterators/iter_impl.hpp>
  8789. #include <ciso646> // not
  8790. #include <iterator> // iterator, random_access_iterator_tag, bidirectional_iterator_tag, advance, next
  8791. #include <type_traits> // conditional, is_const, remove_const
  8792. // #include <nlohmann/detail/exceptions.hpp>
  8793. // #include <nlohmann/detail/iterators/internal_iterator.hpp>
  8794. // #include <nlohmann/detail/iterators/primitive_iterator.hpp>
  8795. // #include <nlohmann/detail/macro_scope.hpp>
  8796. // #include <nlohmann/detail/meta/cpp_future.hpp>
  8797. // #include <nlohmann/detail/meta/type_traits.hpp>
  8798. // #include <nlohmann/detail/value_t.hpp>
  8799. namespace nlohmann
  8800. {
  8801. namespace detail
  8802. {
  8803. // forward declare, to be able to friend it later on
  8804. template<typename IteratorType> class iteration_proxy;
  8805. template<typename IteratorType> class iteration_proxy_value;
  8806. /*!
  8807. @brief a template for a bidirectional iterator for the @ref basic_json class
  8808. This class implements a both iterators (iterator and const_iterator) for the
  8809. @ref basic_json class.
  8810. @note An iterator is called *initialized* when a pointer to a JSON value has
  8811. been set (e.g., by a constructor or a copy assignment). If the iterator is
  8812. default-constructed, it is *uninitialized* and most methods are undefined.
  8813. **The library uses assertions to detect calls on uninitialized iterators.**
  8814. @requirement The class satisfies the following concept requirements:
  8815. -
  8816. [BidirectionalIterator](https://en.cppreference.com/w/cpp/named_req/BidirectionalIterator):
  8817. The iterator that can be moved can be moved in both directions (i.e.
  8818. incremented and decremented).
  8819. @since version 1.0.0, simplified in version 2.0.9, change to bidirectional
  8820. iterators in version 3.0.0 (see https://github.com/nlohmann/json/issues/593)
  8821. */
  8822. template<typename BasicJsonType>
  8823. class iter_impl
  8824. {
  8825. /// allow basic_json to access private members
  8826. friend iter_impl<typename std::conditional<std::is_const<BasicJsonType>::value, typename std::remove_const<BasicJsonType>::type, const BasicJsonType>::type>;
  8827. friend BasicJsonType;
  8828. friend iteration_proxy<iter_impl>;
  8829. friend iteration_proxy_value<iter_impl>;
  8830. using object_t = typename BasicJsonType::object_t;
  8831. using array_t = typename BasicJsonType::array_t;
  8832. // make sure BasicJsonType is basic_json or const basic_json
  8833. static_assert(is_basic_json<typename std::remove_const<BasicJsonType>::type>::value,
  8834. "iter_impl only accepts (const) basic_json");
  8835. public:
  8836. /// The std::iterator class template (used as a base class to provide typedefs) is deprecated in C++17.
  8837. /// The C++ Standard has never required user-defined iterators to derive from std::iterator.
  8838. /// A user-defined iterator should provide publicly accessible typedefs named
  8839. /// iterator_category, value_type, difference_type, pointer, and reference.
  8840. /// Note that value_type is required to be non-const, even for constant iterators.
  8841. using iterator_category = std::bidirectional_iterator_tag;
  8842. /// the type of the values when the iterator is dereferenced
  8843. using value_type = typename BasicJsonType::value_type;
  8844. /// a type to represent differences between iterators
  8845. using difference_type = typename BasicJsonType::difference_type;
  8846. /// defines a pointer to the type iterated over (value_type)
  8847. using pointer = typename std::conditional<std::is_const<BasicJsonType>::value,
  8848. typename BasicJsonType::const_pointer,
  8849. typename BasicJsonType::pointer>::type;
  8850. /// defines a reference to the type iterated over (value_type)
  8851. using reference =
  8852. typename std::conditional<std::is_const<BasicJsonType>::value,
  8853. typename BasicJsonType::const_reference,
  8854. typename BasicJsonType::reference>::type;
  8855. /// default constructor
  8856. iter_impl() = default;
  8857. /*!
  8858. @brief constructor for a given JSON instance
  8859. @param[in] object pointer to a JSON object for this iterator
  8860. @pre object != nullptr
  8861. @post The iterator is initialized; i.e. `m_object != nullptr`.
  8862. */
  8863. explicit iter_impl(pointer object) noexcept : m_object(object)
  8864. {
  8865. assert(m_object != nullptr);
  8866. switch (m_object->m_type)
  8867. {
  8868. case value_t::object:
  8869. {
  8870. m_it.object_iterator = typename object_t::iterator();
  8871. break;
  8872. }
  8873. case value_t::array:
  8874. {
  8875. m_it.array_iterator = typename array_t::iterator();
  8876. break;
  8877. }
  8878. default:
  8879. {
  8880. m_it.primitive_iterator = primitive_iterator_t();
  8881. break;
  8882. }
  8883. }
  8884. }
  8885. /*!
  8886. @note The conventional copy constructor and copy assignment are implicitly
  8887. defined. Combined with the following converting constructor and
  8888. assignment, they support: (1) copy from iterator to iterator, (2)
  8889. copy from const iterator to const iterator, and (3) conversion from
  8890. iterator to const iterator. However conversion from const iterator
  8891. to iterator is not defined.
  8892. */
  8893. /*!
  8894. @brief const copy constructor
  8895. @param[in] other const iterator to copy from
  8896. @note This copy constructor had to be defined explicitly to circumvent a bug
  8897. occurring on msvc v19.0 compiler (VS 2015) debug build. For more
  8898. information refer to: https://github.com/nlohmann/json/issues/1608
  8899. */
  8900. iter_impl(const iter_impl<const BasicJsonType>& other) noexcept
  8901. : m_object(other.m_object), m_it(other.m_it)
  8902. {}
  8903. /*!
  8904. @brief converting assignment
  8905. @param[in] other const iterator to copy from
  8906. @return const/non-const iterator
  8907. @note It is not checked whether @a other is initialized.
  8908. */
  8909. iter_impl& operator=(const iter_impl<const BasicJsonType>& other) noexcept
  8910. {
  8911. m_object = other.m_object;
  8912. m_it = other.m_it;
  8913. return *this;
  8914. }
  8915. /*!
  8916. @brief converting constructor
  8917. @param[in] other non-const iterator to copy from
  8918. @note It is not checked whether @a other is initialized.
  8919. */
  8920. iter_impl(const iter_impl<typename std::remove_const<BasicJsonType>::type>& other) noexcept
  8921. : m_object(other.m_object), m_it(other.m_it)
  8922. {}
  8923. /*!
  8924. @brief converting assignment
  8925. @param[in] other non-const iterator to copy from
  8926. @return const/non-const iterator
  8927. @note It is not checked whether @a other is initialized.
  8928. */
  8929. iter_impl& operator=(const iter_impl<typename std::remove_const<BasicJsonType>::type>& other) noexcept
  8930. {
  8931. m_object = other.m_object;
  8932. m_it = other.m_it;
  8933. return *this;
  8934. }
  8935. private:
  8936. /*!
  8937. @brief set the iterator to the first value
  8938. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  8939. */
  8940. void set_begin() noexcept
  8941. {
  8942. assert(m_object != nullptr);
  8943. switch (m_object->m_type)
  8944. {
  8945. case value_t::object:
  8946. {
  8947. m_it.object_iterator = m_object->m_value.object->begin();
  8948. break;
  8949. }
  8950. case value_t::array:
  8951. {
  8952. m_it.array_iterator = m_object->m_value.array->begin();
  8953. break;
  8954. }
  8955. case value_t::null:
  8956. {
  8957. // set to end so begin()==end() is true: null is empty
  8958. m_it.primitive_iterator.set_end();
  8959. break;
  8960. }
  8961. default:
  8962. {
  8963. m_it.primitive_iterator.set_begin();
  8964. break;
  8965. }
  8966. }
  8967. }
  8968. /*!
  8969. @brief set the iterator past the last value
  8970. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  8971. */
  8972. void set_end() noexcept
  8973. {
  8974. assert(m_object != nullptr);
  8975. switch (m_object->m_type)
  8976. {
  8977. case value_t::object:
  8978. {
  8979. m_it.object_iterator = m_object->m_value.object->end();
  8980. break;
  8981. }
  8982. case value_t::array:
  8983. {
  8984. m_it.array_iterator = m_object->m_value.array->end();
  8985. break;
  8986. }
  8987. default:
  8988. {
  8989. m_it.primitive_iterator.set_end();
  8990. break;
  8991. }
  8992. }
  8993. }
  8994. public:
  8995. /*!
  8996. @brief return a reference to the value pointed to by the iterator
  8997. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  8998. */
  8999. reference operator*() const
  9000. {
  9001. assert(m_object != nullptr);
  9002. switch (m_object->m_type)
  9003. {
  9004. case value_t::object:
  9005. {
  9006. assert(m_it.object_iterator != m_object->m_value.object->end());
  9007. return m_it.object_iterator->second;
  9008. }
  9009. case value_t::array:
  9010. {
  9011. assert(m_it.array_iterator != m_object->m_value.array->end());
  9012. return *m_it.array_iterator;
  9013. }
  9014. case value_t::null:
  9015. JSON_THROW(invalid_iterator::create(214, "cannot get value"));
  9016. default:
  9017. {
  9018. if (JSON_HEDLEY_LIKELY(m_it.primitive_iterator.is_begin()))
  9019. {
  9020. return *m_object;
  9021. }
  9022. JSON_THROW(invalid_iterator::create(214, "cannot get value"));
  9023. }
  9024. }
  9025. }
  9026. /*!
  9027. @brief dereference the iterator
  9028. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  9029. */
  9030. pointer operator->() const
  9031. {
  9032. assert(m_object != nullptr);
  9033. switch (m_object->m_type)
  9034. {
  9035. case value_t::object:
  9036. {
  9037. assert(m_it.object_iterator != m_object->m_value.object->end());
  9038. return &(m_it.object_iterator->second);
  9039. }
  9040. case value_t::array:
  9041. {
  9042. assert(m_it.array_iterator != m_object->m_value.array->end());
  9043. return &*m_it.array_iterator;
  9044. }
  9045. default:
  9046. {
  9047. if (JSON_HEDLEY_LIKELY(m_it.primitive_iterator.is_begin()))
  9048. {
  9049. return m_object;
  9050. }
  9051. JSON_THROW(invalid_iterator::create(214, "cannot get value"));
  9052. }
  9053. }
  9054. }
  9055. /*!
  9056. @brief post-increment (it++)
  9057. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  9058. */
  9059. iter_impl const operator++(int)
  9060. {
  9061. auto result = *this;
  9062. ++(*this);
  9063. return result;
  9064. }
  9065. /*!
  9066. @brief pre-increment (++it)
  9067. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  9068. */
  9069. iter_impl& operator++()
  9070. {
  9071. assert(m_object != nullptr);
  9072. switch (m_object->m_type)
  9073. {
  9074. case value_t::object:
  9075. {
  9076. std::advance(m_it.object_iterator, 1);
  9077. break;
  9078. }
  9079. case value_t::array:
  9080. {
  9081. std::advance(m_it.array_iterator, 1);
  9082. break;
  9083. }
  9084. default:
  9085. {
  9086. ++m_it.primitive_iterator;
  9087. break;
  9088. }
  9089. }
  9090. return *this;
  9091. }
  9092. /*!
  9093. @brief post-decrement (it--)
  9094. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  9095. */
  9096. iter_impl const operator--(int)
  9097. {
  9098. auto result = *this;
  9099. --(*this);
  9100. return result;
  9101. }
  9102. /*!
  9103. @brief pre-decrement (--it)
  9104. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  9105. */
  9106. iter_impl& operator--()
  9107. {
  9108. assert(m_object != nullptr);
  9109. switch (m_object->m_type)
  9110. {
  9111. case value_t::object:
  9112. {
  9113. std::advance(m_it.object_iterator, -1);
  9114. break;
  9115. }
  9116. case value_t::array:
  9117. {
  9118. std::advance(m_it.array_iterator, -1);
  9119. break;
  9120. }
  9121. default:
  9122. {
  9123. --m_it.primitive_iterator;
  9124. break;
  9125. }
  9126. }
  9127. return *this;
  9128. }
  9129. /*!
  9130. @brief comparison: equal
  9131. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  9132. */
  9133. bool operator==(const iter_impl& other) const
  9134. {
  9135. // if objects are not the same, the comparison is undefined
  9136. if (JSON_HEDLEY_UNLIKELY(m_object != other.m_object))
  9137. {
  9138. JSON_THROW(invalid_iterator::create(212, "cannot compare iterators of different containers"));
  9139. }
  9140. assert(m_object != nullptr);
  9141. switch (m_object->m_type)
  9142. {
  9143. case value_t::object:
  9144. return (m_it.object_iterator == other.m_it.object_iterator);
  9145. case value_t::array:
  9146. return (m_it.array_iterator == other.m_it.array_iterator);
  9147. default:
  9148. return (m_it.primitive_iterator == other.m_it.primitive_iterator);
  9149. }
  9150. }
  9151. /*!
  9152. @brief comparison: not equal
  9153. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  9154. */
  9155. bool operator!=(const iter_impl& other) const
  9156. {
  9157. return not operator==(other);
  9158. }
  9159. /*!
  9160. @brief comparison: smaller
  9161. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  9162. */
  9163. bool operator<(const iter_impl& other) const
  9164. {
  9165. // if objects are not the same, the comparison is undefined
  9166. if (JSON_HEDLEY_UNLIKELY(m_object != other.m_object))
  9167. {
  9168. JSON_THROW(invalid_iterator::create(212, "cannot compare iterators of different containers"));
  9169. }
  9170. assert(m_object != nullptr);
  9171. switch (m_object->m_type)
  9172. {
  9173. case value_t::object:
  9174. JSON_THROW(invalid_iterator::create(213, "cannot compare order of object iterators"));
  9175. case value_t::array:
  9176. return (m_it.array_iterator < other.m_it.array_iterator);
  9177. default:
  9178. return (m_it.primitive_iterator < other.m_it.primitive_iterator);
  9179. }
  9180. }
  9181. /*!
  9182. @brief comparison: less than or equal
  9183. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  9184. */
  9185. bool operator<=(const iter_impl& other) const
  9186. {
  9187. return not other.operator < (*this);
  9188. }
  9189. /*!
  9190. @brief comparison: greater than
  9191. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  9192. */
  9193. bool operator>(const iter_impl& other) const
  9194. {
  9195. return not operator<=(other);
  9196. }
  9197. /*!
  9198. @brief comparison: greater than or equal
  9199. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  9200. */
  9201. bool operator>=(const iter_impl& other) const
  9202. {
  9203. return not operator<(other);
  9204. }
  9205. /*!
  9206. @brief add to iterator
  9207. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  9208. */
  9209. iter_impl& operator+=(difference_type i)
  9210. {
  9211. assert(m_object != nullptr);
  9212. switch (m_object->m_type)
  9213. {
  9214. case value_t::object:
  9215. JSON_THROW(invalid_iterator::create(209, "cannot use offsets with object iterators"));
  9216. case value_t::array:
  9217. {
  9218. std::advance(m_it.array_iterator, i);
  9219. break;
  9220. }
  9221. default:
  9222. {
  9223. m_it.primitive_iterator += i;
  9224. break;
  9225. }
  9226. }
  9227. return *this;
  9228. }
  9229. /*!
  9230. @brief subtract from iterator
  9231. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  9232. */
  9233. iter_impl& operator-=(difference_type i)
  9234. {
  9235. return operator+=(-i);
  9236. }
  9237. /*!
  9238. @brief add to iterator
  9239. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  9240. */
  9241. iter_impl operator+(difference_type i) const
  9242. {
  9243. auto result = *this;
  9244. result += i;
  9245. return result;
  9246. }
  9247. /*!
  9248. @brief addition of distance and iterator
  9249. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  9250. */
  9251. friend iter_impl operator+(difference_type i, const iter_impl& it)
  9252. {
  9253. auto result = it;
  9254. result += i;
  9255. return result;
  9256. }
  9257. /*!
  9258. @brief subtract from iterator
  9259. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  9260. */
  9261. iter_impl operator-(difference_type i) const
  9262. {
  9263. auto result = *this;
  9264. result -= i;
  9265. return result;
  9266. }
  9267. /*!
  9268. @brief return difference
  9269. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  9270. */
  9271. difference_type operator-(const iter_impl& other) const
  9272. {
  9273. assert(m_object != nullptr);
  9274. switch (m_object->m_type)
  9275. {
  9276. case value_t::object:
  9277. JSON_THROW(invalid_iterator::create(209, "cannot use offsets with object iterators"));
  9278. case value_t::array:
  9279. return m_it.array_iterator - other.m_it.array_iterator;
  9280. default:
  9281. return m_it.primitive_iterator - other.m_it.primitive_iterator;
  9282. }
  9283. }
  9284. /*!
  9285. @brief access to successor
  9286. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  9287. */
  9288. reference operator[](difference_type n) const
  9289. {
  9290. assert(m_object != nullptr);
  9291. switch (m_object->m_type)
  9292. {
  9293. case value_t::object:
  9294. JSON_THROW(invalid_iterator::create(208, "cannot use operator[] for object iterators"));
  9295. case value_t::array:
  9296. return *std::next(m_it.array_iterator, n);
  9297. case value_t::null:
  9298. JSON_THROW(invalid_iterator::create(214, "cannot get value"));
  9299. default:
  9300. {
  9301. if (JSON_HEDLEY_LIKELY(m_it.primitive_iterator.get_value() == -n))
  9302. {
  9303. return *m_object;
  9304. }
  9305. JSON_THROW(invalid_iterator::create(214, "cannot get value"));
  9306. }
  9307. }
  9308. }
  9309. /*!
  9310. @brief return the key of an object iterator
  9311. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  9312. */
  9313. const typename object_t::key_type& key() const
  9314. {
  9315. assert(m_object != nullptr);
  9316. if (JSON_HEDLEY_LIKELY(m_object->is_object()))
  9317. {
  9318. return m_it.object_iterator->first;
  9319. }
  9320. JSON_THROW(invalid_iterator::create(207, "cannot use key() for non-object iterators"));
  9321. }
  9322. /*!
  9323. @brief return the value of an iterator
  9324. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  9325. */
  9326. reference value() const
  9327. {
  9328. return operator*();
  9329. }
  9330. private:
  9331. /// associated JSON instance
  9332. pointer m_object = nullptr;
  9333. /// the actual iterator of the associated instance
  9334. internal_iterator<typename std::remove_const<BasicJsonType>::type> m_it {};
  9335. };
  9336. } // namespace detail
  9337. } // namespace nlohmann
  9338. // #include <nlohmann/detail/iterators/iteration_proxy.hpp>
  9339. // #include <nlohmann/detail/iterators/json_reverse_iterator.hpp>
  9340. #include <cstddef> // ptrdiff_t
  9341. #include <iterator> // reverse_iterator
  9342. #include <utility> // declval
  9343. namespace nlohmann
  9344. {
  9345. namespace detail
  9346. {
  9347. //////////////////////
  9348. // reverse_iterator //
  9349. //////////////////////
  9350. /*!
  9351. @brief a template for a reverse iterator class
  9352. @tparam Base the base iterator type to reverse. Valid types are @ref
  9353. iterator (to create @ref reverse_iterator) and @ref const_iterator (to
  9354. create @ref const_reverse_iterator).
  9355. @requirement The class satisfies the following concept requirements:
  9356. -
  9357. [BidirectionalIterator](https://en.cppreference.com/w/cpp/named_req/BidirectionalIterator):
  9358. The iterator that can be moved can be moved in both directions (i.e.
  9359. incremented and decremented).
  9360. - [OutputIterator](https://en.cppreference.com/w/cpp/named_req/OutputIterator):
  9361. It is possible to write to the pointed-to element (only if @a Base is
  9362. @ref iterator).
  9363. @since version 1.0.0
  9364. */
  9365. template<typename Base>
  9366. class json_reverse_iterator : public std::reverse_iterator<Base>
  9367. {
  9368. public:
  9369. using difference_type = std::ptrdiff_t;
  9370. /// shortcut to the reverse iterator adapter
  9371. using base_iterator = std::reverse_iterator<Base>;
  9372. /// the reference type for the pointed-to element
  9373. using reference = typename Base::reference;
  9374. /// create reverse iterator from iterator
  9375. explicit json_reverse_iterator(const typename base_iterator::iterator_type& it) noexcept
  9376. : base_iterator(it) {}
  9377. /// create reverse iterator from base class
  9378. explicit json_reverse_iterator(const base_iterator& it) noexcept : base_iterator(it) {}
  9379. /// post-increment (it++)
  9380. json_reverse_iterator const operator++(int)
  9381. {
  9382. return static_cast<json_reverse_iterator>(base_iterator::operator++(1));
  9383. }
  9384. /// pre-increment (++it)
  9385. json_reverse_iterator& operator++()
  9386. {
  9387. return static_cast<json_reverse_iterator&>(base_iterator::operator++());
  9388. }
  9389. /// post-decrement (it--)
  9390. json_reverse_iterator const operator--(int)
  9391. {
  9392. return static_cast<json_reverse_iterator>(base_iterator::operator--(1));
  9393. }
  9394. /// pre-decrement (--it)
  9395. json_reverse_iterator& operator--()
  9396. {
  9397. return static_cast<json_reverse_iterator&>(base_iterator::operator--());
  9398. }
  9399. /// add to iterator
  9400. json_reverse_iterator& operator+=(difference_type i)
  9401. {
  9402. return static_cast<json_reverse_iterator&>(base_iterator::operator+=(i));
  9403. }
  9404. /// add to iterator
  9405. json_reverse_iterator operator+(difference_type i) const
  9406. {
  9407. return static_cast<json_reverse_iterator>(base_iterator::operator+(i));
  9408. }
  9409. /// subtract from iterator
  9410. json_reverse_iterator operator-(difference_type i) const
  9411. {
  9412. return static_cast<json_reverse_iterator>(base_iterator::operator-(i));
  9413. }
  9414. /// return difference
  9415. difference_type operator-(const json_reverse_iterator& other) const
  9416. {
  9417. return base_iterator(*this) - base_iterator(other);
  9418. }
  9419. /// access to successor
  9420. reference operator[](difference_type n) const
  9421. {
  9422. return *(this->operator+(n));
  9423. }
  9424. /// return the key of an object iterator
  9425. auto key() const -> decltype(std::declval<Base>().key())
  9426. {
  9427. auto it = --this->base();
  9428. return it.key();
  9429. }
  9430. /// return the value of an iterator
  9431. reference value() const
  9432. {
  9433. auto it = --this->base();
  9434. return it.operator * ();
  9435. }
  9436. };
  9437. } // namespace detail
  9438. } // namespace nlohmann
  9439. // #include <nlohmann/detail/iterators/primitive_iterator.hpp>
  9440. // #include <nlohmann/detail/json_pointer.hpp>
  9441. #include <algorithm> // all_of
  9442. #include <cassert> // assert
  9443. #include <cctype> // isdigit
  9444. #include <numeric> // accumulate
  9445. #include <string> // string
  9446. #include <utility> // move
  9447. #include <vector> // vector
  9448. // #include <nlohmann/detail/exceptions.hpp>
  9449. // #include <nlohmann/detail/macro_scope.hpp>
  9450. // #include <nlohmann/detail/value_t.hpp>
  9451. namespace nlohmann
  9452. {
  9453. template<typename BasicJsonType>
  9454. class json_pointer
  9455. {
  9456. // allow basic_json to access private members
  9457. NLOHMANN_BASIC_JSON_TPL_DECLARATION
  9458. friend class basic_json;
  9459. public:
  9460. /*!
  9461. @brief create JSON pointer
  9462. Create a JSON pointer according to the syntax described in
  9463. [Section 3 of RFC6901](https://tools.ietf.org/html/rfc6901#section-3).
  9464. @param[in] s string representing the JSON pointer; if omitted, the empty
  9465. string is assumed which references the whole JSON value
  9466. @throw parse_error.107 if the given JSON pointer @a s is nonempty and does
  9467. not begin with a slash (`/`); see example below
  9468. @throw parse_error.108 if a tilde (`~`) in the given JSON pointer @a s is
  9469. not followed by `0` (representing `~`) or `1` (representing `/`); see
  9470. example below
  9471. @liveexample{The example shows the construction several valid JSON pointers
  9472. as well as the exceptional behavior.,json_pointer}
  9473. @since version 2.0.0
  9474. */
  9475. explicit json_pointer(const std::string& s = "")
  9476. : reference_tokens(split(s))
  9477. {}
  9478. /*!
  9479. @brief return a string representation of the JSON pointer
  9480. @invariant For each JSON pointer `ptr`, it holds:
  9481. @code {.cpp}
  9482. ptr == json_pointer(ptr.to_string());
  9483. @endcode
  9484. @return a string representation of the JSON pointer
  9485. @liveexample{The example shows the result of `to_string`.,json_pointer__to_string}
  9486. @since version 2.0.0
  9487. */
  9488. std::string to_string() const
  9489. {
  9490. return std::accumulate(reference_tokens.begin(), reference_tokens.end(),
  9491. std::string{},
  9492. [](const std::string & a, const std::string & b)
  9493. {
  9494. return a + "/" + escape(b);
  9495. });
  9496. }
  9497. /// @copydoc to_string()
  9498. operator std::string() const
  9499. {
  9500. return to_string();
  9501. }
  9502. /*!
  9503. @brief append another JSON pointer at the end of this JSON pointer
  9504. @param[in] ptr JSON pointer to append
  9505. @return JSON pointer with @a ptr appended
  9506. @liveexample{The example shows the usage of `operator/=`.,json_pointer__operator_add}
  9507. @complexity Linear in the length of @a ptr.
  9508. @sa @ref operator/=(std::string) to append a reference token
  9509. @sa @ref operator/=(std::size_t) to append an array index
  9510. @sa @ref operator/(const json_pointer&, const json_pointer&) for a binary operator
  9511. @since version 3.6.0
  9512. */
  9513. json_pointer& operator/=(const json_pointer& ptr)
  9514. {
  9515. reference_tokens.insert(reference_tokens.end(),
  9516. ptr.reference_tokens.begin(),
  9517. ptr.reference_tokens.end());
  9518. return *this;
  9519. }
  9520. /*!
  9521. @brief append an unescaped reference token at the end of this JSON pointer
  9522. @param[in] token reference token to append
  9523. @return JSON pointer with @a token appended without escaping @a token
  9524. @liveexample{The example shows the usage of `operator/=`.,json_pointer__operator_add}
  9525. @complexity Amortized constant.
  9526. @sa @ref operator/=(const json_pointer&) to append a JSON pointer
  9527. @sa @ref operator/=(std::size_t) to append an array index
  9528. @sa @ref operator/(const json_pointer&, std::size_t) for a binary operator
  9529. @since version 3.6.0
  9530. */
  9531. json_pointer& operator/=(std::string token)
  9532. {
  9533. push_back(std::move(token));
  9534. return *this;
  9535. }
  9536. /*!
  9537. @brief append an array index at the end of this JSON pointer
  9538. @param[in] array_idx array index to append
  9539. @return JSON pointer with @a array_idx appended
  9540. @liveexample{The example shows the usage of `operator/=`.,json_pointer__operator_add}
  9541. @complexity Amortized constant.
  9542. @sa @ref operator/=(const json_pointer&) to append a JSON pointer
  9543. @sa @ref operator/=(std::string) to append a reference token
  9544. @sa @ref operator/(const json_pointer&, std::string) for a binary operator
  9545. @since version 3.6.0
  9546. */
  9547. json_pointer& operator/=(std::size_t array_idx)
  9548. {
  9549. return *this /= std::to_string(array_idx);
  9550. }
  9551. /*!
  9552. @brief create a new JSON pointer by appending the right JSON pointer at the end of the left JSON pointer
  9553. @param[in] lhs JSON pointer
  9554. @param[in] rhs JSON pointer
  9555. @return a new JSON pointer with @a rhs appended to @a lhs
  9556. @liveexample{The example shows the usage of `operator/`.,json_pointer__operator_add_binary}
  9557. @complexity Linear in the length of @a lhs and @a rhs.
  9558. @sa @ref operator/=(const json_pointer&) to append a JSON pointer
  9559. @since version 3.6.0
  9560. */
  9561. friend json_pointer operator/(const json_pointer& lhs,
  9562. const json_pointer& rhs)
  9563. {
  9564. return json_pointer(lhs) /= rhs;
  9565. }
  9566. /*!
  9567. @brief create a new JSON pointer by appending the unescaped token at the end of the JSON pointer
  9568. @param[in] ptr JSON pointer
  9569. @param[in] token reference token
  9570. @return a new JSON pointer with unescaped @a token appended to @a ptr
  9571. @liveexample{The example shows the usage of `operator/`.,json_pointer__operator_add_binary}
  9572. @complexity Linear in the length of @a ptr.
  9573. @sa @ref operator/=(std::string) to append a reference token
  9574. @since version 3.6.0
  9575. */
  9576. friend json_pointer operator/(const json_pointer& ptr, std::string token)
  9577. {
  9578. return json_pointer(ptr) /= std::move(token);
  9579. }
  9580. /*!
  9581. @brief create a new JSON pointer by appending the array-index-token at the end of the JSON pointer
  9582. @param[in] ptr JSON pointer
  9583. @param[in] array_idx array index
  9584. @return a new JSON pointer with @a array_idx appended to @a ptr
  9585. @liveexample{The example shows the usage of `operator/`.,json_pointer__operator_add_binary}
  9586. @complexity Linear in the length of @a ptr.
  9587. @sa @ref operator/=(std::size_t) to append an array index
  9588. @since version 3.6.0
  9589. */
  9590. friend json_pointer operator/(const json_pointer& ptr, std::size_t array_idx)
  9591. {
  9592. return json_pointer(ptr) /= array_idx;
  9593. }
  9594. /*!
  9595. @brief returns the parent of this JSON pointer
  9596. @return parent of this JSON pointer; in case this JSON pointer is the root,
  9597. the root itself is returned
  9598. @complexity Linear in the length of the JSON pointer.
  9599. @liveexample{The example shows the result of `parent_pointer` for different
  9600. JSON Pointers.,json_pointer__parent_pointer}
  9601. @since version 3.6.0
  9602. */
  9603. json_pointer parent_pointer() const
  9604. {
  9605. if (empty())
  9606. {
  9607. return *this;
  9608. }
  9609. json_pointer res = *this;
  9610. res.pop_back();
  9611. return res;
  9612. }
  9613. /*!
  9614. @brief remove last reference token
  9615. @pre not `empty()`
  9616. @liveexample{The example shows the usage of `pop_back`.,json_pointer__pop_back}
  9617. @complexity Constant.
  9618. @throw out_of_range.405 if JSON pointer has no parent
  9619. @since version 3.6.0
  9620. */
  9621. void pop_back()
  9622. {
  9623. if (JSON_HEDLEY_UNLIKELY(empty()))
  9624. {
  9625. JSON_THROW(detail::out_of_range::create(405, "JSON pointer has no parent"));
  9626. }
  9627. reference_tokens.pop_back();
  9628. }
  9629. /*!
  9630. @brief return last reference token
  9631. @pre not `empty()`
  9632. @return last reference token
  9633. @liveexample{The example shows the usage of `back`.,json_pointer__back}
  9634. @complexity Constant.
  9635. @throw out_of_range.405 if JSON pointer has no parent
  9636. @since version 3.6.0
  9637. */
  9638. const std::string& back() const
  9639. {
  9640. if (JSON_HEDLEY_UNLIKELY(empty()))
  9641. {
  9642. JSON_THROW(detail::out_of_range::create(405, "JSON pointer has no parent"));
  9643. }
  9644. return reference_tokens.back();
  9645. }
  9646. /*!
  9647. @brief append an unescaped token at the end of the reference pointer
  9648. @param[in] token token to add
  9649. @complexity Amortized constant.
  9650. @liveexample{The example shows the result of `push_back` for different
  9651. JSON Pointers.,json_pointer__push_back}
  9652. @since version 3.6.0
  9653. */
  9654. void push_back(const std::string& token)
  9655. {
  9656. reference_tokens.push_back(token);
  9657. }
  9658. /// @copydoc push_back(const std::string&)
  9659. void push_back(std::string&& token)
  9660. {
  9661. reference_tokens.push_back(std::move(token));
  9662. }
  9663. /*!
  9664. @brief return whether pointer points to the root document
  9665. @return true iff the JSON pointer points to the root document
  9666. @complexity Constant.
  9667. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  9668. @liveexample{The example shows the result of `empty` for different JSON
  9669. Pointers.,json_pointer__empty}
  9670. @since version 3.6.0
  9671. */
  9672. bool empty() const noexcept
  9673. {
  9674. return reference_tokens.empty();
  9675. }
  9676. private:
  9677. /*!
  9678. @param[in] s reference token to be converted into an array index
  9679. @return integer representation of @a s
  9680. @throw out_of_range.404 if string @a s could not be converted to an integer
  9681. */
  9682. static int array_index(const std::string& s)
  9683. {
  9684. // error condition (cf. RFC 6901, Sect. 4)
  9685. if (JSON_HEDLEY_UNLIKELY(s.size() > 1 and s[0] == '0'))
  9686. {
  9687. JSON_THROW(detail::parse_error::create(106, 0,
  9688. "array index '" + s +
  9689. "' must not begin with '0'"));
  9690. }
  9691. // error condition (cf. RFC 6901, Sect. 4)
  9692. if (JSON_HEDLEY_UNLIKELY(s.size() > 1 and not (s[0] >= '1' and s[0] <= '9')))
  9693. {
  9694. JSON_THROW(detail::parse_error::create(109, 0, "array index '" + s + "' is not a number"));
  9695. }
  9696. std::size_t processed_chars = 0;
  9697. int res = 0;
  9698. JSON_TRY
  9699. {
  9700. res = std::stoi(s, &processed_chars);
  9701. }
  9702. JSON_CATCH(std::out_of_range&)
  9703. {
  9704. JSON_THROW(detail::out_of_range::create(404, "unresolved reference token '" + s + "'"));
  9705. }
  9706. // check if the string was completely read
  9707. if (JSON_HEDLEY_UNLIKELY(processed_chars != s.size()))
  9708. {
  9709. JSON_THROW(detail::out_of_range::create(404, "unresolved reference token '" + s + "'"));
  9710. }
  9711. return res;
  9712. }
  9713. json_pointer top() const
  9714. {
  9715. if (JSON_HEDLEY_UNLIKELY(empty()))
  9716. {
  9717. JSON_THROW(detail::out_of_range::create(405, "JSON pointer has no parent"));
  9718. }
  9719. json_pointer result = *this;
  9720. result.reference_tokens = {reference_tokens[0]};
  9721. return result;
  9722. }
  9723. /*!
  9724. @brief create and return a reference to the pointed to value
  9725. @complexity Linear in the number of reference tokens.
  9726. @throw parse_error.109 if array index is not a number
  9727. @throw type_error.313 if value cannot be unflattened
  9728. */
  9729. BasicJsonType& get_and_create(BasicJsonType& j) const
  9730. {
  9731. using size_type = typename BasicJsonType::size_type;
  9732. auto result = &j;
  9733. // in case no reference tokens exist, return a reference to the JSON value
  9734. // j which will be overwritten by a primitive value
  9735. for (const auto& reference_token : reference_tokens)
  9736. {
  9737. switch (result->type())
  9738. {
  9739. case detail::value_t::null:
  9740. {
  9741. if (reference_token == "0")
  9742. {
  9743. // start a new array if reference token is 0
  9744. result = &result->operator[](0);
  9745. }
  9746. else
  9747. {
  9748. // start a new object otherwise
  9749. result = &result->operator[](reference_token);
  9750. }
  9751. break;
  9752. }
  9753. case detail::value_t::object:
  9754. {
  9755. // create an entry in the object
  9756. result = &result->operator[](reference_token);
  9757. break;
  9758. }
  9759. case detail::value_t::array:
  9760. {
  9761. // create an entry in the array
  9762. result = &result->operator[](static_cast<size_type>(array_index(reference_token)));
  9763. break;
  9764. }
  9765. /*
  9766. The following code is only reached if there exists a reference
  9767. token _and_ the current value is primitive. In this case, we have
  9768. an error situation, because primitive values may only occur as
  9769. single value; that is, with an empty list of reference tokens.
  9770. */
  9771. default:
  9772. JSON_THROW(detail::type_error::create(313, "invalid value to unflatten"));
  9773. }
  9774. }
  9775. return *result;
  9776. }
  9777. /*!
  9778. @brief return a reference to the pointed to value
  9779. @note This version does not throw if a value is not present, but tries to
  9780. create nested values instead. For instance, calling this function
  9781. with pointer `"/this/that"` on a null value is equivalent to calling
  9782. `operator[]("this").operator[]("that")` on that value, effectively
  9783. changing the null value to an object.
  9784. @param[in] ptr a JSON value
  9785. @return reference to the JSON value pointed to by the JSON pointer
  9786. @complexity Linear in the length of the JSON pointer.
  9787. @throw parse_error.106 if an array index begins with '0'
  9788. @throw parse_error.109 if an array index was not a number
  9789. @throw out_of_range.404 if the JSON pointer can not be resolved
  9790. */
  9791. BasicJsonType& get_unchecked(BasicJsonType* ptr) const
  9792. {
  9793. using size_type = typename BasicJsonType::size_type;
  9794. for (const auto& reference_token : reference_tokens)
  9795. {
  9796. // convert null values to arrays or objects before continuing
  9797. if (ptr->is_null())
  9798. {
  9799. // check if reference token is a number
  9800. const bool nums =
  9801. std::all_of(reference_token.begin(), reference_token.end(),
  9802. [](const unsigned char x)
  9803. {
  9804. return std::isdigit(x);
  9805. });
  9806. // change value to array for numbers or "-" or to object otherwise
  9807. *ptr = (nums or reference_token == "-")
  9808. ? detail::value_t::array
  9809. : detail::value_t::object;
  9810. }
  9811. switch (ptr->type())
  9812. {
  9813. case detail::value_t::object:
  9814. {
  9815. // use unchecked object access
  9816. ptr = &ptr->operator[](reference_token);
  9817. break;
  9818. }
  9819. case detail::value_t::array:
  9820. {
  9821. if (reference_token == "-")
  9822. {
  9823. // explicitly treat "-" as index beyond the end
  9824. ptr = &ptr->operator[](ptr->m_value.array->size());
  9825. }
  9826. else
  9827. {
  9828. // convert array index to number; unchecked access
  9829. ptr = &ptr->operator[](
  9830. static_cast<size_type>(array_index(reference_token)));
  9831. }
  9832. break;
  9833. }
  9834. default:
  9835. JSON_THROW(detail::out_of_range::create(404, "unresolved reference token '" + reference_token + "'"));
  9836. }
  9837. }
  9838. return *ptr;
  9839. }
  9840. /*!
  9841. @throw parse_error.106 if an array index begins with '0'
  9842. @throw parse_error.109 if an array index was not a number
  9843. @throw out_of_range.402 if the array index '-' is used
  9844. @throw out_of_range.404 if the JSON pointer can not be resolved
  9845. */
  9846. BasicJsonType& get_checked(BasicJsonType* ptr) const
  9847. {
  9848. using size_type = typename BasicJsonType::size_type;
  9849. for (const auto& reference_token : reference_tokens)
  9850. {
  9851. switch (ptr->type())
  9852. {
  9853. case detail::value_t::object:
  9854. {
  9855. // note: at performs range check
  9856. ptr = &ptr->at(reference_token);
  9857. break;
  9858. }
  9859. case detail::value_t::array:
  9860. {
  9861. if (JSON_HEDLEY_UNLIKELY(reference_token == "-"))
  9862. {
  9863. // "-" always fails the range check
  9864. JSON_THROW(detail::out_of_range::create(402,
  9865. "array index '-' (" + std::to_string(ptr->m_value.array->size()) +
  9866. ") is out of range"));
  9867. }
  9868. // note: at performs range check
  9869. ptr = &ptr->at(static_cast<size_type>(array_index(reference_token)));
  9870. break;
  9871. }
  9872. default:
  9873. JSON_THROW(detail::out_of_range::create(404, "unresolved reference token '" + reference_token + "'"));
  9874. }
  9875. }
  9876. return *ptr;
  9877. }
  9878. /*!
  9879. @brief return a const reference to the pointed to value
  9880. @param[in] ptr a JSON value
  9881. @return const reference to the JSON value pointed to by the JSON
  9882. pointer
  9883. @throw parse_error.106 if an array index begins with '0'
  9884. @throw parse_error.109 if an array index was not a number
  9885. @throw out_of_range.402 if the array index '-' is used
  9886. @throw out_of_range.404 if the JSON pointer can not be resolved
  9887. */
  9888. const BasicJsonType& get_unchecked(const BasicJsonType* ptr) const
  9889. {
  9890. using size_type = typename BasicJsonType::size_type;
  9891. for (const auto& reference_token : reference_tokens)
  9892. {
  9893. switch (ptr->type())
  9894. {
  9895. case detail::value_t::object:
  9896. {
  9897. // use unchecked object access
  9898. ptr = &ptr->operator[](reference_token);
  9899. break;
  9900. }
  9901. case detail::value_t::array:
  9902. {
  9903. if (JSON_HEDLEY_UNLIKELY(reference_token == "-"))
  9904. {
  9905. // "-" cannot be used for const access
  9906. JSON_THROW(detail::out_of_range::create(402,
  9907. "array index '-' (" + std::to_string(ptr->m_value.array->size()) +
  9908. ") is out of range"));
  9909. }
  9910. // use unchecked array access
  9911. ptr = &ptr->operator[](
  9912. static_cast<size_type>(array_index(reference_token)));
  9913. break;
  9914. }
  9915. default:
  9916. JSON_THROW(detail::out_of_range::create(404, "unresolved reference token '" + reference_token + "'"));
  9917. }
  9918. }
  9919. return *ptr;
  9920. }
  9921. /*!
  9922. @throw parse_error.106 if an array index begins with '0'
  9923. @throw parse_error.109 if an array index was not a number
  9924. @throw out_of_range.402 if the array index '-' is used
  9925. @throw out_of_range.404 if the JSON pointer can not be resolved
  9926. */
  9927. const BasicJsonType& get_checked(const BasicJsonType* ptr) const
  9928. {
  9929. using size_type = typename BasicJsonType::size_type;
  9930. for (const auto& reference_token : reference_tokens)
  9931. {
  9932. switch (ptr->type())
  9933. {
  9934. case detail::value_t::object:
  9935. {
  9936. // note: at performs range check
  9937. ptr = &ptr->at(reference_token);
  9938. break;
  9939. }
  9940. case detail::value_t::array:
  9941. {
  9942. if (JSON_HEDLEY_UNLIKELY(reference_token == "-"))
  9943. {
  9944. // "-" always fails the range check
  9945. JSON_THROW(detail::out_of_range::create(402,
  9946. "array index '-' (" + std::to_string(ptr->m_value.array->size()) +
  9947. ") is out of range"));
  9948. }
  9949. // note: at performs range check
  9950. ptr = &ptr->at(static_cast<size_type>(array_index(reference_token)));
  9951. break;
  9952. }
  9953. default:
  9954. JSON_THROW(detail::out_of_range::create(404, "unresolved reference token '" + reference_token + "'"));
  9955. }
  9956. }
  9957. return *ptr;
  9958. }
  9959. /*!
  9960. @throw parse_error.106 if an array index begins with '0'
  9961. @throw parse_error.109 if an array index was not a number
  9962. */
  9963. bool contains(const BasicJsonType* ptr) const
  9964. {
  9965. using size_type = typename BasicJsonType::size_type;
  9966. for (const auto& reference_token : reference_tokens)
  9967. {
  9968. switch (ptr->type())
  9969. {
  9970. case detail::value_t::object:
  9971. {
  9972. if (not ptr->contains(reference_token))
  9973. {
  9974. // we did not find the key in the object
  9975. return false;
  9976. }
  9977. ptr = &ptr->operator[](reference_token);
  9978. break;
  9979. }
  9980. case detail::value_t::array:
  9981. {
  9982. if (JSON_HEDLEY_UNLIKELY(reference_token == "-"))
  9983. {
  9984. // "-" always fails the range check
  9985. return false;
  9986. }
  9987. if (JSON_HEDLEY_UNLIKELY(reference_token.size() == 1 and not ("0" <= reference_token and reference_token <= "9")))
  9988. {
  9989. // invalid char
  9990. return false;
  9991. }
  9992. if (JSON_HEDLEY_UNLIKELY(reference_token.size() > 1))
  9993. {
  9994. if (JSON_HEDLEY_UNLIKELY(not ('1' <= reference_token[0] and reference_token[0] <= '9')))
  9995. {
  9996. // first char should be between '1' and '9'
  9997. return false;
  9998. }
  9999. for (std::size_t i = 1; i < reference_token.size(); i++)
  10000. {
  10001. if (JSON_HEDLEY_UNLIKELY(not ('0' <= reference_token[i] and reference_token[i] <= '9')))
  10002. {
  10003. // other char should be between '0' and '9'
  10004. return false;
  10005. }
  10006. }
  10007. }
  10008. const auto idx = static_cast<size_type>(array_index(reference_token));
  10009. if (idx >= ptr->size())
  10010. {
  10011. // index out of range
  10012. return false;
  10013. }
  10014. ptr = &ptr->operator[](idx);
  10015. break;
  10016. }
  10017. default:
  10018. {
  10019. // we do not expect primitive values if there is still a
  10020. // reference token to process
  10021. return false;
  10022. }
  10023. }
  10024. }
  10025. // no reference token left means we found a primitive value
  10026. return true;
  10027. }
  10028. /*!
  10029. @brief split the string input to reference tokens
  10030. @note This function is only called by the json_pointer constructor.
  10031. All exceptions below are documented there.
  10032. @throw parse_error.107 if the pointer is not empty or begins with '/'
  10033. @throw parse_error.108 if character '~' is not followed by '0' or '1'
  10034. */
  10035. static std::vector<std::string> split(const std::string& reference_string)
  10036. {
  10037. std::vector<std::string> result;
  10038. // special case: empty reference string -> no reference tokens
  10039. if (reference_string.empty())
  10040. {
  10041. return result;
  10042. }
  10043. // check if nonempty reference string begins with slash
  10044. if (JSON_HEDLEY_UNLIKELY(reference_string[0] != '/'))
  10045. {
  10046. JSON_THROW(detail::parse_error::create(107, 1,
  10047. "JSON pointer must be empty or begin with '/' - was: '" +
  10048. reference_string + "'"));
  10049. }
  10050. // extract the reference tokens:
  10051. // - slash: position of the last read slash (or end of string)
  10052. // - start: position after the previous slash
  10053. for (
  10054. // search for the first slash after the first character
  10055. std::size_t slash = reference_string.find_first_of('/', 1),
  10056. // set the beginning of the first reference token
  10057. start = 1;
  10058. // we can stop if start == 0 (if slash == std::string::npos)
  10059. start != 0;
  10060. // set the beginning of the next reference token
  10061. // (will eventually be 0 if slash == std::string::npos)
  10062. start = (slash == std::string::npos) ? 0 : slash + 1,
  10063. // find next slash
  10064. slash = reference_string.find_first_of('/', start))
  10065. {
  10066. // use the text between the beginning of the reference token
  10067. // (start) and the last slash (slash).
  10068. auto reference_token = reference_string.substr(start, slash - start);
  10069. // check reference tokens are properly escaped
  10070. for (std::size_t pos = reference_token.find_first_of('~');
  10071. pos != std::string::npos;
  10072. pos = reference_token.find_first_of('~', pos + 1))
  10073. {
  10074. assert(reference_token[pos] == '~');
  10075. // ~ must be followed by 0 or 1
  10076. if (JSON_HEDLEY_UNLIKELY(pos == reference_token.size() - 1 or
  10077. (reference_token[pos + 1] != '0' and
  10078. reference_token[pos + 1] != '1')))
  10079. {
  10080. JSON_THROW(detail::parse_error::create(108, 0, "escape character '~' must be followed with '0' or '1'"));
  10081. }
  10082. }
  10083. // finally, store the reference token
  10084. unescape(reference_token);
  10085. result.push_back(reference_token);
  10086. }
  10087. return result;
  10088. }
  10089. /*!
  10090. @brief replace all occurrences of a substring by another string
  10091. @param[in,out] s the string to manipulate; changed so that all
  10092. occurrences of @a f are replaced with @a t
  10093. @param[in] f the substring to replace with @a t
  10094. @param[in] t the string to replace @a f
  10095. @pre The search string @a f must not be empty. **This precondition is
  10096. enforced with an assertion.**
  10097. @since version 2.0.0
  10098. */
  10099. static void replace_substring(std::string& s, const std::string& f,
  10100. const std::string& t)
  10101. {
  10102. assert(not f.empty());
  10103. for (auto pos = s.find(f); // find first occurrence of f
  10104. pos != std::string::npos; // make sure f was found
  10105. s.replace(pos, f.size(), t), // replace with t, and
  10106. pos = s.find(f, pos + t.size())) // find next occurrence of f
  10107. {}
  10108. }
  10109. /// escape "~" to "~0" and "/" to "~1"
  10110. static std::string escape(std::string s)
  10111. {
  10112. replace_substring(s, "~", "~0");
  10113. replace_substring(s, "/", "~1");
  10114. return s;
  10115. }
  10116. /// unescape "~1" to tilde and "~0" to slash (order is important!)
  10117. static void unescape(std::string& s)
  10118. {
  10119. replace_substring(s, "~1", "/");
  10120. replace_substring(s, "~0", "~");
  10121. }
  10122. /*!
  10123. @param[in] reference_string the reference string to the current value
  10124. @param[in] value the value to consider
  10125. @param[in,out] result the result object to insert values to
  10126. @note Empty objects or arrays are flattened to `null`.
  10127. */
  10128. static void flatten(const std::string& reference_string,
  10129. const BasicJsonType& value,
  10130. BasicJsonType& result)
  10131. {
  10132. switch (value.type())
  10133. {
  10134. case detail::value_t::array:
  10135. {
  10136. if (value.m_value.array->empty())
  10137. {
  10138. // flatten empty array as null
  10139. result[reference_string] = nullptr;
  10140. }
  10141. else
  10142. {
  10143. // iterate array and use index as reference string
  10144. for (std::size_t i = 0; i < value.m_value.array->size(); ++i)
  10145. {
  10146. flatten(reference_string + "/" + std::to_string(i),
  10147. value.m_value.array->operator[](i), result);
  10148. }
  10149. }
  10150. break;
  10151. }
  10152. case detail::value_t::object:
  10153. {
  10154. if (value.m_value.object->empty())
  10155. {
  10156. // flatten empty object as null
  10157. result[reference_string] = nullptr;
  10158. }
  10159. else
  10160. {
  10161. // iterate object and use keys as reference string
  10162. for (const auto& element : *value.m_value.object)
  10163. {
  10164. flatten(reference_string + "/" + escape(element.first), element.second, result);
  10165. }
  10166. }
  10167. break;
  10168. }
  10169. default:
  10170. {
  10171. // add primitive value with its reference string
  10172. result[reference_string] = value;
  10173. break;
  10174. }
  10175. }
  10176. }
  10177. /*!
  10178. @param[in] value flattened JSON
  10179. @return unflattened JSON
  10180. @throw parse_error.109 if array index is not a number
  10181. @throw type_error.314 if value is not an object
  10182. @throw type_error.315 if object values are not primitive
  10183. @throw type_error.313 if value cannot be unflattened
  10184. */
  10185. static BasicJsonType
  10186. unflatten(const BasicJsonType& value)
  10187. {
  10188. if (JSON_HEDLEY_UNLIKELY(not value.is_object()))
  10189. {
  10190. JSON_THROW(detail::type_error::create(314, "only objects can be unflattened"));
  10191. }
  10192. BasicJsonType result;
  10193. // iterate the JSON object values
  10194. for (const auto& element : *value.m_value.object)
  10195. {
  10196. if (JSON_HEDLEY_UNLIKELY(not element.second.is_primitive()))
  10197. {
  10198. JSON_THROW(detail::type_error::create(315, "values in object must be primitive"));
  10199. }
  10200. // assign value to reference pointed to by JSON pointer; Note that if
  10201. // the JSON pointer is "" (i.e., points to the whole value), function
  10202. // get_and_create returns a reference to result itself. An assignment
  10203. // will then create a primitive value.
  10204. json_pointer(element.first).get_and_create(result) = element.second;
  10205. }
  10206. return result;
  10207. }
  10208. /*!
  10209. @brief compares two JSON pointers for equality
  10210. @param[in] lhs JSON pointer to compare
  10211. @param[in] rhs JSON pointer to compare
  10212. @return whether @a lhs is equal to @a rhs
  10213. @complexity Linear in the length of the JSON pointer
  10214. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  10215. */
  10216. friend bool operator==(json_pointer const& lhs,
  10217. json_pointer const& rhs) noexcept
  10218. {
  10219. return lhs.reference_tokens == rhs.reference_tokens;
  10220. }
  10221. /*!
  10222. @brief compares two JSON pointers for inequality
  10223. @param[in] lhs JSON pointer to compare
  10224. @param[in] rhs JSON pointer to compare
  10225. @return whether @a lhs is not equal @a rhs
  10226. @complexity Linear in the length of the JSON pointer
  10227. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  10228. */
  10229. friend bool operator!=(json_pointer const& lhs,
  10230. json_pointer const& rhs) noexcept
  10231. {
  10232. return not (lhs == rhs);
  10233. }
  10234. /// the reference tokens
  10235. std::vector<std::string> reference_tokens;
  10236. };
  10237. } // namespace nlohmann
  10238. // #include <nlohmann/detail/json_ref.hpp>
  10239. #include <initializer_list>
  10240. #include <utility>
  10241. // #include <nlohmann/detail/meta/type_traits.hpp>
  10242. namespace nlohmann
  10243. {
  10244. namespace detail
  10245. {
  10246. template<typename BasicJsonType>
  10247. class json_ref
  10248. {
  10249. public:
  10250. using value_type = BasicJsonType;
  10251. json_ref(value_type&& value)
  10252. : owned_value(std::move(value)), value_ref(&owned_value), is_rvalue(true)
  10253. {}
  10254. json_ref(const value_type& value)
  10255. : value_ref(const_cast<value_type*>(&value)), is_rvalue(false)
  10256. {}
  10257. json_ref(std::initializer_list<json_ref> init)
  10258. : owned_value(init), value_ref(&owned_value), is_rvalue(true)
  10259. {}
  10260. template <
  10261. class... Args,
  10262. enable_if_t<std::is_constructible<value_type, Args...>::value, int> = 0 >
  10263. json_ref(Args && ... args)
  10264. : owned_value(std::forward<Args>(args)...), value_ref(&owned_value),
  10265. is_rvalue(true) {}
  10266. // class should be movable only
  10267. json_ref(json_ref&&) = default;
  10268. json_ref(const json_ref&) = delete;
  10269. json_ref& operator=(const json_ref&) = delete;
  10270. json_ref& operator=(json_ref&&) = delete;
  10271. ~json_ref() = default;
  10272. value_type moved_or_copied() const
  10273. {
  10274. if (is_rvalue)
  10275. {
  10276. return std::move(*value_ref);
  10277. }
  10278. return *value_ref;
  10279. }
  10280. value_type const& operator*() const
  10281. {
  10282. return *static_cast<value_type const*>(value_ref);
  10283. }
  10284. value_type const* operator->() const
  10285. {
  10286. return static_cast<value_type const*>(value_ref);
  10287. }
  10288. private:
  10289. mutable value_type owned_value = nullptr;
  10290. value_type* value_ref = nullptr;
  10291. const bool is_rvalue;
  10292. };
  10293. } // namespace detail
  10294. } // namespace nlohmann
  10295. // #include <nlohmann/detail/macro_scope.hpp>
  10296. // #include <nlohmann/detail/meta/cpp_future.hpp>
  10297. // #include <nlohmann/detail/meta/type_traits.hpp>
  10298. // #include <nlohmann/detail/output/binary_writer.hpp>
  10299. #include <algorithm> // reverse
  10300. #include <array> // array
  10301. #include <cstdint> // uint8_t, uint16_t, uint32_t, uint64_t
  10302. #include <cstring> // memcpy
  10303. #include <limits> // numeric_limits
  10304. #include <string> // string
  10305. // #include <nlohmann/detail/input/binary_reader.hpp>
  10306. // #include <nlohmann/detail/macro_scope.hpp>
  10307. // #include <nlohmann/detail/output/output_adapters.hpp>
  10308. #include <algorithm> // copy
  10309. #include <cstddef> // size_t
  10310. #include <ios> // streamsize
  10311. #include <iterator> // back_inserter
  10312. #include <memory> // shared_ptr, make_shared
  10313. #include <ostream> // basic_ostream
  10314. #include <string> // basic_string
  10315. #include <vector> // vector
  10316. // #include <nlohmann/detail/macro_scope.hpp>
  10317. namespace nlohmann
  10318. {
  10319. namespace detail
  10320. {
  10321. /// abstract output adapter interface
  10322. template<typename CharType> struct output_adapter_protocol
  10323. {
  10324. virtual void write_character(CharType c) = 0;
  10325. virtual void write_characters(const CharType* s, std::size_t length) = 0;
  10326. virtual ~output_adapter_protocol() = default;
  10327. };
  10328. /// a type to simplify interfaces
  10329. template<typename CharType>
  10330. using output_adapter_t = std::shared_ptr<output_adapter_protocol<CharType>>;
  10331. /// output adapter for byte vectors
  10332. template<typename CharType>
  10333. class output_vector_adapter : public output_adapter_protocol<CharType>
  10334. {
  10335. public:
  10336. explicit output_vector_adapter(std::vector<CharType>& vec) noexcept
  10337. : v(vec)
  10338. {}
  10339. void write_character(CharType c) override
  10340. {
  10341. v.push_back(c);
  10342. }
  10343. JSON_HEDLEY_NON_NULL(2)
  10344. void write_characters(const CharType* s, std::size_t length) override
  10345. {
  10346. std::copy(s, s + length, std::back_inserter(v));
  10347. }
  10348. private:
  10349. std::vector<CharType>& v;
  10350. };
  10351. /// output adapter for output streams
  10352. template<typename CharType>
  10353. class output_stream_adapter : public output_adapter_protocol<CharType>
  10354. {
  10355. public:
  10356. explicit output_stream_adapter(std::basic_ostream<CharType>& s) noexcept
  10357. : stream(s)
  10358. {}
  10359. void write_character(CharType c) override
  10360. {
  10361. stream.put(c);
  10362. }
  10363. JSON_HEDLEY_NON_NULL(2)
  10364. void write_characters(const CharType* s, std::size_t length) override
  10365. {
  10366. stream.write(s, static_cast<std::streamsize>(length));
  10367. }
  10368. private:
  10369. std::basic_ostream<CharType>& stream;
  10370. };
  10371. /// output adapter for basic_string
  10372. template<typename CharType, typename StringType = std::basic_string<CharType>>
  10373. class output_string_adapter : public output_adapter_protocol<CharType>
  10374. {
  10375. public:
  10376. explicit output_string_adapter(StringType& s) noexcept
  10377. : str(s)
  10378. {}
  10379. void write_character(CharType c) override
  10380. {
  10381. str.push_back(c);
  10382. }
  10383. JSON_HEDLEY_NON_NULL(2)
  10384. void write_characters(const CharType* s, std::size_t length) override
  10385. {
  10386. str.append(s, length);
  10387. }
  10388. private:
  10389. StringType& str;
  10390. };
  10391. template<typename CharType, typename StringType = std::basic_string<CharType>>
  10392. class output_adapter
  10393. {
  10394. public:
  10395. output_adapter(std::vector<CharType>& vec)
  10396. : oa(std::make_shared<output_vector_adapter<CharType>>(vec)) {}
  10397. output_adapter(std::basic_ostream<CharType>& s)
  10398. : oa(std::make_shared<output_stream_adapter<CharType>>(s)) {}
  10399. output_adapter(StringType& s)
  10400. : oa(std::make_shared<output_string_adapter<CharType, StringType>>(s)) {}
  10401. operator output_adapter_t<CharType>()
  10402. {
  10403. return oa;
  10404. }
  10405. private:
  10406. output_adapter_t<CharType> oa = nullptr;
  10407. };
  10408. } // namespace detail
  10409. } // namespace nlohmann
  10410. namespace nlohmann
  10411. {
  10412. namespace detail
  10413. {
  10414. ///////////////////
  10415. // binary writer //
  10416. ///////////////////
  10417. /*!
  10418. @brief serialization to CBOR and MessagePack values
  10419. */
  10420. template<typename BasicJsonType, typename CharType>
  10421. class binary_writer
  10422. {
  10423. using string_t = typename BasicJsonType::string_t;
  10424. using internal_binary_t = typename BasicJsonType::internal_binary_t;
  10425. public:
  10426. /*!
  10427. @brief create a binary writer
  10428. @param[in] adapter output adapter to write to
  10429. */
  10430. explicit binary_writer(output_adapter_t<CharType> adapter) : oa(adapter)
  10431. {
  10432. assert(oa);
  10433. }
  10434. /*!
  10435. @param[in] j JSON value to serialize
  10436. @pre j.type() == value_t::object
  10437. */
  10438. void write_bson(const BasicJsonType& j)
  10439. {
  10440. switch (j.type())
  10441. {
  10442. case value_t::object:
  10443. {
  10444. write_bson_object(*j.m_value.object);
  10445. break;
  10446. }
  10447. default:
  10448. {
  10449. JSON_THROW(type_error::create(317, "to serialize to BSON, top-level type must be object, but is " + std::string(j.type_name())));
  10450. }
  10451. }
  10452. }
  10453. /*!
  10454. @param[in] j JSON value to serialize
  10455. */
  10456. void write_cbor(const BasicJsonType& j)
  10457. {
  10458. switch (j.type())
  10459. {
  10460. case value_t::null:
  10461. {
  10462. oa->write_character(to_char_type(0xF6));
  10463. break;
  10464. }
  10465. case value_t::boolean:
  10466. {
  10467. oa->write_character(j.m_value.boolean
  10468. ? to_char_type(0xF5)
  10469. : to_char_type(0xF4));
  10470. break;
  10471. }
  10472. case value_t::number_integer:
  10473. {
  10474. if (j.m_value.number_integer >= 0)
  10475. {
  10476. // CBOR does not differentiate between positive signed
  10477. // integers and unsigned integers. Therefore, we used the
  10478. // code from the value_t::number_unsigned case here.
  10479. if (j.m_value.number_integer <= 0x17)
  10480. {
  10481. write_number(static_cast<std::uint8_t>(j.m_value.number_integer));
  10482. }
  10483. else if (j.m_value.number_integer <= (std::numeric_limits<std::uint8_t>::max)())
  10484. {
  10485. oa->write_character(to_char_type(0x18));
  10486. write_number(static_cast<std::uint8_t>(j.m_value.number_integer));
  10487. }
  10488. else if (j.m_value.number_integer <= (std::numeric_limits<std::uint16_t>::max)())
  10489. {
  10490. oa->write_character(to_char_type(0x19));
  10491. write_number(static_cast<std::uint16_t>(j.m_value.number_integer));
  10492. }
  10493. else if (j.m_value.number_integer <= (std::numeric_limits<std::uint32_t>::max)())
  10494. {
  10495. oa->write_character(to_char_type(0x1A));
  10496. write_number(static_cast<std::uint32_t>(j.m_value.number_integer));
  10497. }
  10498. else
  10499. {
  10500. oa->write_character(to_char_type(0x1B));
  10501. write_number(static_cast<std::uint64_t>(j.m_value.number_integer));
  10502. }
  10503. }
  10504. else
  10505. {
  10506. // The conversions below encode the sign in the first
  10507. // byte, and the value is converted to a positive number.
  10508. const auto positive_number = -1 - j.m_value.number_integer;
  10509. if (j.m_value.number_integer >= -24)
  10510. {
  10511. write_number(static_cast<std::uint8_t>(0x20 + positive_number));
  10512. }
  10513. else if (positive_number <= (std::numeric_limits<std::uint8_t>::max)())
  10514. {
  10515. oa->write_character(to_char_type(0x38));
  10516. write_number(static_cast<std::uint8_t>(positive_number));
  10517. }
  10518. else if (positive_number <= (std::numeric_limits<std::uint16_t>::max)())
  10519. {
  10520. oa->write_character(to_char_type(0x39));
  10521. write_number(static_cast<std::uint16_t>(positive_number));
  10522. }
  10523. else if (positive_number <= (std::numeric_limits<std::uint32_t>::max)())
  10524. {
  10525. oa->write_character(to_char_type(0x3A));
  10526. write_number(static_cast<std::uint32_t>(positive_number));
  10527. }
  10528. else
  10529. {
  10530. oa->write_character(to_char_type(0x3B));
  10531. write_number(static_cast<std::uint64_t>(positive_number));
  10532. }
  10533. }
  10534. break;
  10535. }
  10536. case value_t::number_unsigned:
  10537. {
  10538. if (j.m_value.number_unsigned <= 0x17)
  10539. {
  10540. write_number(static_cast<std::uint8_t>(j.m_value.number_unsigned));
  10541. }
  10542. else if (j.m_value.number_unsigned <= (std::numeric_limits<std::uint8_t>::max)())
  10543. {
  10544. oa->write_character(to_char_type(0x18));
  10545. write_number(static_cast<std::uint8_t>(j.m_value.number_unsigned));
  10546. }
  10547. else if (j.m_value.number_unsigned <= (std::numeric_limits<std::uint16_t>::max)())
  10548. {
  10549. oa->write_character(to_char_type(0x19));
  10550. write_number(static_cast<std::uint16_t>(j.m_value.number_unsigned));
  10551. }
  10552. else if (j.m_value.number_unsigned <= (std::numeric_limits<std::uint32_t>::max)())
  10553. {
  10554. oa->write_character(to_char_type(0x1A));
  10555. write_number(static_cast<std::uint32_t>(j.m_value.number_unsigned));
  10556. }
  10557. else
  10558. {
  10559. oa->write_character(to_char_type(0x1B));
  10560. write_number(static_cast<std::uint64_t>(j.m_value.number_unsigned));
  10561. }
  10562. break;
  10563. }
  10564. case value_t::number_float:
  10565. {
  10566. oa->write_character(get_cbor_float_prefix(j.m_value.number_float));
  10567. write_number(j.m_value.number_float);
  10568. break;
  10569. }
  10570. case value_t::string:
  10571. {
  10572. // step 1: write control byte and the string length
  10573. const auto N = j.m_value.string->size();
  10574. if (N <= 0x17)
  10575. {
  10576. write_number(static_cast<std::uint8_t>(0x60 + N));
  10577. }
  10578. else if (N <= (std::numeric_limits<std::uint8_t>::max)())
  10579. {
  10580. oa->write_character(to_char_type(0x78));
  10581. write_number(static_cast<std::uint8_t>(N));
  10582. }
  10583. else if (N <= (std::numeric_limits<std::uint16_t>::max)())
  10584. {
  10585. oa->write_character(to_char_type(0x79));
  10586. write_number(static_cast<std::uint16_t>(N));
  10587. }
  10588. else if (N <= (std::numeric_limits<std::uint32_t>::max)())
  10589. {
  10590. oa->write_character(to_char_type(0x7A));
  10591. write_number(static_cast<std::uint32_t>(N));
  10592. }
  10593. // LCOV_EXCL_START
  10594. else if (N <= (std::numeric_limits<std::uint64_t>::max)())
  10595. {
  10596. oa->write_character(to_char_type(0x7B));
  10597. write_number(static_cast<std::uint64_t>(N));
  10598. }
  10599. // LCOV_EXCL_STOP
  10600. // step 2: write the string
  10601. oa->write_characters(
  10602. reinterpret_cast<const CharType*>(j.m_value.string->c_str()),
  10603. j.m_value.string->size());
  10604. break;
  10605. }
  10606. case value_t::array:
  10607. {
  10608. // step 1: write control byte and the array size
  10609. const auto N = j.m_value.array->size();
  10610. if (N <= 0x17)
  10611. {
  10612. write_number(static_cast<std::uint8_t>(0x80 + N));
  10613. }
  10614. else if (N <= (std::numeric_limits<std::uint8_t>::max)())
  10615. {
  10616. oa->write_character(to_char_type(0x98));
  10617. write_number(static_cast<std::uint8_t>(N));
  10618. }
  10619. else if (N <= (std::numeric_limits<std::uint16_t>::max)())
  10620. {
  10621. oa->write_character(to_char_type(0x99));
  10622. write_number(static_cast<std::uint16_t>(N));
  10623. }
  10624. else if (N <= (std::numeric_limits<std::uint32_t>::max)())
  10625. {
  10626. oa->write_character(to_char_type(0x9A));
  10627. write_number(static_cast<std::uint32_t>(N));
  10628. }
  10629. // LCOV_EXCL_START
  10630. else if (N <= (std::numeric_limits<std::uint64_t>::max)())
  10631. {
  10632. oa->write_character(to_char_type(0x9B));
  10633. write_number(static_cast<std::uint64_t>(N));
  10634. }
  10635. // LCOV_EXCL_STOP
  10636. // step 2: write each element
  10637. for (const auto& el : *j.m_value.array)
  10638. {
  10639. write_cbor(el);
  10640. }
  10641. break;
  10642. }
  10643. case value_t::binary:
  10644. {
  10645. // step 1: write control byte and the binary array size
  10646. const auto N = j.m_value.binary->size();
  10647. if (N <= 0x17)
  10648. {
  10649. write_number(static_cast<std::uint8_t>(0x40 + N));
  10650. }
  10651. else if (N <= (std::numeric_limits<std::uint8_t>::max)())
  10652. {
  10653. oa->write_character(to_char_type(0x58));
  10654. write_number(static_cast<std::uint8_t>(N));
  10655. }
  10656. else if (N <= (std::numeric_limits<std::uint16_t>::max)())
  10657. {
  10658. oa->write_character(to_char_type(0x59));
  10659. write_number(static_cast<std::uint16_t>(N));
  10660. }
  10661. else if (N <= (std::numeric_limits<std::uint32_t>::max)())
  10662. {
  10663. oa->write_character(to_char_type(0x5A));
  10664. write_number(static_cast<std::uint32_t>(N));
  10665. }
  10666. // LCOV_EXCL_START
  10667. else if (N <= (std::numeric_limits<std::uint64_t>::max)())
  10668. {
  10669. oa->write_character(to_char_type(0x5B));
  10670. write_number(static_cast<std::uint64_t>(N));
  10671. }
  10672. // LCOV_EXCL_STOP
  10673. // step 2: write each element
  10674. oa->write_characters(
  10675. reinterpret_cast<const CharType*>(j.m_value.binary->data()),
  10676. N);
  10677. break;
  10678. }
  10679. case value_t::object:
  10680. {
  10681. // step 1: write control byte and the object size
  10682. const auto N = j.m_value.object->size();
  10683. if (N <= 0x17)
  10684. {
  10685. write_number(static_cast<std::uint8_t>(0xA0 + N));
  10686. }
  10687. else if (N <= (std::numeric_limits<std::uint8_t>::max)())
  10688. {
  10689. oa->write_character(to_char_type(0xB8));
  10690. write_number(static_cast<std::uint8_t>(N));
  10691. }
  10692. else if (N <= (std::numeric_limits<std::uint16_t>::max)())
  10693. {
  10694. oa->write_character(to_char_type(0xB9));
  10695. write_number(static_cast<std::uint16_t>(N));
  10696. }
  10697. else if (N <= (std::numeric_limits<std::uint32_t>::max)())
  10698. {
  10699. oa->write_character(to_char_type(0xBA));
  10700. write_number(static_cast<std::uint32_t>(N));
  10701. }
  10702. // LCOV_EXCL_START
  10703. else if (N <= (std::numeric_limits<std::uint64_t>::max)())
  10704. {
  10705. oa->write_character(to_char_type(0xBB));
  10706. write_number(static_cast<std::uint64_t>(N));
  10707. }
  10708. // LCOV_EXCL_STOP
  10709. // step 2: write each element
  10710. for (const auto& el : *j.m_value.object)
  10711. {
  10712. write_cbor(el.first);
  10713. write_cbor(el.second);
  10714. }
  10715. break;
  10716. }
  10717. default:
  10718. break;
  10719. }
  10720. }
  10721. /*!
  10722. @param[in] j JSON value to serialize
  10723. */
  10724. void write_msgpack(const BasicJsonType& j)
  10725. {
  10726. switch (j.type())
  10727. {
  10728. case value_t::null: // nil
  10729. {
  10730. oa->write_character(to_char_type(0xC0));
  10731. break;
  10732. }
  10733. case value_t::boolean: // true and false
  10734. {
  10735. oa->write_character(j.m_value.boolean
  10736. ? to_char_type(0xC3)
  10737. : to_char_type(0xC2));
  10738. break;
  10739. }
  10740. case value_t::number_integer:
  10741. {
  10742. if (j.m_value.number_integer >= 0)
  10743. {
  10744. // MessagePack does not differentiate between positive
  10745. // signed integers and unsigned integers. Therefore, we used
  10746. // the code from the value_t::number_unsigned case here.
  10747. if (j.m_value.number_unsigned < 128)
  10748. {
  10749. // positive fixnum
  10750. write_number(static_cast<std::uint8_t>(j.m_value.number_integer));
  10751. }
  10752. else if (j.m_value.number_unsigned <= (std::numeric_limits<std::uint8_t>::max)())
  10753. {
  10754. // uint 8
  10755. oa->write_character(to_char_type(0xCC));
  10756. write_number(static_cast<std::uint8_t>(j.m_value.number_integer));
  10757. }
  10758. else if (j.m_value.number_unsigned <= (std::numeric_limits<std::uint16_t>::max)())
  10759. {
  10760. // uint 16
  10761. oa->write_character(to_char_type(0xCD));
  10762. write_number(static_cast<std::uint16_t>(j.m_value.number_integer));
  10763. }
  10764. else if (j.m_value.number_unsigned <= (std::numeric_limits<std::uint32_t>::max)())
  10765. {
  10766. // uint 32
  10767. oa->write_character(to_char_type(0xCE));
  10768. write_number(static_cast<std::uint32_t>(j.m_value.number_integer));
  10769. }
  10770. else if (j.m_value.number_unsigned <= (std::numeric_limits<std::uint64_t>::max)())
  10771. {
  10772. // uint 64
  10773. oa->write_character(to_char_type(0xCF));
  10774. write_number(static_cast<std::uint64_t>(j.m_value.number_integer));
  10775. }
  10776. }
  10777. else
  10778. {
  10779. if (j.m_value.number_integer >= -32)
  10780. {
  10781. // negative fixnum
  10782. write_number(static_cast<std::int8_t>(j.m_value.number_integer));
  10783. }
  10784. else if (j.m_value.number_integer >= (std::numeric_limits<std::int8_t>::min)() and
  10785. j.m_value.number_integer <= (std::numeric_limits<std::int8_t>::max)())
  10786. {
  10787. // int 8
  10788. oa->write_character(to_char_type(0xD0));
  10789. write_number(static_cast<std::int8_t>(j.m_value.number_integer));
  10790. }
  10791. else if (j.m_value.number_integer >= (std::numeric_limits<std::int16_t>::min)() and
  10792. j.m_value.number_integer <= (std::numeric_limits<std::int16_t>::max)())
  10793. {
  10794. // int 16
  10795. oa->write_character(to_char_type(0xD1));
  10796. write_number(static_cast<std::int16_t>(j.m_value.number_integer));
  10797. }
  10798. else if (j.m_value.number_integer >= (std::numeric_limits<std::int32_t>::min)() and
  10799. j.m_value.number_integer <= (std::numeric_limits<std::int32_t>::max)())
  10800. {
  10801. // int 32
  10802. oa->write_character(to_char_type(0xD2));
  10803. write_number(static_cast<std::int32_t>(j.m_value.number_integer));
  10804. }
  10805. else if (j.m_value.number_integer >= (std::numeric_limits<std::int64_t>::min)() and
  10806. j.m_value.number_integer <= (std::numeric_limits<std::int64_t>::max)())
  10807. {
  10808. // int 64
  10809. oa->write_character(to_char_type(0xD3));
  10810. write_number(static_cast<std::int64_t>(j.m_value.number_integer));
  10811. }
  10812. }
  10813. break;
  10814. }
  10815. case value_t::number_unsigned:
  10816. {
  10817. if (j.m_value.number_unsigned < 128)
  10818. {
  10819. // positive fixnum
  10820. write_number(static_cast<std::uint8_t>(j.m_value.number_integer));
  10821. }
  10822. else if (j.m_value.number_unsigned <= (std::numeric_limits<std::uint8_t>::max)())
  10823. {
  10824. // uint 8
  10825. oa->write_character(to_char_type(0xCC));
  10826. write_number(static_cast<std::uint8_t>(j.m_value.number_integer));
  10827. }
  10828. else if (j.m_value.number_unsigned <= (std::numeric_limits<std::uint16_t>::max)())
  10829. {
  10830. // uint 16
  10831. oa->write_character(to_char_type(0xCD));
  10832. write_number(static_cast<std::uint16_t>(j.m_value.number_integer));
  10833. }
  10834. else if (j.m_value.number_unsigned <= (std::numeric_limits<std::uint32_t>::max)())
  10835. {
  10836. // uint 32
  10837. oa->write_character(to_char_type(0xCE));
  10838. write_number(static_cast<std::uint32_t>(j.m_value.number_integer));
  10839. }
  10840. else if (j.m_value.number_unsigned <= (std::numeric_limits<std::uint64_t>::max)())
  10841. {
  10842. // uint 64
  10843. oa->write_character(to_char_type(0xCF));
  10844. write_number(static_cast<std::uint64_t>(j.m_value.number_integer));
  10845. }
  10846. break;
  10847. }
  10848. case value_t::number_float:
  10849. {
  10850. oa->write_character(get_msgpack_float_prefix(j.m_value.number_float));
  10851. write_number(j.m_value.number_float);
  10852. break;
  10853. }
  10854. case value_t::string:
  10855. {
  10856. // step 1: write control byte and the string length
  10857. const auto N = j.m_value.string->size();
  10858. if (N <= 31)
  10859. {
  10860. // fixstr
  10861. write_number(static_cast<std::uint8_t>(0xA0 | N));
  10862. }
  10863. else if (N <= (std::numeric_limits<std::uint8_t>::max)())
  10864. {
  10865. // str 8
  10866. oa->write_character(to_char_type(0xD9));
  10867. write_number(static_cast<std::uint8_t>(N));
  10868. }
  10869. else if (N <= (std::numeric_limits<std::uint16_t>::max)())
  10870. {
  10871. // str 16
  10872. oa->write_character(to_char_type(0xDA));
  10873. write_number(static_cast<std::uint16_t>(N));
  10874. }
  10875. else if (N <= (std::numeric_limits<std::uint32_t>::max)())
  10876. {
  10877. // str 32
  10878. oa->write_character(to_char_type(0xDB));
  10879. write_number(static_cast<std::uint32_t>(N));
  10880. }
  10881. // step 2: write the string
  10882. oa->write_characters(
  10883. reinterpret_cast<const CharType*>(j.m_value.string->c_str()),
  10884. j.m_value.string->size());
  10885. break;
  10886. }
  10887. case value_t::array:
  10888. {
  10889. // step 1: write control byte and the array size
  10890. const auto N = j.m_value.array->size();
  10891. if (N <= 15)
  10892. {
  10893. // fixarray
  10894. write_number(static_cast<std::uint8_t>(0x90 | N));
  10895. }
  10896. else if (N <= (std::numeric_limits<std::uint16_t>::max)())
  10897. {
  10898. // array 16
  10899. oa->write_character(to_char_type(0xDC));
  10900. write_number(static_cast<std::uint16_t>(N));
  10901. }
  10902. else if (N <= (std::numeric_limits<std::uint32_t>::max)())
  10903. {
  10904. // array 32
  10905. oa->write_character(to_char_type(0xDD));
  10906. write_number(static_cast<std::uint32_t>(N));
  10907. }
  10908. // step 2: write each element
  10909. for (const auto& el : *j.m_value.array)
  10910. {
  10911. write_msgpack(el);
  10912. }
  10913. break;
  10914. }
  10915. case value_t::binary:
  10916. {
  10917. // step 0: determine if the binary type has a set subtype to
  10918. // determine whether or not to use the ext or fixext types
  10919. const bool use_ext = j.m_value.binary->has_subtype;
  10920. // step 1: write control byte and the byte string length
  10921. const auto N = j.m_value.binary->size();
  10922. if (N <= (std::numeric_limits<std::uint8_t>::max)())
  10923. {
  10924. std::uint8_t output_type;
  10925. bool fixed = true;
  10926. if (use_ext)
  10927. {
  10928. switch (N)
  10929. {
  10930. case 1:
  10931. output_type = 0xD4; // fixext 1
  10932. break;
  10933. case 2:
  10934. output_type = 0xD5; // fixext 2
  10935. break;
  10936. case 4:
  10937. output_type = 0xD6; // fixext 4
  10938. break;
  10939. case 8:
  10940. output_type = 0xD7; // fixext 8
  10941. break;
  10942. case 16:
  10943. output_type = 0xD8; // fixext 16
  10944. break;
  10945. default:
  10946. output_type = 0xC7; // ext 8
  10947. fixed = false;
  10948. break;
  10949. }
  10950. }
  10951. else
  10952. {
  10953. output_type = 0xC4; // bin 8
  10954. fixed = false;
  10955. }
  10956. oa->write_character(to_char_type(output_type));
  10957. if (not fixed)
  10958. {
  10959. write_number(static_cast<std::uint8_t>(N));
  10960. }
  10961. }
  10962. else if (N <= (std::numeric_limits<std::uint16_t>::max)())
  10963. {
  10964. std::uint8_t output_type;
  10965. if (use_ext)
  10966. {
  10967. output_type = 0xC8; // ext 16
  10968. }
  10969. else
  10970. {
  10971. output_type = 0xC5; // bin 16
  10972. }
  10973. oa->write_character(to_char_type(output_type));
  10974. write_number(static_cast<std::uint16_t>(N));
  10975. }
  10976. else if (N <= (std::numeric_limits<std::uint32_t>::max)())
  10977. {
  10978. std::uint8_t output_type;
  10979. if (use_ext)
  10980. {
  10981. output_type = 0xC9; // ext 32
  10982. }
  10983. else
  10984. {
  10985. output_type = 0xC6; // bin 32
  10986. }
  10987. oa->write_character(to_char_type(output_type));
  10988. write_number(static_cast<std::uint32_t>(N));
  10989. }
  10990. // step 1.5: if this is an ext type, write the subtype
  10991. if (use_ext)
  10992. {
  10993. write_number(j.m_value.binary->subtype);
  10994. }
  10995. // step 2: write the byte string
  10996. oa->write_characters(
  10997. reinterpret_cast<const CharType*>(j.m_value.binary->data()),
  10998. N);
  10999. break;
  11000. }
  11001. case value_t::object:
  11002. {
  11003. // step 1: write control byte and the object size
  11004. const auto N = j.m_value.object->size();
  11005. if (N <= 15)
  11006. {
  11007. // fixmap
  11008. write_number(static_cast<std::uint8_t>(0x80 | (N & 0xF)));
  11009. }
  11010. else if (N <= (std::numeric_limits<std::uint16_t>::max)())
  11011. {
  11012. // map 16
  11013. oa->write_character(to_char_type(0xDE));
  11014. write_number(static_cast<std::uint16_t>(N));
  11015. }
  11016. else if (N <= (std::numeric_limits<std::uint32_t>::max)())
  11017. {
  11018. // map 32
  11019. oa->write_character(to_char_type(0xDF));
  11020. write_number(static_cast<std::uint32_t>(N));
  11021. }
  11022. // step 2: write each element
  11023. for (const auto& el : *j.m_value.object)
  11024. {
  11025. write_msgpack(el.first);
  11026. write_msgpack(el.second);
  11027. }
  11028. break;
  11029. }
  11030. default:
  11031. break;
  11032. }
  11033. }
  11034. /*!
  11035. @param[in] j JSON value to serialize
  11036. @param[in] use_count whether to use '#' prefixes (optimized format)
  11037. @param[in] use_type whether to use '$' prefixes (optimized format)
  11038. @param[in] add_prefix whether prefixes need to be used for this value
  11039. */
  11040. void write_ubjson(const BasicJsonType& j, const bool use_count,
  11041. const bool use_type, const bool add_prefix = true)
  11042. {
  11043. switch (j.type())
  11044. {
  11045. case value_t::null:
  11046. {
  11047. if (add_prefix)
  11048. {
  11049. oa->write_character(to_char_type('Z'));
  11050. }
  11051. break;
  11052. }
  11053. case value_t::boolean:
  11054. {
  11055. if (add_prefix)
  11056. {
  11057. oa->write_character(j.m_value.boolean
  11058. ? to_char_type('T')
  11059. : to_char_type('F'));
  11060. }
  11061. break;
  11062. }
  11063. case value_t::number_integer:
  11064. {
  11065. write_number_with_ubjson_prefix(j.m_value.number_integer, add_prefix);
  11066. break;
  11067. }
  11068. case value_t::number_unsigned:
  11069. {
  11070. write_number_with_ubjson_prefix(j.m_value.number_unsigned, add_prefix);
  11071. break;
  11072. }
  11073. case value_t::number_float:
  11074. {
  11075. write_number_with_ubjson_prefix(j.m_value.number_float, add_prefix);
  11076. break;
  11077. }
  11078. case value_t::string:
  11079. {
  11080. if (add_prefix)
  11081. {
  11082. oa->write_character(to_char_type('S'));
  11083. }
  11084. write_number_with_ubjson_prefix(j.m_value.string->size(), true);
  11085. oa->write_characters(
  11086. reinterpret_cast<const CharType*>(j.m_value.string->c_str()),
  11087. j.m_value.string->size());
  11088. break;
  11089. }
  11090. case value_t::array:
  11091. {
  11092. if (add_prefix)
  11093. {
  11094. oa->write_character(to_char_type('['));
  11095. }
  11096. bool prefix_required = true;
  11097. if (use_type and not j.m_value.array->empty())
  11098. {
  11099. assert(use_count);
  11100. const CharType first_prefix = ubjson_prefix(j.front());
  11101. const bool same_prefix = std::all_of(j.begin() + 1, j.end(),
  11102. [this, first_prefix](const BasicJsonType & v)
  11103. {
  11104. return ubjson_prefix(v) == first_prefix;
  11105. });
  11106. if (same_prefix)
  11107. {
  11108. prefix_required = false;
  11109. oa->write_character(to_char_type('$'));
  11110. oa->write_character(first_prefix);
  11111. }
  11112. }
  11113. if (use_count)
  11114. {
  11115. oa->write_character(to_char_type('#'));
  11116. write_number_with_ubjson_prefix(j.m_value.array->size(), true);
  11117. }
  11118. for (const auto& el : *j.m_value.array)
  11119. {
  11120. write_ubjson(el, use_count, use_type, prefix_required);
  11121. }
  11122. if (not use_count)
  11123. {
  11124. oa->write_character(to_char_type(']'));
  11125. }
  11126. break;
  11127. }
  11128. case value_t::binary:
  11129. {
  11130. if (add_prefix)
  11131. {
  11132. oa->write_character(to_char_type('['));
  11133. }
  11134. if (use_type and not j.m_value.binary->empty())
  11135. {
  11136. assert(use_count);
  11137. oa->write_character(to_char_type('$'));
  11138. oa->write_character('U');
  11139. }
  11140. if (use_count)
  11141. {
  11142. oa->write_character(to_char_type('#'));
  11143. write_number_with_ubjson_prefix(j.m_value.binary->size(), true);
  11144. }
  11145. if (use_type)
  11146. {
  11147. oa->write_characters(
  11148. reinterpret_cast<const CharType*>(j.m_value.binary->data()),
  11149. j.m_value.binary->size());
  11150. }
  11151. else
  11152. {
  11153. for (size_t i = 0; i < j.m_value.binary->size(); ++i)
  11154. {
  11155. oa->write_character(to_char_type('U'));
  11156. oa->write_character(j.m_value.binary->data()[i]);
  11157. }
  11158. }
  11159. if (not use_count)
  11160. {
  11161. oa->write_character(to_char_type(']'));
  11162. }
  11163. break;
  11164. }
  11165. case value_t::object:
  11166. {
  11167. if (add_prefix)
  11168. {
  11169. oa->write_character(to_char_type('{'));
  11170. }
  11171. bool prefix_required = true;
  11172. if (use_type and not j.m_value.object->empty())
  11173. {
  11174. assert(use_count);
  11175. const CharType first_prefix = ubjson_prefix(j.front());
  11176. const bool same_prefix = std::all_of(j.begin(), j.end(),
  11177. [this, first_prefix](const BasicJsonType & v)
  11178. {
  11179. return ubjson_prefix(v) == first_prefix;
  11180. });
  11181. if (same_prefix)
  11182. {
  11183. prefix_required = false;
  11184. oa->write_character(to_char_type('$'));
  11185. oa->write_character(first_prefix);
  11186. }
  11187. }
  11188. if (use_count)
  11189. {
  11190. oa->write_character(to_char_type('#'));
  11191. write_number_with_ubjson_prefix(j.m_value.object->size(), true);
  11192. }
  11193. for (const auto& el : *j.m_value.object)
  11194. {
  11195. write_number_with_ubjson_prefix(el.first.size(), true);
  11196. oa->write_characters(
  11197. reinterpret_cast<const CharType*>(el.first.c_str()),
  11198. el.first.size());
  11199. write_ubjson(el.second, use_count, use_type, prefix_required);
  11200. }
  11201. if (not use_count)
  11202. {
  11203. oa->write_character(to_char_type('}'));
  11204. }
  11205. break;
  11206. }
  11207. default:
  11208. break;
  11209. }
  11210. }
  11211. private:
  11212. //////////
  11213. // BSON //
  11214. //////////
  11215. /*!
  11216. @return The size of a BSON document entry header, including the id marker
  11217. and the entry name size (and its null-terminator).
  11218. */
  11219. static std::size_t calc_bson_entry_header_size(const string_t& name)
  11220. {
  11221. const auto it = name.find(static_cast<typename string_t::value_type>(0));
  11222. if (JSON_HEDLEY_UNLIKELY(it != BasicJsonType::string_t::npos))
  11223. {
  11224. JSON_THROW(out_of_range::create(409,
  11225. "BSON key cannot contain code point U+0000 (at byte " + std::to_string(it) + ")"));
  11226. }
  11227. return /*id*/ 1ul + name.size() + /*zero-terminator*/1u;
  11228. }
  11229. /*!
  11230. @brief Writes the given @a element_type and @a name to the output adapter
  11231. */
  11232. void write_bson_entry_header(const string_t& name,
  11233. const std::uint8_t element_type)
  11234. {
  11235. oa->write_character(to_char_type(element_type)); // boolean
  11236. oa->write_characters(
  11237. reinterpret_cast<const CharType*>(name.c_str()),
  11238. name.size() + 1u);
  11239. }
  11240. /*!
  11241. @brief Writes a BSON element with key @a name and boolean value @a value
  11242. */
  11243. void write_bson_boolean(const string_t& name,
  11244. const bool value)
  11245. {
  11246. write_bson_entry_header(name, 0x08);
  11247. oa->write_character(value ? to_char_type(0x01) : to_char_type(0x00));
  11248. }
  11249. /*!
  11250. @brief Writes a BSON element with key @a name and double value @a value
  11251. */
  11252. void write_bson_double(const string_t& name,
  11253. const double value)
  11254. {
  11255. write_bson_entry_header(name, 0x01);
  11256. write_number<double, true>(value);
  11257. }
  11258. /*!
  11259. @return The size of the BSON-encoded string in @a value
  11260. */
  11261. static std::size_t calc_bson_string_size(const string_t& value)
  11262. {
  11263. return sizeof(std::int32_t) + value.size() + 1ul;
  11264. }
  11265. /*!
  11266. @brief Writes a BSON element with key @a name and string value @a value
  11267. */
  11268. void write_bson_string(const string_t& name,
  11269. const string_t& value)
  11270. {
  11271. write_bson_entry_header(name, 0x02);
  11272. write_number<std::int32_t, true>(static_cast<std::int32_t>(value.size() + 1ul));
  11273. oa->write_characters(
  11274. reinterpret_cast<const CharType*>(value.c_str()),
  11275. value.size() + 1);
  11276. }
  11277. /*!
  11278. @brief Writes a BSON element with key @a name and null value
  11279. */
  11280. void write_bson_null(const string_t& name)
  11281. {
  11282. write_bson_entry_header(name, 0x0A);
  11283. }
  11284. /*!
  11285. @return The size of the BSON-encoded integer @a value
  11286. */
  11287. static std::size_t calc_bson_integer_size(const std::int64_t value)
  11288. {
  11289. return (std::numeric_limits<std::int32_t>::min)() <= value and value <= (std::numeric_limits<std::int32_t>::max)()
  11290. ? sizeof(std::int32_t)
  11291. : sizeof(std::int64_t);
  11292. }
  11293. /*!
  11294. @brief Writes a BSON element with key @a name and integer @a value
  11295. */
  11296. void write_bson_integer(const string_t& name,
  11297. const std::int64_t value)
  11298. {
  11299. if ((std::numeric_limits<std::int32_t>::min)() <= value and value <= (std::numeric_limits<std::int32_t>::max)())
  11300. {
  11301. write_bson_entry_header(name, 0x10); // int32
  11302. write_number<std::int32_t, true>(static_cast<std::int32_t>(value));
  11303. }
  11304. else
  11305. {
  11306. write_bson_entry_header(name, 0x12); // int64
  11307. write_number<std::int64_t, true>(static_cast<std::int64_t>(value));
  11308. }
  11309. }
  11310. /*!
  11311. @return The size of the BSON-encoded unsigned integer in @a j
  11312. */
  11313. static constexpr std::size_t calc_bson_unsigned_size(const std::uint64_t value) noexcept
  11314. {
  11315. return (value <= static_cast<std::uint64_t>((std::numeric_limits<std::int32_t>::max)()))
  11316. ? sizeof(std::int32_t)
  11317. : sizeof(std::int64_t);
  11318. }
  11319. /*!
  11320. @brief Writes a BSON element with key @a name and unsigned @a value
  11321. */
  11322. void write_bson_unsigned(const string_t& name,
  11323. const std::uint64_t value)
  11324. {
  11325. if (value <= static_cast<std::uint64_t>((std::numeric_limits<std::int32_t>::max)()))
  11326. {
  11327. write_bson_entry_header(name, 0x10 /* int32 */);
  11328. write_number<std::int32_t, true>(static_cast<std::int32_t>(value));
  11329. }
  11330. else if (value <= static_cast<std::uint64_t>((std::numeric_limits<std::int64_t>::max)()))
  11331. {
  11332. write_bson_entry_header(name, 0x12 /* int64 */);
  11333. write_number<std::int64_t, true>(static_cast<std::int64_t>(value));
  11334. }
  11335. else
  11336. {
  11337. JSON_THROW(out_of_range::create(407, "integer number " + std::to_string(value) + " cannot be represented by BSON as it does not fit int64"));
  11338. }
  11339. }
  11340. /*!
  11341. @brief Writes a BSON element with key @a name and object @a value
  11342. */
  11343. void write_bson_object_entry(const string_t& name,
  11344. const typename BasicJsonType::object_t& value)
  11345. {
  11346. write_bson_entry_header(name, 0x03); // object
  11347. write_bson_object(value);
  11348. }
  11349. /*!
  11350. @return The size of the BSON-encoded array @a value
  11351. */
  11352. static std::size_t calc_bson_array_size(const typename BasicJsonType::array_t& value)
  11353. {
  11354. std::size_t array_index = 0ul;
  11355. const std::size_t embedded_document_size = std::accumulate(std::begin(value), std::end(value), std::size_t(0), [&array_index](std::size_t result, const typename BasicJsonType::array_t::value_type & el)
  11356. {
  11357. return result + calc_bson_element_size(std::to_string(array_index++), el);
  11358. });
  11359. return sizeof(std::int32_t) + embedded_document_size + 1ul;
  11360. }
  11361. /*!
  11362. @return The size of the BSON-encoded binary array @a value
  11363. */
  11364. static std::size_t calc_bson_binary_size(const typename BasicJsonType::internal_binary_t& value)
  11365. {
  11366. return sizeof(std::int32_t) + value.size() + 1ul;
  11367. }
  11368. /*!
  11369. @brief Writes a BSON element with key @a name and array @a value
  11370. */
  11371. void write_bson_array(const string_t& name,
  11372. const typename BasicJsonType::array_t& value)
  11373. {
  11374. write_bson_entry_header(name, 0x04); // array
  11375. write_number<std::int32_t, true>(static_cast<std::int32_t>(calc_bson_array_size(value)));
  11376. std::size_t array_index = 0ul;
  11377. for (const auto& el : value)
  11378. {
  11379. write_bson_element(std::to_string(array_index++), el);
  11380. }
  11381. oa->write_character(to_char_type(0x00));
  11382. }
  11383. /*!
  11384. @brief Writes a BSON element with key @a name and binary value @a value
  11385. */
  11386. void write_bson_binary(const string_t& name,
  11387. const internal_binary_t& value)
  11388. {
  11389. write_bson_entry_header(name, 0x05);
  11390. write_number<std::int32_t, true>(static_cast<std::int32_t>(value.size()));
  11391. std::uint8_t subtype = 0x00; // Generic Binary Subtype
  11392. if (value.has_subtype)
  11393. {
  11394. subtype = value.subtype;
  11395. }
  11396. write_number(subtype);
  11397. oa->write_characters(reinterpret_cast<const CharType*>(value.data()), value.size());
  11398. }
  11399. /*!
  11400. @brief Calculates the size necessary to serialize the JSON value @a j with its @a name
  11401. @return The calculated size for the BSON document entry for @a j with the given @a name.
  11402. */
  11403. static std::size_t calc_bson_element_size(const string_t& name,
  11404. const BasicJsonType& j)
  11405. {
  11406. const auto header_size = calc_bson_entry_header_size(name);
  11407. switch (j.type())
  11408. {
  11409. case value_t::object:
  11410. return header_size + calc_bson_object_size(*j.m_value.object);
  11411. case value_t::array:
  11412. return header_size + calc_bson_array_size(*j.m_value.array);
  11413. case value_t::binary:
  11414. return header_size + calc_bson_binary_size(*j.m_value.binary);
  11415. case value_t::boolean:
  11416. return header_size + 1ul;
  11417. case value_t::number_float:
  11418. return header_size + 8ul;
  11419. case value_t::number_integer:
  11420. return header_size + calc_bson_integer_size(j.m_value.number_integer);
  11421. case value_t::number_unsigned:
  11422. return header_size + calc_bson_unsigned_size(j.m_value.number_unsigned);
  11423. case value_t::string:
  11424. return header_size + calc_bson_string_size(*j.m_value.string);
  11425. case value_t::null:
  11426. return header_size + 0ul;
  11427. // LCOV_EXCL_START
  11428. default:
  11429. assert(false);
  11430. return 0ul;
  11431. // LCOV_EXCL_STOP
  11432. }
  11433. }
  11434. /*!
  11435. @brief Serializes the JSON value @a j to BSON and associates it with the
  11436. key @a name.
  11437. @param name The name to associate with the JSON entity @a j within the
  11438. current BSON document
  11439. @return The size of the BSON entry
  11440. */
  11441. void write_bson_element(const string_t& name,
  11442. const BasicJsonType& j)
  11443. {
  11444. switch (j.type())
  11445. {
  11446. case value_t::object:
  11447. return write_bson_object_entry(name, *j.m_value.object);
  11448. case value_t::array:
  11449. return write_bson_array(name, *j.m_value.array);
  11450. case value_t::binary:
  11451. return write_bson_binary(name, *j.m_value.binary);
  11452. case value_t::boolean:
  11453. return write_bson_boolean(name, j.m_value.boolean);
  11454. case value_t::number_float:
  11455. return write_bson_double(name, j.m_value.number_float);
  11456. case value_t::number_integer:
  11457. return write_bson_integer(name, j.m_value.number_integer);
  11458. case value_t::number_unsigned:
  11459. return write_bson_unsigned(name, j.m_value.number_unsigned);
  11460. case value_t::string:
  11461. return write_bson_string(name, *j.m_value.string);
  11462. case value_t::null:
  11463. return write_bson_null(name);
  11464. // LCOV_EXCL_START
  11465. default:
  11466. assert(false);
  11467. return;
  11468. // LCOV_EXCL_STOP
  11469. }
  11470. }
  11471. /*!
  11472. @brief Calculates the size of the BSON serialization of the given
  11473. JSON-object @a j.
  11474. @param[in] j JSON value to serialize
  11475. @pre j.type() == value_t::object
  11476. */
  11477. static std::size_t calc_bson_object_size(const typename BasicJsonType::object_t& value)
  11478. {
  11479. std::size_t document_size = std::accumulate(value.begin(), value.end(), std::size_t(0),
  11480. [](size_t result, const typename BasicJsonType::object_t::value_type & el)
  11481. {
  11482. return result += calc_bson_element_size(el.first, el.second);
  11483. });
  11484. return sizeof(std::int32_t) + document_size + 1ul;
  11485. }
  11486. /*!
  11487. @param[in] j JSON value to serialize
  11488. @pre j.type() == value_t::object
  11489. */
  11490. void write_bson_object(const typename BasicJsonType::object_t& value)
  11491. {
  11492. write_number<std::int32_t, true>(static_cast<std::int32_t>(calc_bson_object_size(value)));
  11493. for (const auto& el : value)
  11494. {
  11495. write_bson_element(el.first, el.second);
  11496. }
  11497. oa->write_character(to_char_type(0x00));
  11498. }
  11499. //////////
  11500. // CBOR //
  11501. //////////
  11502. static constexpr CharType get_cbor_float_prefix(float /*unused*/)
  11503. {
  11504. return to_char_type(0xFA); // Single-Precision Float
  11505. }
  11506. static constexpr CharType get_cbor_float_prefix(double /*unused*/)
  11507. {
  11508. return to_char_type(0xFB); // Double-Precision Float
  11509. }
  11510. /////////////
  11511. // MsgPack //
  11512. /////////////
  11513. static constexpr CharType get_msgpack_float_prefix(float /*unused*/)
  11514. {
  11515. return to_char_type(0xCA); // float 32
  11516. }
  11517. static constexpr CharType get_msgpack_float_prefix(double /*unused*/)
  11518. {
  11519. return to_char_type(0xCB); // float 64
  11520. }
  11521. ////////////
  11522. // UBJSON //
  11523. ////////////
  11524. // UBJSON: write number (floating point)
  11525. template<typename NumberType, typename std::enable_if<
  11526. std::is_floating_point<NumberType>::value, int>::type = 0>
  11527. void write_number_with_ubjson_prefix(const NumberType n,
  11528. const bool add_prefix)
  11529. {
  11530. if (add_prefix)
  11531. {
  11532. oa->write_character(get_ubjson_float_prefix(n));
  11533. }
  11534. write_number(n);
  11535. }
  11536. // UBJSON: write number (unsigned integer)
  11537. template<typename NumberType, typename std::enable_if<
  11538. std::is_unsigned<NumberType>::value, int>::type = 0>
  11539. void write_number_with_ubjson_prefix(const NumberType n,
  11540. const bool add_prefix)
  11541. {
  11542. if (n <= static_cast<std::uint64_t>((std::numeric_limits<std::int8_t>::max)()))
  11543. {
  11544. if (add_prefix)
  11545. {
  11546. oa->write_character(to_char_type('i')); // int8
  11547. }
  11548. write_number(static_cast<std::uint8_t>(n));
  11549. }
  11550. else if (n <= (std::numeric_limits<std::uint8_t>::max)())
  11551. {
  11552. if (add_prefix)
  11553. {
  11554. oa->write_character(to_char_type('U')); // uint8
  11555. }
  11556. write_number(static_cast<std::uint8_t>(n));
  11557. }
  11558. else if (n <= static_cast<std::uint64_t>((std::numeric_limits<std::int16_t>::max)()))
  11559. {
  11560. if (add_prefix)
  11561. {
  11562. oa->write_character(to_char_type('I')); // int16
  11563. }
  11564. write_number(static_cast<std::int16_t>(n));
  11565. }
  11566. else if (n <= static_cast<std::uint64_t>((std::numeric_limits<std::int32_t>::max)()))
  11567. {
  11568. if (add_prefix)
  11569. {
  11570. oa->write_character(to_char_type('l')); // int32
  11571. }
  11572. write_number(static_cast<std::int32_t>(n));
  11573. }
  11574. else if (n <= static_cast<std::uint64_t>((std::numeric_limits<std::int64_t>::max)()))
  11575. {
  11576. if (add_prefix)
  11577. {
  11578. oa->write_character(to_char_type('L')); // int64
  11579. }
  11580. write_number(static_cast<std::int64_t>(n));
  11581. }
  11582. else
  11583. {
  11584. JSON_THROW(out_of_range::create(407, "integer number " + std::to_string(n) + " cannot be represented by UBJSON as it does not fit int64"));
  11585. }
  11586. }
  11587. // UBJSON: write number (signed integer)
  11588. template<typename NumberType, typename std::enable_if<
  11589. std::is_signed<NumberType>::value and
  11590. not std::is_floating_point<NumberType>::value, int>::type = 0>
  11591. void write_number_with_ubjson_prefix(const NumberType n,
  11592. const bool add_prefix)
  11593. {
  11594. if ((std::numeric_limits<std::int8_t>::min)() <= n and n <= (std::numeric_limits<std::int8_t>::max)())
  11595. {
  11596. if (add_prefix)
  11597. {
  11598. oa->write_character(to_char_type('i')); // int8
  11599. }
  11600. write_number(static_cast<std::int8_t>(n));
  11601. }
  11602. 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)()))
  11603. {
  11604. if (add_prefix)
  11605. {
  11606. oa->write_character(to_char_type('U')); // uint8
  11607. }
  11608. write_number(static_cast<std::uint8_t>(n));
  11609. }
  11610. else if ((std::numeric_limits<std::int16_t>::min)() <= n and n <= (std::numeric_limits<std::int16_t>::max)())
  11611. {
  11612. if (add_prefix)
  11613. {
  11614. oa->write_character(to_char_type('I')); // int16
  11615. }
  11616. write_number(static_cast<std::int16_t>(n));
  11617. }
  11618. else if ((std::numeric_limits<std::int32_t>::min)() <= n and n <= (std::numeric_limits<std::int32_t>::max)())
  11619. {
  11620. if (add_prefix)
  11621. {
  11622. oa->write_character(to_char_type('l')); // int32
  11623. }
  11624. write_number(static_cast<std::int32_t>(n));
  11625. }
  11626. else if ((std::numeric_limits<std::int64_t>::min)() <= n and n <= (std::numeric_limits<std::int64_t>::max)())
  11627. {
  11628. if (add_prefix)
  11629. {
  11630. oa->write_character(to_char_type('L')); // int64
  11631. }
  11632. write_number(static_cast<std::int64_t>(n));
  11633. }
  11634. // LCOV_EXCL_START
  11635. else
  11636. {
  11637. JSON_THROW(out_of_range::create(407, "integer number " + std::to_string(n) + " cannot be represented by UBJSON as it does not fit int64"));
  11638. }
  11639. // LCOV_EXCL_STOP
  11640. }
  11641. /*!
  11642. @brief determine the type prefix of container values
  11643. @note This function does not need to be 100% accurate when it comes to
  11644. integer limits. In case a number exceeds the limits of int64_t,
  11645. this will be detected by a later call to function
  11646. write_number_with_ubjson_prefix. Therefore, we return 'L' for any
  11647. value that does not fit the previous limits.
  11648. */
  11649. CharType ubjson_prefix(const BasicJsonType& j) const noexcept
  11650. {
  11651. switch (j.type())
  11652. {
  11653. case value_t::null:
  11654. return 'Z';
  11655. case value_t::boolean:
  11656. return j.m_value.boolean ? 'T' : 'F';
  11657. case value_t::number_integer:
  11658. {
  11659. 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)())
  11660. {
  11661. return 'i';
  11662. }
  11663. 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)())
  11664. {
  11665. return 'U';
  11666. }
  11667. 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)())
  11668. {
  11669. return 'I';
  11670. }
  11671. 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)())
  11672. {
  11673. return 'l';
  11674. }
  11675. // no check and assume int64_t (see note above)
  11676. return 'L';
  11677. }
  11678. case value_t::number_unsigned:
  11679. {
  11680. if (j.m_value.number_unsigned <= static_cast<std::uint64_t>((std::numeric_limits<std::int8_t>::max)()))
  11681. {
  11682. return 'i';
  11683. }
  11684. if (j.m_value.number_unsigned <= static_cast<std::uint64_t>((std::numeric_limits<std::uint8_t>::max)()))
  11685. {
  11686. return 'U';
  11687. }
  11688. if (j.m_value.number_unsigned <= static_cast<std::uint64_t>((std::numeric_limits<std::int16_t>::max)()))
  11689. {
  11690. return 'I';
  11691. }
  11692. if (j.m_value.number_unsigned <= static_cast<std::uint64_t>((std::numeric_limits<std::int32_t>::max)()))
  11693. {
  11694. return 'l';
  11695. }
  11696. // no check and assume int64_t (see note above)
  11697. return 'L';
  11698. }
  11699. case value_t::number_float:
  11700. return get_ubjson_float_prefix(j.m_value.number_float);
  11701. case value_t::string:
  11702. return 'S';
  11703. case value_t::array: // fallthrough
  11704. case value_t::binary:
  11705. return '[';
  11706. case value_t::object:
  11707. return '{';
  11708. default: // discarded values
  11709. return 'N';
  11710. }
  11711. }
  11712. static constexpr CharType get_ubjson_float_prefix(float /*unused*/)
  11713. {
  11714. return 'd'; // float 32
  11715. }
  11716. static constexpr CharType get_ubjson_float_prefix(double /*unused*/)
  11717. {
  11718. return 'D'; // float 64
  11719. }
  11720. ///////////////////////
  11721. // Utility functions //
  11722. ///////////////////////
  11723. /*
  11724. @brief write a number to output input
  11725. @param[in] n number of type @a NumberType
  11726. @tparam NumberType the type of the number
  11727. @tparam OutputIsLittleEndian Set to true if output data is
  11728. required to be little endian
  11729. @note This function needs to respect the system's endianess, because bytes
  11730. in CBOR, MessagePack, and UBJSON are stored in network order (big
  11731. endian) and therefore need reordering on little endian systems.
  11732. */
  11733. template<typename NumberType, bool OutputIsLittleEndian = false>
  11734. void write_number(const NumberType n)
  11735. {
  11736. // step 1: write number to array of length NumberType
  11737. std::array<CharType, sizeof(NumberType)> vec;
  11738. std::memcpy(vec.data(), &n, sizeof(NumberType));
  11739. // step 2: write array to output (with possible reordering)
  11740. if (is_little_endian != OutputIsLittleEndian)
  11741. {
  11742. // reverse byte order prior to conversion if necessary
  11743. std::reverse(vec.begin(), vec.end());
  11744. }
  11745. oa->write_characters(vec.data(), sizeof(NumberType));
  11746. }
  11747. public:
  11748. // The following to_char_type functions are implement the conversion
  11749. // between uint8_t and CharType. In case CharType is not unsigned,
  11750. // such a conversion is required to allow values greater than 128.
  11751. // See <https://github.com/nlohmann/json/issues/1286> for a discussion.
  11752. template < typename C = CharType,
  11753. enable_if_t < std::is_signed<C>::value and std::is_signed<char>::value > * = nullptr >
  11754. static constexpr CharType to_char_type(std::uint8_t x) noexcept
  11755. {
  11756. return *reinterpret_cast<char*>(&x);
  11757. }
  11758. template < typename C = CharType,
  11759. enable_if_t < std::is_signed<C>::value and std::is_unsigned<char>::value > * = nullptr >
  11760. static CharType to_char_type(std::uint8_t x) noexcept
  11761. {
  11762. static_assert(sizeof(std::uint8_t) == sizeof(CharType), "size of CharType must be equal to std::uint8_t");
  11763. static_assert(std::is_trivial<CharType>::value, "CharType must be trivial");
  11764. CharType result;
  11765. std::memcpy(&result, &x, sizeof(x));
  11766. return result;
  11767. }
  11768. template<typename C = CharType,
  11769. enable_if_t<std::is_unsigned<C>::value>* = nullptr>
  11770. static constexpr CharType to_char_type(std::uint8_t x) noexcept
  11771. {
  11772. return x;
  11773. }
  11774. template < typename InputCharType, typename C = CharType,
  11775. enable_if_t <
  11776. std::is_signed<C>::value and
  11777. std::is_signed<char>::value and
  11778. std::is_same<char, typename std::remove_cv<InputCharType>::type>::value
  11779. > * = nullptr >
  11780. static constexpr CharType to_char_type(InputCharType x) noexcept
  11781. {
  11782. return x;
  11783. }
  11784. private:
  11785. /// whether we can assume little endianess
  11786. const bool is_little_endian = little_endianess();
  11787. /// the output
  11788. output_adapter_t<CharType> oa = nullptr;
  11789. };
  11790. } // namespace detail
  11791. } // namespace nlohmann
  11792. // #include <nlohmann/detail/output/output_adapters.hpp>
  11793. // #include <nlohmann/detail/output/serializer.hpp>
  11794. #include <algorithm> // reverse, remove, fill, find, none_of
  11795. #include <array> // array
  11796. #include <cassert> // assert
  11797. #include <ciso646> // and, or
  11798. #include <clocale> // localeconv, lconv
  11799. #include <cmath> // labs, isfinite, isnan, signbit
  11800. #include <cstddef> // size_t, ptrdiff_t
  11801. #include <cstdint> // uint8_t
  11802. #include <cstdio> // snprintf
  11803. #include <limits> // numeric_limits
  11804. #include <string> // string
  11805. #include <type_traits> // is_same
  11806. #include <utility> // move
  11807. // #include <nlohmann/detail/conversions/to_chars.hpp>
  11808. #include <array> // array
  11809. #include <cassert> // assert
  11810. #include <ciso646> // or, and, not
  11811. #include <cmath> // signbit, isfinite
  11812. #include <cstdint> // intN_t, uintN_t
  11813. #include <cstring> // memcpy, memmove
  11814. #include <limits> // numeric_limits
  11815. #include <type_traits> // conditional
  11816. // #include <nlohmann/detail/macro_scope.hpp>
  11817. namespace nlohmann
  11818. {
  11819. namespace detail
  11820. {
  11821. /*!
  11822. @brief implements the Grisu2 algorithm for binary to decimal floating-point
  11823. conversion.
  11824. This implementation is a slightly modified version of the reference
  11825. implementation which may be obtained from
  11826. http://florian.loitsch.com/publications (bench.tar.gz).
  11827. The code is distributed under the MIT license, Copyright (c) 2009 Florian Loitsch.
  11828. For a detailed description of the algorithm see:
  11829. [1] Loitsch, "Printing Floating-Point Numbers Quickly and Accurately with
  11830. Integers", Proceedings of the ACM SIGPLAN 2010 Conference on Programming
  11831. Language Design and Implementation, PLDI 2010
  11832. [2] Burger, Dybvig, "Printing Floating-Point Numbers Quickly and Accurately",
  11833. Proceedings of the ACM SIGPLAN 1996 Conference on Programming Language
  11834. Design and Implementation, PLDI 1996
  11835. */
  11836. namespace dtoa_impl
  11837. {
  11838. template <typename Target, typename Source>
  11839. Target reinterpret_bits(const Source source)
  11840. {
  11841. static_assert(sizeof(Target) == sizeof(Source), "size mismatch");
  11842. Target target;
  11843. std::memcpy(&target, &source, sizeof(Source));
  11844. return target;
  11845. }
  11846. struct diyfp // f * 2^e
  11847. {
  11848. static constexpr int kPrecision = 64; // = q
  11849. std::uint64_t f = 0;
  11850. int e = 0;
  11851. constexpr diyfp(std::uint64_t f_, int e_) noexcept : f(f_), e(e_) {}
  11852. /*!
  11853. @brief returns x - y
  11854. @pre x.e == y.e and x.f >= y.f
  11855. */
  11856. static diyfp sub(const diyfp& x, const diyfp& y) noexcept
  11857. {
  11858. assert(x.e == y.e);
  11859. assert(x.f >= y.f);
  11860. return {x.f - y.f, x.e};
  11861. }
  11862. /*!
  11863. @brief returns x * y
  11864. @note The result is rounded. (Only the upper q bits are returned.)
  11865. */
  11866. static diyfp mul(const diyfp& x, const diyfp& y) noexcept
  11867. {
  11868. static_assert(kPrecision == 64, "internal error");
  11869. // Computes:
  11870. // f = round((x.f * y.f) / 2^q)
  11871. // e = x.e + y.e + q
  11872. // Emulate the 64-bit * 64-bit multiplication:
  11873. //
  11874. // p = u * v
  11875. // = (u_lo + 2^32 u_hi) (v_lo + 2^32 v_hi)
  11876. // = (u_lo v_lo ) + 2^32 ((u_lo v_hi ) + (u_hi v_lo )) + 2^64 (u_hi v_hi )
  11877. // = (p0 ) + 2^32 ((p1 ) + (p2 )) + 2^64 (p3 )
  11878. // = (p0_lo + 2^32 p0_hi) + 2^32 ((p1_lo + 2^32 p1_hi) + (p2_lo + 2^32 p2_hi)) + 2^64 (p3 )
  11879. // = (p0_lo ) + 2^32 (p0_hi + p1_lo + p2_lo ) + 2^64 (p1_hi + p2_hi + p3)
  11880. // = (p0_lo ) + 2^32 (Q ) + 2^64 (H )
  11881. // = (p0_lo ) + 2^32 (Q_lo + 2^32 Q_hi ) + 2^64 (H )
  11882. //
  11883. // (Since Q might be larger than 2^32 - 1)
  11884. //
  11885. // = (p0_lo + 2^32 Q_lo) + 2^64 (Q_hi + H)
  11886. //
  11887. // (Q_hi + H does not overflow a 64-bit int)
  11888. //
  11889. // = p_lo + 2^64 p_hi
  11890. const std::uint64_t u_lo = x.f & 0xFFFFFFFFu;
  11891. const std::uint64_t u_hi = x.f >> 32u;
  11892. const std::uint64_t v_lo = y.f & 0xFFFFFFFFu;
  11893. const std::uint64_t v_hi = y.f >> 32u;
  11894. const std::uint64_t p0 = u_lo * v_lo;
  11895. const std::uint64_t p1 = u_lo * v_hi;
  11896. const std::uint64_t p2 = u_hi * v_lo;
  11897. const std::uint64_t p3 = u_hi * v_hi;
  11898. const std::uint64_t p0_hi = p0 >> 32u;
  11899. const std::uint64_t p1_lo = p1 & 0xFFFFFFFFu;
  11900. const std::uint64_t p1_hi = p1 >> 32u;
  11901. const std::uint64_t p2_lo = p2 & 0xFFFFFFFFu;
  11902. const std::uint64_t p2_hi = p2 >> 32u;
  11903. std::uint64_t Q = p0_hi + p1_lo + p2_lo;
  11904. // The full product might now be computed as
  11905. //
  11906. // p_hi = p3 + p2_hi + p1_hi + (Q >> 32)
  11907. // p_lo = p0_lo + (Q << 32)
  11908. //
  11909. // But in this particular case here, the full p_lo is not required.
  11910. // Effectively we only need to add the highest bit in p_lo to p_hi (and
  11911. // Q_hi + 1 does not overflow).
  11912. Q += std::uint64_t{1} << (64u - 32u - 1u); // round, ties up
  11913. const std::uint64_t h = p3 + p2_hi + p1_hi + (Q >> 32u);
  11914. return {h, x.e + y.e + 64};
  11915. }
  11916. /*!
  11917. @brief normalize x such that the significand is >= 2^(q-1)
  11918. @pre x.f != 0
  11919. */
  11920. static diyfp normalize(diyfp x) noexcept
  11921. {
  11922. assert(x.f != 0);
  11923. while ((x.f >> 63u) == 0)
  11924. {
  11925. x.f <<= 1u;
  11926. x.e--;
  11927. }
  11928. return x;
  11929. }
  11930. /*!
  11931. @brief normalize x such that the result has the exponent E
  11932. @pre e >= x.e and the upper e - x.e bits of x.f must be zero.
  11933. */
  11934. static diyfp normalize_to(const diyfp& x, const int target_exponent) noexcept
  11935. {
  11936. const int delta = x.e - target_exponent;
  11937. assert(delta >= 0);
  11938. assert(((x.f << delta) >> delta) == x.f);
  11939. return {x.f << delta, target_exponent};
  11940. }
  11941. };
  11942. struct boundaries
  11943. {
  11944. diyfp w;
  11945. diyfp minus;
  11946. diyfp plus;
  11947. };
  11948. /*!
  11949. Compute the (normalized) diyfp representing the input number 'value' and its
  11950. boundaries.
  11951. @pre value must be finite and positive
  11952. */
  11953. template <typename FloatType>
  11954. boundaries compute_boundaries(FloatType value)
  11955. {
  11956. assert(std::isfinite(value));
  11957. assert(value > 0);
  11958. // Convert the IEEE representation into a diyfp.
  11959. //
  11960. // If v is denormal:
  11961. // value = 0.F * 2^(1 - bias) = ( F) * 2^(1 - bias - (p-1))
  11962. // If v is normalized:
  11963. // value = 1.F * 2^(E - bias) = (2^(p-1) + F) * 2^(E - bias - (p-1))
  11964. static_assert(std::numeric_limits<FloatType>::is_iec559,
  11965. "internal error: dtoa_short requires an IEEE-754 floating-point implementation");
  11966. constexpr int kPrecision = std::numeric_limits<FloatType>::digits; // = p (includes the hidden bit)
  11967. constexpr int kBias = std::numeric_limits<FloatType>::max_exponent - 1 + (kPrecision - 1);
  11968. constexpr int kMinExp = 1 - kBias;
  11969. constexpr std::uint64_t kHiddenBit = std::uint64_t{1} << (kPrecision - 1); // = 2^(p-1)
  11970. using bits_type = typename std::conditional<kPrecision == 24, std::uint32_t, std::uint64_t >::type;
  11971. const std::uint64_t bits = reinterpret_bits<bits_type>(value);
  11972. const std::uint64_t E = bits >> (kPrecision - 1);
  11973. const std::uint64_t F = bits & (kHiddenBit - 1);
  11974. const bool is_denormal = E == 0;
  11975. const diyfp v = is_denormal
  11976. ? diyfp(F, kMinExp)
  11977. : diyfp(F + kHiddenBit, static_cast<int>(E) - kBias);
  11978. // Compute the boundaries m- and m+ of the floating-point value
  11979. // v = f * 2^e.
  11980. //
  11981. // Determine v- and v+, the floating-point predecessor and successor if v,
  11982. // respectively.
  11983. //
  11984. // v- = v - 2^e if f != 2^(p-1) or e == e_min (A)
  11985. // = v - 2^(e-1) if f == 2^(p-1) and e > e_min (B)
  11986. //
  11987. // v+ = v + 2^e
  11988. //
  11989. // Let m- = (v- + v) / 2 and m+ = (v + v+) / 2. All real numbers _strictly_
  11990. // between m- and m+ round to v, regardless of how the input rounding
  11991. // algorithm breaks ties.
  11992. //
  11993. // ---+-------------+-------------+-------------+-------------+--- (A)
  11994. // v- m- v m+ v+
  11995. //
  11996. // -----------------+------+------+-------------+-------------+--- (B)
  11997. // v- m- v m+ v+
  11998. const bool lower_boundary_is_closer = F == 0 and E > 1;
  11999. const diyfp m_plus = diyfp(2 * v.f + 1, v.e - 1);
  12000. const diyfp m_minus = lower_boundary_is_closer
  12001. ? diyfp(4 * v.f - 1, v.e - 2) // (B)
  12002. : diyfp(2 * v.f - 1, v.e - 1); // (A)
  12003. // Determine the normalized w+ = m+.
  12004. const diyfp w_plus = diyfp::normalize(m_plus);
  12005. // Determine w- = m- such that e_(w-) = e_(w+).
  12006. const diyfp w_minus = diyfp::normalize_to(m_minus, w_plus.e);
  12007. return {diyfp::normalize(v), w_minus, w_plus};
  12008. }
  12009. // Given normalized diyfp w, Grisu needs to find a (normalized) cached
  12010. // power-of-ten c, such that the exponent of the product c * w = f * 2^e lies
  12011. // within a certain range [alpha, gamma] (Definition 3.2 from [1])
  12012. //
  12013. // alpha <= e = e_c + e_w + q <= gamma
  12014. //
  12015. // or
  12016. //
  12017. // f_c * f_w * 2^alpha <= f_c 2^(e_c) * f_w 2^(e_w) * 2^q
  12018. // <= f_c * f_w * 2^gamma
  12019. //
  12020. // Since c and w are normalized, i.e. 2^(q-1) <= f < 2^q, this implies
  12021. //
  12022. // 2^(q-1) * 2^(q-1) * 2^alpha <= c * w * 2^q < 2^q * 2^q * 2^gamma
  12023. //
  12024. // or
  12025. //
  12026. // 2^(q - 2 + alpha) <= c * w < 2^(q + gamma)
  12027. //
  12028. // The choice of (alpha,gamma) determines the size of the table and the form of
  12029. // the digit generation procedure. Using (alpha,gamma)=(-60,-32) works out well
  12030. // in practice:
  12031. //
  12032. // The idea is to cut the number c * w = f * 2^e into two parts, which can be
  12033. // processed independently: An integral part p1, and a fractional part p2:
  12034. //
  12035. // f * 2^e = ( (f div 2^-e) * 2^-e + (f mod 2^-e) ) * 2^e
  12036. // = (f div 2^-e) + (f mod 2^-e) * 2^e
  12037. // = p1 + p2 * 2^e
  12038. //
  12039. // The conversion of p1 into decimal form requires a series of divisions and
  12040. // modulos by (a power of) 10. These operations are faster for 32-bit than for
  12041. // 64-bit integers, so p1 should ideally fit into a 32-bit integer. This can be
  12042. // achieved by choosing
  12043. //
  12044. // -e >= 32 or e <= -32 := gamma
  12045. //
  12046. // In order to convert the fractional part
  12047. //
  12048. // p2 * 2^e = p2 / 2^-e = d[-1] / 10^1 + d[-2] / 10^2 + ...
  12049. //
  12050. // into decimal form, the fraction is repeatedly multiplied by 10 and the digits
  12051. // d[-i] are extracted in order:
  12052. //
  12053. // (10 * p2) div 2^-e = d[-1]
  12054. // (10 * p2) mod 2^-e = d[-2] / 10^1 + ...
  12055. //
  12056. // The multiplication by 10 must not overflow. It is sufficient to choose
  12057. //
  12058. // 10 * p2 < 16 * p2 = 2^4 * p2 <= 2^64.
  12059. //
  12060. // Since p2 = f mod 2^-e < 2^-e,
  12061. //
  12062. // -e <= 60 or e >= -60 := alpha
  12063. constexpr int kAlpha = -60;
  12064. constexpr int kGamma = -32;
  12065. struct cached_power // c = f * 2^e ~= 10^k
  12066. {
  12067. std::uint64_t f;
  12068. int e;
  12069. int k;
  12070. };
  12071. /*!
  12072. For a normalized diyfp w = f * 2^e, this function returns a (normalized) cached
  12073. power-of-ten c = f_c * 2^e_c, such that the exponent of the product w * c
  12074. satisfies (Definition 3.2 from [1])
  12075. alpha <= e_c + e + q <= gamma.
  12076. */
  12077. inline cached_power get_cached_power_for_binary_exponent(int e)
  12078. {
  12079. // Now
  12080. //
  12081. // alpha <= e_c + e + q <= gamma (1)
  12082. // ==> f_c * 2^alpha <= c * 2^e * 2^q
  12083. //
  12084. // and since the c's are normalized, 2^(q-1) <= f_c,
  12085. //
  12086. // ==> 2^(q - 1 + alpha) <= c * 2^(e + q)
  12087. // ==> 2^(alpha - e - 1) <= c
  12088. //
  12089. // If c were an exact power of ten, i.e. c = 10^k, one may determine k as
  12090. //
  12091. // k = ceil( log_10( 2^(alpha - e - 1) ) )
  12092. // = ceil( (alpha - e - 1) * log_10(2) )
  12093. //
  12094. // From the paper:
  12095. // "In theory the result of the procedure could be wrong since c is rounded,
  12096. // and the computation itself is approximated [...]. In practice, however,
  12097. // this simple function is sufficient."
  12098. //
  12099. // For IEEE double precision floating-point numbers converted into
  12100. // normalized diyfp's w = f * 2^e, with q = 64,
  12101. //
  12102. // e >= -1022 (min IEEE exponent)
  12103. // -52 (p - 1)
  12104. // -52 (p - 1, possibly normalize denormal IEEE numbers)
  12105. // -11 (normalize the diyfp)
  12106. // = -1137
  12107. //
  12108. // and
  12109. //
  12110. // e <= +1023 (max IEEE exponent)
  12111. // -52 (p - 1)
  12112. // -11 (normalize the diyfp)
  12113. // = 960
  12114. //
  12115. // This binary exponent range [-1137,960] results in a decimal exponent
  12116. // range [-307,324]. One does not need to store a cached power for each
  12117. // k in this range. For each such k it suffices to find a cached power
  12118. // such that the exponent of the product lies in [alpha,gamma].
  12119. // This implies that the difference of the decimal exponents of adjacent
  12120. // table entries must be less than or equal to
  12121. //
  12122. // floor( (gamma - alpha) * log_10(2) ) = 8.
  12123. //
  12124. // (A smaller distance gamma-alpha would require a larger table.)
  12125. // NB:
  12126. // Actually this function returns c, such that -60 <= e_c + e + 64 <= -34.
  12127. constexpr int kCachedPowersMinDecExp = -300;
  12128. constexpr int kCachedPowersDecStep = 8;
  12129. static constexpr std::array<cached_power, 79> kCachedPowers =
  12130. {
  12131. {
  12132. { 0xAB70FE17C79AC6CA, -1060, -300 },
  12133. { 0xFF77B1FCBEBCDC4F, -1034, -292 },
  12134. { 0xBE5691EF416BD60C, -1007, -284 },
  12135. { 0x8DD01FAD907FFC3C, -980, -276 },
  12136. { 0xD3515C2831559A83, -954, -268 },
  12137. { 0x9D71AC8FADA6C9B5, -927, -260 },
  12138. { 0xEA9C227723EE8BCB, -901, -252 },
  12139. { 0xAECC49914078536D, -874, -244 },
  12140. { 0x823C12795DB6CE57, -847, -236 },
  12141. { 0xC21094364DFB5637, -821, -228 },
  12142. { 0x9096EA6F3848984F, -794, -220 },
  12143. { 0xD77485CB25823AC7, -768, -212 },
  12144. { 0xA086CFCD97BF97F4, -741, -204 },
  12145. { 0xEF340A98172AACE5, -715, -196 },
  12146. { 0xB23867FB2A35B28E, -688, -188 },
  12147. { 0x84C8D4DFD2C63F3B, -661, -180 },
  12148. { 0xC5DD44271AD3CDBA, -635, -172 },
  12149. { 0x936B9FCEBB25C996, -608, -164 },
  12150. { 0xDBAC6C247D62A584, -582, -156 },
  12151. { 0xA3AB66580D5FDAF6, -555, -148 },
  12152. { 0xF3E2F893DEC3F126, -529, -140 },
  12153. { 0xB5B5ADA8AAFF80B8, -502, -132 },
  12154. { 0x87625F056C7C4A8B, -475, -124 },
  12155. { 0xC9BCFF6034C13053, -449, -116 },
  12156. { 0x964E858C91BA2655, -422, -108 },
  12157. { 0xDFF9772470297EBD, -396, -100 },
  12158. { 0xA6DFBD9FB8E5B88F, -369, -92 },
  12159. { 0xF8A95FCF88747D94, -343, -84 },
  12160. { 0xB94470938FA89BCF, -316, -76 },
  12161. { 0x8A08F0F8BF0F156B, -289, -68 },
  12162. { 0xCDB02555653131B6, -263, -60 },
  12163. { 0x993FE2C6D07B7FAC, -236, -52 },
  12164. { 0xE45C10C42A2B3B06, -210, -44 },
  12165. { 0xAA242499697392D3, -183, -36 },
  12166. { 0xFD87B5F28300CA0E, -157, -28 },
  12167. { 0xBCE5086492111AEB, -130, -20 },
  12168. { 0x8CBCCC096F5088CC, -103, -12 },
  12169. { 0xD1B71758E219652C, -77, -4 },
  12170. { 0x9C40000000000000, -50, 4 },
  12171. { 0xE8D4A51000000000, -24, 12 },
  12172. { 0xAD78EBC5AC620000, 3, 20 },
  12173. { 0x813F3978F8940984, 30, 28 },
  12174. { 0xC097CE7BC90715B3, 56, 36 },
  12175. { 0x8F7E32CE7BEA5C70, 83, 44 },
  12176. { 0xD5D238A4ABE98068, 109, 52 },
  12177. { 0x9F4F2726179A2245, 136, 60 },
  12178. { 0xED63A231D4C4FB27, 162, 68 },
  12179. { 0xB0DE65388CC8ADA8, 189, 76 },
  12180. { 0x83C7088E1AAB65DB, 216, 84 },
  12181. { 0xC45D1DF942711D9A, 242, 92 },
  12182. { 0x924D692CA61BE758, 269, 100 },
  12183. { 0xDA01EE641A708DEA, 295, 108 },
  12184. { 0xA26DA3999AEF774A, 322, 116 },
  12185. { 0xF209787BB47D6B85, 348, 124 },
  12186. { 0xB454E4A179DD1877, 375, 132 },
  12187. { 0x865B86925B9BC5C2, 402, 140 },
  12188. { 0xC83553C5C8965D3D, 428, 148 },
  12189. { 0x952AB45CFA97A0B3, 455, 156 },
  12190. { 0xDE469FBD99A05FE3, 481, 164 },
  12191. { 0xA59BC234DB398C25, 508, 172 },
  12192. { 0xF6C69A72A3989F5C, 534, 180 },
  12193. { 0xB7DCBF5354E9BECE, 561, 188 },
  12194. { 0x88FCF317F22241E2, 588, 196 },
  12195. { 0xCC20CE9BD35C78A5, 614, 204 },
  12196. { 0x98165AF37B2153DF, 641, 212 },
  12197. { 0xE2A0B5DC971F303A, 667, 220 },
  12198. { 0xA8D9D1535CE3B396, 694, 228 },
  12199. { 0xFB9B7CD9A4A7443C, 720, 236 },
  12200. { 0xBB764C4CA7A44410, 747, 244 },
  12201. { 0x8BAB8EEFB6409C1A, 774, 252 },
  12202. { 0xD01FEF10A657842C, 800, 260 },
  12203. { 0x9B10A4E5E9913129, 827, 268 },
  12204. { 0xE7109BFBA19C0C9D, 853, 276 },
  12205. { 0xAC2820D9623BF429, 880, 284 },
  12206. { 0x80444B5E7AA7CF85, 907, 292 },
  12207. { 0xBF21E44003ACDD2D, 933, 300 },
  12208. { 0x8E679C2F5E44FF8F, 960, 308 },
  12209. { 0xD433179D9C8CB841, 986, 316 },
  12210. { 0x9E19DB92B4E31BA9, 1013, 324 },
  12211. }
  12212. };
  12213. // This computation gives exactly the same results for k as
  12214. // k = ceil((kAlpha - e - 1) * 0.30102999566398114)
  12215. // for |e| <= 1500, but doesn't require floating-point operations.
  12216. // NB: log_10(2) ~= 78913 / 2^18
  12217. assert(e >= -1500);
  12218. assert(e <= 1500);
  12219. const int f = kAlpha - e - 1;
  12220. const int k = (f * 78913) / (1 << 18) + static_cast<int>(f > 0);
  12221. const int index = (-kCachedPowersMinDecExp + k + (kCachedPowersDecStep - 1)) / kCachedPowersDecStep;
  12222. assert(index >= 0);
  12223. assert(static_cast<std::size_t>(index) < kCachedPowers.size());
  12224. const cached_power cached = kCachedPowers[static_cast<std::size_t>(index)];
  12225. assert(kAlpha <= cached.e + e + 64);
  12226. assert(kGamma >= cached.e + e + 64);
  12227. return cached;
  12228. }
  12229. /*!
  12230. For n != 0, returns k, such that pow10 := 10^(k-1) <= n < 10^k.
  12231. For n == 0, returns 1 and sets pow10 := 1.
  12232. */
  12233. inline int find_largest_pow10(const std::uint32_t n, std::uint32_t& pow10)
  12234. {
  12235. // LCOV_EXCL_START
  12236. if (n >= 1000000000)
  12237. {
  12238. pow10 = 1000000000;
  12239. return 10;
  12240. }
  12241. // LCOV_EXCL_STOP
  12242. else if (n >= 100000000)
  12243. {
  12244. pow10 = 100000000;
  12245. return 9;
  12246. }
  12247. else if (n >= 10000000)
  12248. {
  12249. pow10 = 10000000;
  12250. return 8;
  12251. }
  12252. else if (n >= 1000000)
  12253. {
  12254. pow10 = 1000000;
  12255. return 7;
  12256. }
  12257. else if (n >= 100000)
  12258. {
  12259. pow10 = 100000;
  12260. return 6;
  12261. }
  12262. else if (n >= 10000)
  12263. {
  12264. pow10 = 10000;
  12265. return 5;
  12266. }
  12267. else if (n >= 1000)
  12268. {
  12269. pow10 = 1000;
  12270. return 4;
  12271. }
  12272. else if (n >= 100)
  12273. {
  12274. pow10 = 100;
  12275. return 3;
  12276. }
  12277. else if (n >= 10)
  12278. {
  12279. pow10 = 10;
  12280. return 2;
  12281. }
  12282. else
  12283. {
  12284. pow10 = 1;
  12285. return 1;
  12286. }
  12287. }
  12288. inline void grisu2_round(char* buf, int len, std::uint64_t dist, std::uint64_t delta,
  12289. std::uint64_t rest, std::uint64_t ten_k)
  12290. {
  12291. assert(len >= 1);
  12292. assert(dist <= delta);
  12293. assert(rest <= delta);
  12294. assert(ten_k > 0);
  12295. // <--------------------------- delta ---->
  12296. // <---- dist --------->
  12297. // --------------[------------------+-------------------]--------------
  12298. // M- w M+
  12299. //
  12300. // ten_k
  12301. // <------>
  12302. // <---- rest ---->
  12303. // --------------[------------------+----+--------------]--------------
  12304. // w V
  12305. // = buf * 10^k
  12306. //
  12307. // ten_k represents a unit-in-the-last-place in the decimal representation
  12308. // stored in buf.
  12309. // Decrement buf by ten_k while this takes buf closer to w.
  12310. // The tests are written in this order to avoid overflow in unsigned
  12311. // integer arithmetic.
  12312. while (rest < dist
  12313. and delta - rest >= ten_k
  12314. and (rest + ten_k < dist or dist - rest > rest + ten_k - dist))
  12315. {
  12316. assert(buf[len - 1] != '0');
  12317. buf[len - 1]--;
  12318. rest += ten_k;
  12319. }
  12320. }
  12321. /*!
  12322. Generates V = buffer * 10^decimal_exponent, such that M- <= V <= M+.
  12323. M- and M+ must be normalized and share the same exponent -60 <= e <= -32.
  12324. */
  12325. inline void grisu2_digit_gen(char* buffer, int& length, int& decimal_exponent,
  12326. diyfp M_minus, diyfp w, diyfp M_plus)
  12327. {
  12328. static_assert(kAlpha >= -60, "internal error");
  12329. static_assert(kGamma <= -32, "internal error");
  12330. // Generates the digits (and the exponent) of a decimal floating-point
  12331. // number V = buffer * 10^decimal_exponent in the range [M-, M+]. The diyfp's
  12332. // w, M- and M+ share the same exponent e, which satisfies alpha <= e <= gamma.
  12333. //
  12334. // <--------------------------- delta ---->
  12335. // <---- dist --------->
  12336. // --------------[------------------+-------------------]--------------
  12337. // M- w M+
  12338. //
  12339. // Grisu2 generates the digits of M+ from left to right and stops as soon as
  12340. // V is in [M-,M+].
  12341. assert(M_plus.e >= kAlpha);
  12342. assert(M_plus.e <= kGamma);
  12343. std::uint64_t delta = diyfp::sub(M_plus, M_minus).f; // (significand of (M+ - M-), implicit exponent is e)
  12344. std::uint64_t dist = diyfp::sub(M_plus, w ).f; // (significand of (M+ - w ), implicit exponent is e)
  12345. // Split M+ = f * 2^e into two parts p1 and p2 (note: e < 0):
  12346. //
  12347. // M+ = f * 2^e
  12348. // = ((f div 2^-e) * 2^-e + (f mod 2^-e)) * 2^e
  12349. // = ((p1 ) * 2^-e + (p2 )) * 2^e
  12350. // = p1 + p2 * 2^e
  12351. const diyfp one(std::uint64_t{1} << -M_plus.e, M_plus.e);
  12352. 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.)
  12353. std::uint64_t p2 = M_plus.f & (one.f - 1); // p2 = f mod 2^-e
  12354. // 1)
  12355. //
  12356. // Generate the digits of the integral part p1 = d[n-1]...d[1]d[0]
  12357. assert(p1 > 0);
  12358. std::uint32_t pow10;
  12359. const int k = find_largest_pow10(p1, pow10);
  12360. // 10^(k-1) <= p1 < 10^k, pow10 = 10^(k-1)
  12361. //
  12362. // p1 = (p1 div 10^(k-1)) * 10^(k-1) + (p1 mod 10^(k-1))
  12363. // = (d[k-1] ) * 10^(k-1) + (p1 mod 10^(k-1))
  12364. //
  12365. // M+ = p1 + p2 * 2^e
  12366. // = d[k-1] * 10^(k-1) + (p1 mod 10^(k-1)) + p2 * 2^e
  12367. // = d[k-1] * 10^(k-1) + ((p1 mod 10^(k-1)) * 2^-e + p2) * 2^e
  12368. // = d[k-1] * 10^(k-1) + ( rest) * 2^e
  12369. //
  12370. // Now generate the digits d[n] of p1 from left to right (n = k-1,...,0)
  12371. //
  12372. // p1 = d[k-1]...d[n] * 10^n + d[n-1]...d[0]
  12373. //
  12374. // but stop as soon as
  12375. //
  12376. // rest * 2^e = (d[n-1]...d[0] * 2^-e + p2) * 2^e <= delta * 2^e
  12377. int n = k;
  12378. while (n > 0)
  12379. {
  12380. // Invariants:
  12381. // M+ = buffer * 10^n + (p1 + p2 * 2^e) (buffer = 0 for n = k)
  12382. // pow10 = 10^(n-1) <= p1 < 10^n
  12383. //
  12384. const std::uint32_t d = p1 / pow10; // d = p1 div 10^(n-1)
  12385. const std::uint32_t r = p1 % pow10; // r = p1 mod 10^(n-1)
  12386. //
  12387. // M+ = buffer * 10^n + (d * 10^(n-1) + r) + p2 * 2^e
  12388. // = (buffer * 10 + d) * 10^(n-1) + (r + p2 * 2^e)
  12389. //
  12390. assert(d <= 9);
  12391. buffer[length++] = static_cast<char>('0' + d); // buffer := buffer * 10 + d
  12392. //
  12393. // M+ = buffer * 10^(n-1) + (r + p2 * 2^e)
  12394. //
  12395. p1 = r;
  12396. n--;
  12397. //
  12398. // M+ = buffer * 10^n + (p1 + p2 * 2^e)
  12399. // pow10 = 10^n
  12400. //
  12401. // Now check if enough digits have been generated.
  12402. // Compute
  12403. //
  12404. // p1 + p2 * 2^e = (p1 * 2^-e + p2) * 2^e = rest * 2^e
  12405. //
  12406. // Note:
  12407. // Since rest and delta share the same exponent e, it suffices to
  12408. // compare the significands.
  12409. const std::uint64_t rest = (std::uint64_t{p1} << -one.e) + p2;
  12410. if (rest <= delta)
  12411. {
  12412. // V = buffer * 10^n, with M- <= V <= M+.
  12413. decimal_exponent += n;
  12414. // We may now just stop. But instead look if the buffer could be
  12415. // decremented to bring V closer to w.
  12416. //
  12417. // pow10 = 10^n is now 1 ulp in the decimal representation V.
  12418. // The rounding procedure works with diyfp's with an implicit
  12419. // exponent of e.
  12420. //
  12421. // 10^n = (10^n * 2^-e) * 2^e = ulp * 2^e
  12422. //
  12423. const std::uint64_t ten_n = std::uint64_t{pow10} << -one.e;
  12424. grisu2_round(buffer, length, dist, delta, rest, ten_n);
  12425. return;
  12426. }
  12427. pow10 /= 10;
  12428. //
  12429. // pow10 = 10^(n-1) <= p1 < 10^n
  12430. // Invariants restored.
  12431. }
  12432. // 2)
  12433. //
  12434. // The digits of the integral part have been generated:
  12435. //
  12436. // M+ = d[k-1]...d[1]d[0] + p2 * 2^e
  12437. // = buffer + p2 * 2^e
  12438. //
  12439. // Now generate the digits of the fractional part p2 * 2^e.
  12440. //
  12441. // Note:
  12442. // No decimal point is generated: the exponent is adjusted instead.
  12443. //
  12444. // p2 actually represents the fraction
  12445. //
  12446. // p2 * 2^e
  12447. // = p2 / 2^-e
  12448. // = d[-1] / 10^1 + d[-2] / 10^2 + ...
  12449. //
  12450. // Now generate the digits d[-m] of p1 from left to right (m = 1,2,...)
  12451. //
  12452. // p2 * 2^e = d[-1]d[-2]...d[-m] * 10^-m
  12453. // + 10^-m * (d[-m-1] / 10^1 + d[-m-2] / 10^2 + ...)
  12454. //
  12455. // using
  12456. //
  12457. // 10^m * p2 = ((10^m * p2) div 2^-e) * 2^-e + ((10^m * p2) mod 2^-e)
  12458. // = ( d) * 2^-e + ( r)
  12459. //
  12460. // or
  12461. // 10^m * p2 * 2^e = d + r * 2^e
  12462. //
  12463. // i.e.
  12464. //
  12465. // M+ = buffer + p2 * 2^e
  12466. // = buffer + 10^-m * (d + r * 2^e)
  12467. // = (buffer * 10^m + d) * 10^-m + 10^-m * r * 2^e
  12468. //
  12469. // and stop as soon as 10^-m * r * 2^e <= delta * 2^e
  12470. assert(p2 > delta);
  12471. int m = 0;
  12472. for (;;)
  12473. {
  12474. // Invariant:
  12475. // M+ = buffer * 10^-m + 10^-m * (d[-m-1] / 10 + d[-m-2] / 10^2 + ...) * 2^e
  12476. // = buffer * 10^-m + 10^-m * (p2 ) * 2^e
  12477. // = buffer * 10^-m + 10^-m * (1/10 * (10 * p2) ) * 2^e
  12478. // = buffer * 10^-m + 10^-m * (1/10 * ((10*p2 div 2^-e) * 2^-e + (10*p2 mod 2^-e)) * 2^e
  12479. //
  12480. assert(p2 <= (std::numeric_limits<std::uint64_t>::max)() / 10);
  12481. p2 *= 10;
  12482. const std::uint64_t d = p2 >> -one.e; // d = (10 * p2) div 2^-e
  12483. const std::uint64_t r = p2 & (one.f - 1); // r = (10 * p2) mod 2^-e
  12484. //
  12485. // M+ = buffer * 10^-m + 10^-m * (1/10 * (d * 2^-e + r) * 2^e
  12486. // = buffer * 10^-m + 10^-m * (1/10 * (d + r * 2^e))
  12487. // = (buffer * 10 + d) * 10^(-m-1) + 10^(-m-1) * r * 2^e
  12488. //
  12489. assert(d <= 9);
  12490. buffer[length++] = static_cast<char>('0' + d); // buffer := buffer * 10 + d
  12491. //
  12492. // M+ = buffer * 10^(-m-1) + 10^(-m-1) * r * 2^e
  12493. //
  12494. p2 = r;
  12495. m++;
  12496. //
  12497. // M+ = buffer * 10^-m + 10^-m * p2 * 2^e
  12498. // Invariant restored.
  12499. // Check if enough digits have been generated.
  12500. //
  12501. // 10^-m * p2 * 2^e <= delta * 2^e
  12502. // p2 * 2^e <= 10^m * delta * 2^e
  12503. // p2 <= 10^m * delta
  12504. delta *= 10;
  12505. dist *= 10;
  12506. if (p2 <= delta)
  12507. {
  12508. break;
  12509. }
  12510. }
  12511. // V = buffer * 10^-m, with M- <= V <= M+.
  12512. decimal_exponent -= m;
  12513. // 1 ulp in the decimal representation is now 10^-m.
  12514. // Since delta and dist are now scaled by 10^m, we need to do the
  12515. // same with ulp in order to keep the units in sync.
  12516. //
  12517. // 10^m * 10^-m = 1 = 2^-e * 2^e = ten_m * 2^e
  12518. //
  12519. const std::uint64_t ten_m = one.f;
  12520. grisu2_round(buffer, length, dist, delta, p2, ten_m);
  12521. // By construction this algorithm generates the shortest possible decimal
  12522. // number (Loitsch, Theorem 6.2) which rounds back to w.
  12523. // For an input number of precision p, at least
  12524. //
  12525. // N = 1 + ceil(p * log_10(2))
  12526. //
  12527. // decimal digits are sufficient to identify all binary floating-point
  12528. // numbers (Matula, "In-and-Out conversions").
  12529. // This implies that the algorithm does not produce more than N decimal
  12530. // digits.
  12531. //
  12532. // N = 17 for p = 53 (IEEE double precision)
  12533. // N = 9 for p = 24 (IEEE single precision)
  12534. }
  12535. /*!
  12536. v = buf * 10^decimal_exponent
  12537. len is the length of the buffer (number of decimal digits)
  12538. The buffer must be large enough, i.e. >= max_digits10.
  12539. */
  12540. JSON_HEDLEY_NON_NULL(1)
  12541. inline void grisu2(char* buf, int& len, int& decimal_exponent,
  12542. diyfp m_minus, diyfp v, diyfp m_plus)
  12543. {
  12544. assert(m_plus.e == m_minus.e);
  12545. assert(m_plus.e == v.e);
  12546. // --------(-----------------------+-----------------------)-------- (A)
  12547. // m- v m+
  12548. //
  12549. // --------------------(-----------+-----------------------)-------- (B)
  12550. // m- v m+
  12551. //
  12552. // First scale v (and m- and m+) such that the exponent is in the range
  12553. // [alpha, gamma].
  12554. const cached_power cached = get_cached_power_for_binary_exponent(m_plus.e);
  12555. const diyfp c_minus_k(cached.f, cached.e); // = c ~= 10^-k
  12556. // The exponent of the products is = v.e + c_minus_k.e + q and is in the range [alpha,gamma]
  12557. const diyfp w = diyfp::mul(v, c_minus_k);
  12558. const diyfp w_minus = diyfp::mul(m_minus, c_minus_k);
  12559. const diyfp w_plus = diyfp::mul(m_plus, c_minus_k);
  12560. // ----(---+---)---------------(---+---)---------------(---+---)----
  12561. // w- w w+
  12562. // = c*m- = c*v = c*m+
  12563. //
  12564. // diyfp::mul rounds its result and c_minus_k is approximated too. w, w- and
  12565. // w+ are now off by a small amount.
  12566. // In fact:
  12567. //
  12568. // w - v * 10^k < 1 ulp
  12569. //
  12570. // To account for this inaccuracy, add resp. subtract 1 ulp.
  12571. //
  12572. // --------+---[---------------(---+---)---------------]---+--------
  12573. // w- M- w M+ w+
  12574. //
  12575. // Now any number in [M-, M+] (bounds included) will round to w when input,
  12576. // regardless of how the input rounding algorithm breaks ties.
  12577. //
  12578. // And digit_gen generates the shortest possible such number in [M-, M+].
  12579. // Note that this does not mean that Grisu2 always generates the shortest
  12580. // possible number in the interval (m-, m+).
  12581. const diyfp M_minus(w_minus.f + 1, w_minus.e);
  12582. const diyfp M_plus (w_plus.f - 1, w_plus.e );
  12583. decimal_exponent = -cached.k; // = -(-k) = k
  12584. grisu2_digit_gen(buf, len, decimal_exponent, M_minus, w, M_plus);
  12585. }
  12586. /*!
  12587. v = buf * 10^decimal_exponent
  12588. len is the length of the buffer (number of decimal digits)
  12589. The buffer must be large enough, i.e. >= max_digits10.
  12590. */
  12591. template <typename FloatType>
  12592. JSON_HEDLEY_NON_NULL(1)
  12593. void grisu2(char* buf, int& len, int& decimal_exponent, FloatType value)
  12594. {
  12595. static_assert(diyfp::kPrecision >= std::numeric_limits<FloatType>::digits + 3,
  12596. "internal error: not enough precision");
  12597. assert(std::isfinite(value));
  12598. assert(value > 0);
  12599. // If the neighbors (and boundaries) of 'value' are always computed for double-precision
  12600. // numbers, all float's can be recovered using strtod (and strtof). However, the resulting
  12601. // decimal representations are not exactly "short".
  12602. //
  12603. // The documentation for 'std::to_chars' (https://en.cppreference.com/w/cpp/utility/to_chars)
  12604. // says "value is converted to a string as if by std::sprintf in the default ("C") locale"
  12605. // and since sprintf promotes float's to double's, I think this is exactly what 'std::to_chars'
  12606. // does.
  12607. // On the other hand, the documentation for 'std::to_chars' requires that "parsing the
  12608. // representation using the corresponding std::from_chars function recovers value exactly". That
  12609. // indicates that single precision floating-point numbers should be recovered using
  12610. // 'std::strtof'.
  12611. //
  12612. // NB: If the neighbors are computed for single-precision numbers, there is a single float
  12613. // (7.0385307e-26f) which can't be recovered using strtod. The resulting double precision
  12614. // value is off by 1 ulp.
  12615. #if 0
  12616. const boundaries w = compute_boundaries(static_cast<double>(value));
  12617. #else
  12618. const boundaries w = compute_boundaries(value);
  12619. #endif
  12620. grisu2(buf, len, decimal_exponent, w.minus, w.w, w.plus);
  12621. }
  12622. /*!
  12623. @brief appends a decimal representation of e to buf
  12624. @return a pointer to the element following the exponent.
  12625. @pre -1000 < e < 1000
  12626. */
  12627. JSON_HEDLEY_NON_NULL(1)
  12628. JSON_HEDLEY_RETURNS_NON_NULL
  12629. inline char* append_exponent(char* buf, int e)
  12630. {
  12631. assert(e > -1000);
  12632. assert(e < 1000);
  12633. if (e < 0)
  12634. {
  12635. e = -e;
  12636. *buf++ = '-';
  12637. }
  12638. else
  12639. {
  12640. *buf++ = '+';
  12641. }
  12642. auto k = static_cast<std::uint32_t>(e);
  12643. if (k < 10)
  12644. {
  12645. // Always print at least two digits in the exponent.
  12646. // This is for compatibility with printf("%g").
  12647. *buf++ = '0';
  12648. *buf++ = static_cast<char>('0' + k);
  12649. }
  12650. else if (k < 100)
  12651. {
  12652. *buf++ = static_cast<char>('0' + k / 10);
  12653. k %= 10;
  12654. *buf++ = static_cast<char>('0' + k);
  12655. }
  12656. else
  12657. {
  12658. *buf++ = static_cast<char>('0' + k / 100);
  12659. k %= 100;
  12660. *buf++ = static_cast<char>('0' + k / 10);
  12661. k %= 10;
  12662. *buf++ = static_cast<char>('0' + k);
  12663. }
  12664. return buf;
  12665. }
  12666. /*!
  12667. @brief prettify v = buf * 10^decimal_exponent
  12668. If v is in the range [10^min_exp, 10^max_exp) it will be printed in fixed-point
  12669. notation. Otherwise it will be printed in exponential notation.
  12670. @pre min_exp < 0
  12671. @pre max_exp > 0
  12672. */
  12673. JSON_HEDLEY_NON_NULL(1)
  12674. JSON_HEDLEY_RETURNS_NON_NULL
  12675. inline char* format_buffer(char* buf, int len, int decimal_exponent,
  12676. int min_exp, int max_exp)
  12677. {
  12678. assert(min_exp < 0);
  12679. assert(max_exp > 0);
  12680. const int k = len;
  12681. const int n = len + decimal_exponent;
  12682. // v = buf * 10^(n-k)
  12683. // k is the length of the buffer (number of decimal digits)
  12684. // n is the position of the decimal point relative to the start of the buffer.
  12685. if (k <= n and n <= max_exp)
  12686. {
  12687. // digits[000]
  12688. // len <= max_exp + 2
  12689. std::memset(buf + k, '0', static_cast<size_t>(n) - static_cast<size_t>(k));
  12690. // Make it look like a floating-point number (#362, #378)
  12691. buf[n + 0] = '.';
  12692. buf[n + 1] = '0';
  12693. return buf + (static_cast<size_t>(n) + 2);
  12694. }
  12695. if (0 < n and n <= max_exp)
  12696. {
  12697. // dig.its
  12698. // len <= max_digits10 + 1
  12699. assert(k > n);
  12700. std::memmove(buf + (static_cast<size_t>(n) + 1), buf + n, static_cast<size_t>(k) - static_cast<size_t>(n));
  12701. buf[n] = '.';
  12702. return buf + (static_cast<size_t>(k) + 1U);
  12703. }
  12704. if (min_exp < n and n <= 0)
  12705. {
  12706. // 0.[000]digits
  12707. // len <= 2 + (-min_exp - 1) + max_digits10
  12708. std::memmove(buf + (2 + static_cast<size_t>(-n)), buf, static_cast<size_t>(k));
  12709. buf[0] = '0';
  12710. buf[1] = '.';
  12711. std::memset(buf + 2, '0', static_cast<size_t>(-n));
  12712. return buf + (2U + static_cast<size_t>(-n) + static_cast<size_t>(k));
  12713. }
  12714. if (k == 1)
  12715. {
  12716. // dE+123
  12717. // len <= 1 + 5
  12718. buf += 1;
  12719. }
  12720. else
  12721. {
  12722. // d.igitsE+123
  12723. // len <= max_digits10 + 1 + 5
  12724. std::memmove(buf + 2, buf + 1, static_cast<size_t>(k) - 1);
  12725. buf[1] = '.';
  12726. buf += 1 + static_cast<size_t>(k);
  12727. }
  12728. *buf++ = 'e';
  12729. return append_exponent(buf, n - 1);
  12730. }
  12731. } // namespace dtoa_impl
  12732. /*!
  12733. @brief generates a decimal representation of the floating-point number value in [first, last).
  12734. The format of the resulting decimal representation is similar to printf's %g
  12735. format. Returns an iterator pointing past-the-end of the decimal representation.
  12736. @note The input number must be finite, i.e. NaN's and Inf's are not supported.
  12737. @note The buffer must be large enough.
  12738. @note The result is NOT null-terminated.
  12739. */
  12740. template <typename FloatType>
  12741. JSON_HEDLEY_NON_NULL(1, 2)
  12742. JSON_HEDLEY_RETURNS_NON_NULL
  12743. char* to_chars(char* first, const char* last, FloatType value)
  12744. {
  12745. static_cast<void>(last); // maybe unused - fix warning
  12746. assert(std::isfinite(value));
  12747. // Use signbit(value) instead of (value < 0) since signbit works for -0.
  12748. if (std::signbit(value))
  12749. {
  12750. value = -value;
  12751. *first++ = '-';
  12752. }
  12753. if (value == 0) // +-0
  12754. {
  12755. *first++ = '0';
  12756. // Make it look like a floating-point number (#362, #378)
  12757. *first++ = '.';
  12758. *first++ = '0';
  12759. return first;
  12760. }
  12761. assert(last - first >= std::numeric_limits<FloatType>::max_digits10);
  12762. // Compute v = buffer * 10^decimal_exponent.
  12763. // The decimal digits are stored in the buffer, which needs to be interpreted
  12764. // as an unsigned decimal integer.
  12765. // len is the length of the buffer, i.e. the number of decimal digits.
  12766. int len = 0;
  12767. int decimal_exponent = 0;
  12768. dtoa_impl::grisu2(first, len, decimal_exponent, value);
  12769. assert(len <= std::numeric_limits<FloatType>::max_digits10);
  12770. // Format the buffer like printf("%.*g", prec, value)
  12771. constexpr int kMinExp = -4;
  12772. // Use digits10 here to increase compatibility with version 2.
  12773. constexpr int kMaxExp = std::numeric_limits<FloatType>::digits10;
  12774. assert(last - first >= kMaxExp + 2);
  12775. assert(last - first >= 2 + (-kMinExp - 1) + std::numeric_limits<FloatType>::max_digits10);
  12776. assert(last - first >= std::numeric_limits<FloatType>::max_digits10 + 6);
  12777. return dtoa_impl::format_buffer(first, len, decimal_exponent, kMinExp, kMaxExp);
  12778. }
  12779. } // namespace detail
  12780. } // namespace nlohmann
  12781. // #include <nlohmann/detail/exceptions.hpp>
  12782. // #include <nlohmann/detail/macro_scope.hpp>
  12783. // #include <nlohmann/detail/meta/cpp_future.hpp>
  12784. // #include <nlohmann/detail/output/binary_writer.hpp>
  12785. // #include <nlohmann/detail/output/output_adapters.hpp>
  12786. // #include <nlohmann/detail/value_t.hpp>
  12787. namespace nlohmann
  12788. {
  12789. namespace detail
  12790. {
  12791. ///////////////////
  12792. // serialization //
  12793. ///////////////////
  12794. /// how to treat decoding errors
  12795. enum class error_handler_t
  12796. {
  12797. strict, ///< throw a type_error exception in case of invalid UTF-8
  12798. replace, ///< replace invalid UTF-8 sequences with U+FFFD
  12799. ignore ///< ignore invalid UTF-8 sequences
  12800. };
  12801. template<typename BasicJsonType>
  12802. class serializer
  12803. {
  12804. using string_t = typename BasicJsonType::string_t;
  12805. using number_float_t = typename BasicJsonType::number_float_t;
  12806. using number_integer_t = typename BasicJsonType::number_integer_t;
  12807. using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
  12808. using binary_t = typename BasicJsonType::binary_t;
  12809. static constexpr std::uint8_t UTF8_ACCEPT = 0;
  12810. static constexpr std::uint8_t UTF8_REJECT = 1;
  12811. public:
  12812. /*!
  12813. @param[in] s output stream to serialize to
  12814. @param[in] ichar indentation character to use
  12815. @param[in] error_handler_ how to react on decoding errors
  12816. */
  12817. serializer(output_adapter_t<char> s, const char ichar,
  12818. error_handler_t error_handler_ = error_handler_t::strict)
  12819. : o(std::move(s))
  12820. , loc(std::localeconv())
  12821. , thousands_sep(loc->thousands_sep == nullptr ? '\0' : * (loc->thousands_sep))
  12822. , decimal_point(loc->decimal_point == nullptr ? '\0' : * (loc->decimal_point))
  12823. , indent_char(ichar)
  12824. , indent_string(512, indent_char)
  12825. , error_handler(error_handler_)
  12826. {}
  12827. // delete because of pointer members
  12828. serializer(const serializer&) = delete;
  12829. serializer& operator=(const serializer&) = delete;
  12830. serializer(serializer&&) = delete;
  12831. serializer& operator=(serializer&&) = delete;
  12832. ~serializer() = default;
  12833. /*!
  12834. @brief internal implementation of the serialization function
  12835. This function is called by the public member function dump and organizes
  12836. the serialization internally. The indentation level is propagated as
  12837. additional parameter. In case of arrays and objects, the function is
  12838. called recursively.
  12839. - strings and object keys are escaped using `escape_string()`
  12840. - integer numbers are converted implicitly via `operator<<`
  12841. - floating-point numbers are converted to a string using `"%g"` format
  12842. - if specified to, binary values are output using the syntax `b[]`, otherwise an exception is thrown
  12843. @param[in] val value to serialize
  12844. @param[in] pretty_print whether the output shall be pretty-printed
  12845. @param[in] indent_step the indent level
  12846. @param[in] current_indent the current indent level (only used internally)
  12847. @param[in] serialize_binary whether the output shall include non-standard binary output
  12848. */
  12849. void dump(const BasicJsonType& val, const bool pretty_print,
  12850. const bool ensure_ascii,
  12851. const unsigned int indent_step,
  12852. const unsigned int current_indent = 0,
  12853. const bool serialize_binary = false)
  12854. {
  12855. switch (val.m_type)
  12856. {
  12857. case value_t::object:
  12858. {
  12859. if (val.m_value.object->empty())
  12860. {
  12861. o->write_characters("{}", 2);
  12862. return;
  12863. }
  12864. if (pretty_print)
  12865. {
  12866. o->write_characters("{\n", 2);
  12867. // variable to hold indentation for recursive calls
  12868. const auto new_indent = current_indent + indent_step;
  12869. if (JSON_HEDLEY_UNLIKELY(indent_string.size() < new_indent))
  12870. {
  12871. indent_string.resize(indent_string.size() * 2, ' ');
  12872. }
  12873. // first n-1 elements
  12874. auto i = val.m_value.object->cbegin();
  12875. for (std::size_t cnt = 0; cnt < val.m_value.object->size() - 1; ++cnt, ++i)
  12876. {
  12877. o->write_characters(indent_string.c_str(), new_indent);
  12878. o->write_character('\"');
  12879. dump_escaped(i->first, ensure_ascii);
  12880. o->write_characters("\": ", 3);
  12881. dump(i->second, true, ensure_ascii, indent_step, new_indent, serialize_binary);
  12882. o->write_characters(",\n", 2);
  12883. }
  12884. // last element
  12885. assert(i != val.m_value.object->cend());
  12886. assert(std::next(i) == val.m_value.object->cend());
  12887. o->write_characters(indent_string.c_str(), new_indent);
  12888. o->write_character('\"');
  12889. dump_escaped(i->first, ensure_ascii);
  12890. o->write_characters("\": ", 3);
  12891. dump(i->second, true, ensure_ascii, indent_step, new_indent, serialize_binary);
  12892. o->write_character('\n');
  12893. o->write_characters(indent_string.c_str(), current_indent);
  12894. o->write_character('}');
  12895. }
  12896. else
  12897. {
  12898. o->write_character('{');
  12899. // first n-1 elements
  12900. auto i = val.m_value.object->cbegin();
  12901. for (std::size_t cnt = 0; cnt < val.m_value.object->size() - 1; ++cnt, ++i)
  12902. {
  12903. o->write_character('\"');
  12904. dump_escaped(i->first, ensure_ascii);
  12905. o->write_characters("\":", 2);
  12906. dump(i->second, false, ensure_ascii, indent_step, current_indent, serialize_binary);
  12907. o->write_character(',');
  12908. }
  12909. // last element
  12910. assert(i != val.m_value.object->cend());
  12911. assert(std::next(i) == val.m_value.object->cend());
  12912. o->write_character('\"');
  12913. dump_escaped(i->first, ensure_ascii);
  12914. o->write_characters("\":", 2);
  12915. dump(i->second, false, ensure_ascii, indent_step, current_indent, serialize_binary);
  12916. o->write_character('}');
  12917. }
  12918. return;
  12919. }
  12920. case value_t::array:
  12921. {
  12922. if (val.m_value.array->empty())
  12923. {
  12924. o->write_characters("[]", 2);
  12925. return;
  12926. }
  12927. if (pretty_print)
  12928. {
  12929. o->write_characters("[\n", 2);
  12930. // variable to hold indentation for recursive calls
  12931. const auto new_indent = current_indent + indent_step;
  12932. if (JSON_HEDLEY_UNLIKELY(indent_string.size() < new_indent))
  12933. {
  12934. indent_string.resize(indent_string.size() * 2, ' ');
  12935. }
  12936. // first n-1 elements
  12937. for (auto i = val.m_value.array->cbegin();
  12938. i != val.m_value.array->cend() - 1; ++i)
  12939. {
  12940. o->write_characters(indent_string.c_str(), new_indent);
  12941. dump(*i, true, ensure_ascii, indent_step, new_indent, serialize_binary);
  12942. o->write_characters(",\n", 2);
  12943. }
  12944. // last element
  12945. assert(not val.m_value.array->empty());
  12946. o->write_characters(indent_string.c_str(), new_indent);
  12947. dump(val.m_value.array->back(), true, ensure_ascii, indent_step, new_indent, serialize_binary);
  12948. o->write_character('\n');
  12949. o->write_characters(indent_string.c_str(), current_indent);
  12950. o->write_character(']');
  12951. }
  12952. else
  12953. {
  12954. o->write_character('[');
  12955. // first n-1 elements
  12956. for (auto i = val.m_value.array->cbegin();
  12957. i != val.m_value.array->cend() - 1; ++i)
  12958. {
  12959. dump(*i, false, ensure_ascii, indent_step, current_indent, serialize_binary);
  12960. o->write_character(',');
  12961. }
  12962. // last element
  12963. assert(not val.m_value.array->empty());
  12964. dump(val.m_value.array->back(), false, ensure_ascii, indent_step, current_indent, serialize_binary);
  12965. o->write_character(']');
  12966. }
  12967. return;
  12968. }
  12969. case value_t::string:
  12970. {
  12971. o->write_character('\"');
  12972. dump_escaped(*val.m_value.string, ensure_ascii);
  12973. o->write_character('\"');
  12974. return;
  12975. }
  12976. case value_t::binary:
  12977. {
  12978. if (not serialize_binary)
  12979. {
  12980. JSON_THROW(type_error::create(317, "cannot serialize binary data to text JSON"));
  12981. }
  12982. if (val.m_value.binary->empty())
  12983. {
  12984. o->write_characters("b[]", 3);
  12985. }
  12986. else
  12987. {
  12988. o->write_characters("b[", 2);
  12989. for (auto i = val.m_value.binary->cbegin();
  12990. i != val.m_value.binary->cend() - 1; ++i)
  12991. {
  12992. dump_integer(*i);
  12993. o->write_character(',');
  12994. }
  12995. dump_integer(val.m_value.binary->back());
  12996. o->write_character(']');
  12997. }
  12998. return;
  12999. }
  13000. case value_t::boolean:
  13001. {
  13002. if (val.m_value.boolean)
  13003. {
  13004. o->write_characters("true", 4);
  13005. }
  13006. else
  13007. {
  13008. o->write_characters("false", 5);
  13009. }
  13010. return;
  13011. }
  13012. case value_t::number_integer:
  13013. {
  13014. dump_integer(val.m_value.number_integer);
  13015. return;
  13016. }
  13017. case value_t::number_unsigned:
  13018. {
  13019. dump_integer(val.m_value.number_unsigned);
  13020. return;
  13021. }
  13022. case value_t::number_float:
  13023. {
  13024. dump_float(val.m_value.number_float);
  13025. return;
  13026. }
  13027. case value_t::discarded:
  13028. {
  13029. o->write_characters("<discarded>", 11);
  13030. return;
  13031. }
  13032. case value_t::null:
  13033. {
  13034. o->write_characters("null", 4);
  13035. return;
  13036. }
  13037. default: // LCOV_EXCL_LINE
  13038. assert(false); // LCOV_EXCL_LINE
  13039. }
  13040. }
  13041. private:
  13042. /*!
  13043. @brief dump escaped string
  13044. Escape a string by replacing certain special characters by a sequence of an
  13045. escape character (backslash) and another character and other control
  13046. characters by a sequence of "\u" followed by a four-digit hex
  13047. representation. The escaped string is written to output stream @a o.
  13048. @param[in] s the string to escape
  13049. @param[in] ensure_ascii whether to escape non-ASCII characters with
  13050. \uXXXX sequences
  13051. @complexity Linear in the length of string @a s.
  13052. */
  13053. void dump_escaped(const string_t& s, const bool ensure_ascii)
  13054. {
  13055. std::uint32_t codepoint;
  13056. std::uint8_t state = UTF8_ACCEPT;
  13057. std::size_t bytes = 0; // number of bytes written to string_buffer
  13058. // number of bytes written at the point of the last valid byte
  13059. std::size_t bytes_after_last_accept = 0;
  13060. std::size_t undumped_chars = 0;
  13061. for (std::size_t i = 0; i < s.size(); ++i)
  13062. {
  13063. const auto byte = static_cast<uint8_t>(s[i]);
  13064. switch (decode(state, codepoint, byte))
  13065. {
  13066. case UTF8_ACCEPT: // decode found a new code point
  13067. {
  13068. switch (codepoint)
  13069. {
  13070. case 0x08: // backspace
  13071. {
  13072. string_buffer[bytes++] = '\\';
  13073. string_buffer[bytes++] = 'b';
  13074. break;
  13075. }
  13076. case 0x09: // horizontal tab
  13077. {
  13078. string_buffer[bytes++] = '\\';
  13079. string_buffer[bytes++] = 't';
  13080. break;
  13081. }
  13082. case 0x0A: // newline
  13083. {
  13084. string_buffer[bytes++] = '\\';
  13085. string_buffer[bytes++] = 'n';
  13086. break;
  13087. }
  13088. case 0x0C: // formfeed
  13089. {
  13090. string_buffer[bytes++] = '\\';
  13091. string_buffer[bytes++] = 'f';
  13092. break;
  13093. }
  13094. case 0x0D: // carriage return
  13095. {
  13096. string_buffer[bytes++] = '\\';
  13097. string_buffer[bytes++] = 'r';
  13098. break;
  13099. }
  13100. case 0x22: // quotation mark
  13101. {
  13102. string_buffer[bytes++] = '\\';
  13103. string_buffer[bytes++] = '\"';
  13104. break;
  13105. }
  13106. case 0x5C: // reverse solidus
  13107. {
  13108. string_buffer[bytes++] = '\\';
  13109. string_buffer[bytes++] = '\\';
  13110. break;
  13111. }
  13112. default:
  13113. {
  13114. // escape control characters (0x00..0x1F) or, if
  13115. // ensure_ascii parameter is used, non-ASCII characters
  13116. if ((codepoint <= 0x1F) or (ensure_ascii and (codepoint >= 0x7F)))
  13117. {
  13118. if (codepoint <= 0xFFFF)
  13119. {
  13120. (std::snprintf)(string_buffer.data() + bytes, 7, "\\u%04x",
  13121. static_cast<std::uint16_t>(codepoint));
  13122. bytes += 6;
  13123. }
  13124. else
  13125. {
  13126. (std::snprintf)(string_buffer.data() + bytes, 13, "\\u%04x\\u%04x",
  13127. static_cast<std::uint16_t>(0xD7C0u + (codepoint >> 10u)),
  13128. static_cast<std::uint16_t>(0xDC00u + (codepoint & 0x3FFu)));
  13129. bytes += 12;
  13130. }
  13131. }
  13132. else
  13133. {
  13134. // copy byte to buffer (all previous bytes
  13135. // been copied have in default case above)
  13136. string_buffer[bytes++] = s[i];
  13137. }
  13138. break;
  13139. }
  13140. }
  13141. // write buffer and reset index; there must be 13 bytes
  13142. // left, as this is the maximal number of bytes to be
  13143. // written ("\uxxxx\uxxxx\0") for one code point
  13144. if (string_buffer.size() - bytes < 13)
  13145. {
  13146. o->write_characters(string_buffer.data(), bytes);
  13147. bytes = 0;
  13148. }
  13149. // remember the byte position of this accept
  13150. bytes_after_last_accept = bytes;
  13151. undumped_chars = 0;
  13152. break;
  13153. }
  13154. case UTF8_REJECT: // decode found invalid UTF-8 byte
  13155. {
  13156. switch (error_handler)
  13157. {
  13158. case error_handler_t::strict:
  13159. {
  13160. std::string sn(3, '\0');
  13161. (std::snprintf)(&sn[0], sn.size(), "%.2X", byte);
  13162. JSON_THROW(type_error::create(316, "invalid UTF-8 byte at index " + std::to_string(i) + ": 0x" + sn));
  13163. }
  13164. case error_handler_t::ignore:
  13165. case error_handler_t::replace:
  13166. {
  13167. // in case we saw this character the first time, we
  13168. // would like to read it again, because the byte
  13169. // may be OK for itself, but just not OK for the
  13170. // previous sequence
  13171. if (undumped_chars > 0)
  13172. {
  13173. --i;
  13174. }
  13175. // reset length buffer to the last accepted index;
  13176. // thus removing/ignoring the invalid characters
  13177. bytes = bytes_after_last_accept;
  13178. if (error_handler == error_handler_t::replace)
  13179. {
  13180. // add a replacement character
  13181. if (ensure_ascii)
  13182. {
  13183. string_buffer[bytes++] = '\\';
  13184. string_buffer[bytes++] = 'u';
  13185. string_buffer[bytes++] = 'f';
  13186. string_buffer[bytes++] = 'f';
  13187. string_buffer[bytes++] = 'f';
  13188. string_buffer[bytes++] = 'd';
  13189. }
  13190. else
  13191. {
  13192. string_buffer[bytes++] = detail::binary_writer<BasicJsonType, char>::to_char_type('\xEF');
  13193. string_buffer[bytes++] = detail::binary_writer<BasicJsonType, char>::to_char_type('\xBF');
  13194. string_buffer[bytes++] = detail::binary_writer<BasicJsonType, char>::to_char_type('\xBD');
  13195. }
  13196. // write buffer and reset index; there must be 13 bytes
  13197. // left, as this is the maximal number of bytes to be
  13198. // written ("\uxxxx\uxxxx\0") for one code point
  13199. if (string_buffer.size() - bytes < 13)
  13200. {
  13201. o->write_characters(string_buffer.data(), bytes);
  13202. bytes = 0;
  13203. }
  13204. bytes_after_last_accept = bytes;
  13205. }
  13206. undumped_chars = 0;
  13207. // continue processing the string
  13208. state = UTF8_ACCEPT;
  13209. break;
  13210. }
  13211. default: // LCOV_EXCL_LINE
  13212. assert(false); // LCOV_EXCL_LINE
  13213. }
  13214. break;
  13215. }
  13216. default: // decode found yet incomplete multi-byte code point
  13217. {
  13218. if (not ensure_ascii)
  13219. {
  13220. // code point will not be escaped - copy byte to buffer
  13221. string_buffer[bytes++] = s[i];
  13222. }
  13223. ++undumped_chars;
  13224. break;
  13225. }
  13226. }
  13227. }
  13228. // we finished processing the string
  13229. if (JSON_HEDLEY_LIKELY(state == UTF8_ACCEPT))
  13230. {
  13231. // write buffer
  13232. if (bytes > 0)
  13233. {
  13234. o->write_characters(string_buffer.data(), bytes);
  13235. }
  13236. }
  13237. else
  13238. {
  13239. // we finish reading, but do not accept: string was incomplete
  13240. switch (error_handler)
  13241. {
  13242. case error_handler_t::strict:
  13243. {
  13244. std::string sn(3, '\0');
  13245. (std::snprintf)(&sn[0], sn.size(), "%.2X", static_cast<std::uint8_t>(s.back()));
  13246. JSON_THROW(type_error::create(316, "incomplete UTF-8 string; last byte: 0x" + sn));
  13247. }
  13248. case error_handler_t::ignore:
  13249. {
  13250. // write all accepted bytes
  13251. o->write_characters(string_buffer.data(), bytes_after_last_accept);
  13252. break;
  13253. }
  13254. case error_handler_t::replace:
  13255. {
  13256. // write all accepted bytes
  13257. o->write_characters(string_buffer.data(), bytes_after_last_accept);
  13258. // add a replacement character
  13259. if (ensure_ascii)
  13260. {
  13261. o->write_characters("\\ufffd", 6);
  13262. }
  13263. else
  13264. {
  13265. o->write_characters("\xEF\xBF\xBD", 3);
  13266. }
  13267. break;
  13268. }
  13269. default: // LCOV_EXCL_LINE
  13270. assert(false); // LCOV_EXCL_LINE
  13271. }
  13272. }
  13273. }
  13274. /*!
  13275. @brief count digits
  13276. Count the number of decimal (base 10) digits for an input unsigned integer.
  13277. @param[in] x unsigned integer number to count its digits
  13278. @return number of decimal digits
  13279. */
  13280. inline unsigned int count_digits(number_unsigned_t x) noexcept
  13281. {
  13282. unsigned int n_digits = 1;
  13283. for (;;)
  13284. {
  13285. if (x < 10)
  13286. {
  13287. return n_digits;
  13288. }
  13289. if (x < 100)
  13290. {
  13291. return n_digits + 1;
  13292. }
  13293. if (x < 1000)
  13294. {
  13295. return n_digits + 2;
  13296. }
  13297. if (x < 10000)
  13298. {
  13299. return n_digits + 3;
  13300. }
  13301. x = x / 10000u;
  13302. n_digits += 4;
  13303. }
  13304. }
  13305. /*!
  13306. @brief dump an integer
  13307. Dump a given integer to output stream @a o. Works internally with
  13308. @a number_buffer.
  13309. @param[in] x integer number (signed or unsigned) to dump
  13310. @tparam NumberType either @a number_integer_t or @a number_unsigned_t
  13311. */
  13312. template<typename NumberType, detail::enable_if_t<
  13313. std::is_same<NumberType, number_unsigned_t>::value or
  13314. std::is_same<NumberType, number_integer_t>::value or
  13315. std::is_same<NumberType, typename binary_t::value_type>::value,
  13316. int> = 0>
  13317. void dump_integer(NumberType x)
  13318. {
  13319. static constexpr std::array<std::array<char, 2>, 100> digits_to_99
  13320. {
  13321. {
  13322. {{'0', '0'}}, {{'0', '1'}}, {{'0', '2'}}, {{'0', '3'}}, {{'0', '4'}}, {{'0', '5'}}, {{'0', '6'}}, {{'0', '7'}}, {{'0', '8'}}, {{'0', '9'}},
  13323. {{'1', '0'}}, {{'1', '1'}}, {{'1', '2'}}, {{'1', '3'}}, {{'1', '4'}}, {{'1', '5'}}, {{'1', '6'}}, {{'1', '7'}}, {{'1', '8'}}, {{'1', '9'}},
  13324. {{'2', '0'}}, {{'2', '1'}}, {{'2', '2'}}, {{'2', '3'}}, {{'2', '4'}}, {{'2', '5'}}, {{'2', '6'}}, {{'2', '7'}}, {{'2', '8'}}, {{'2', '9'}},
  13325. {{'3', '0'}}, {{'3', '1'}}, {{'3', '2'}}, {{'3', '3'}}, {{'3', '4'}}, {{'3', '5'}}, {{'3', '6'}}, {{'3', '7'}}, {{'3', '8'}}, {{'3', '9'}},
  13326. {{'4', '0'}}, {{'4', '1'}}, {{'4', '2'}}, {{'4', '3'}}, {{'4', '4'}}, {{'4', '5'}}, {{'4', '6'}}, {{'4', '7'}}, {{'4', '8'}}, {{'4', '9'}},
  13327. {{'5', '0'}}, {{'5', '1'}}, {{'5', '2'}}, {{'5', '3'}}, {{'5', '4'}}, {{'5', '5'}}, {{'5', '6'}}, {{'5', '7'}}, {{'5', '8'}}, {{'5', '9'}},
  13328. {{'6', '0'}}, {{'6', '1'}}, {{'6', '2'}}, {{'6', '3'}}, {{'6', '4'}}, {{'6', '5'}}, {{'6', '6'}}, {{'6', '7'}}, {{'6', '8'}}, {{'6', '9'}},
  13329. {{'7', '0'}}, {{'7', '1'}}, {{'7', '2'}}, {{'7', '3'}}, {{'7', '4'}}, {{'7', '5'}}, {{'7', '6'}}, {{'7', '7'}}, {{'7', '8'}}, {{'7', '9'}},
  13330. {{'8', '0'}}, {{'8', '1'}}, {{'8', '2'}}, {{'8', '3'}}, {{'8', '4'}}, {{'8', '5'}}, {{'8', '6'}}, {{'8', '7'}}, {{'8', '8'}}, {{'8', '9'}},
  13331. {{'9', '0'}}, {{'9', '1'}}, {{'9', '2'}}, {{'9', '3'}}, {{'9', '4'}}, {{'9', '5'}}, {{'9', '6'}}, {{'9', '7'}}, {{'9', '8'}}, {{'9', '9'}},
  13332. }
  13333. };
  13334. // special case for "0"
  13335. if (x == 0)
  13336. {
  13337. o->write_character('0');
  13338. return;
  13339. }
  13340. // use a pointer to fill the buffer
  13341. auto buffer_ptr = number_buffer.begin();
  13342. const bool is_negative = std::is_same<NumberType, number_integer_t>::value and not(x >= 0); // see issue #755
  13343. number_unsigned_t abs_value;
  13344. unsigned int n_chars;
  13345. if (is_negative)
  13346. {
  13347. *buffer_ptr = '-';
  13348. abs_value = remove_sign(static_cast<number_integer_t>(x));
  13349. // account one more byte for the minus sign
  13350. n_chars = 1 + count_digits(abs_value);
  13351. }
  13352. else
  13353. {
  13354. abs_value = static_cast<number_unsigned_t>(x);
  13355. n_chars = count_digits(abs_value);
  13356. }
  13357. // spare 1 byte for '\0'
  13358. assert(n_chars < number_buffer.size() - 1);
  13359. // jump to the end to generate the string from backward
  13360. // so we later avoid reversing the result
  13361. buffer_ptr += n_chars;
  13362. // Fast int2ascii implementation inspired by "Fastware" talk by Andrei Alexandrescu
  13363. // See: https://www.youtube.com/watch?v=o4-CwDo2zpg
  13364. while (abs_value >= 100)
  13365. {
  13366. const auto digits_index = static_cast<unsigned>((abs_value % 100));
  13367. abs_value /= 100;
  13368. *(--buffer_ptr) = digits_to_99[digits_index][1];
  13369. *(--buffer_ptr) = digits_to_99[digits_index][0];
  13370. }
  13371. if (abs_value >= 10)
  13372. {
  13373. const auto digits_index = static_cast<unsigned>(abs_value);
  13374. *(--buffer_ptr) = digits_to_99[digits_index][1];
  13375. *(--buffer_ptr) = digits_to_99[digits_index][0];
  13376. }
  13377. else
  13378. {
  13379. *(--buffer_ptr) = static_cast<char>('0' + abs_value);
  13380. }
  13381. o->write_characters(number_buffer.data(), n_chars);
  13382. }
  13383. /*!
  13384. @brief dump a floating-point number
  13385. Dump a given floating-point number to output stream @a o. Works internally
  13386. with @a number_buffer.
  13387. @param[in] x floating-point number to dump
  13388. */
  13389. void dump_float(number_float_t x)
  13390. {
  13391. // NaN / inf
  13392. if (not std::isfinite(x))
  13393. {
  13394. o->write_characters("null", 4);
  13395. return;
  13396. }
  13397. // If number_float_t is an IEEE-754 single or double precision number,
  13398. // use the Grisu2 algorithm to produce short numbers which are
  13399. // guaranteed to round-trip, using strtof and strtod, resp.
  13400. //
  13401. // NB: The test below works if <long double> == <double>.
  13402. static constexpr bool is_ieee_single_or_double
  13403. = (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
  13404. (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);
  13405. dump_float(x, std::integral_constant<bool, is_ieee_single_or_double>());
  13406. }
  13407. void dump_float(number_float_t x, std::true_type /*is_ieee_single_or_double*/)
  13408. {
  13409. char* begin = number_buffer.data();
  13410. char* end = ::nlohmann::detail::to_chars(begin, begin + number_buffer.size(), x);
  13411. o->write_characters(begin, static_cast<size_t>(end - begin));
  13412. }
  13413. void dump_float(number_float_t x, std::false_type /*is_ieee_single_or_double*/)
  13414. {
  13415. // get number of digits for a float -> text -> float round-trip
  13416. static constexpr auto d = std::numeric_limits<number_float_t>::max_digits10;
  13417. // the actual conversion
  13418. std::ptrdiff_t len = (std::snprintf)(number_buffer.data(), number_buffer.size(), "%.*g", d, x);
  13419. // negative value indicates an error
  13420. assert(len > 0);
  13421. // check if buffer was large enough
  13422. assert(static_cast<std::size_t>(len) < number_buffer.size());
  13423. // erase thousands separator
  13424. if (thousands_sep != '\0')
  13425. {
  13426. const auto end = std::remove(number_buffer.begin(),
  13427. number_buffer.begin() + len, thousands_sep);
  13428. std::fill(end, number_buffer.end(), '\0');
  13429. assert((end - number_buffer.begin()) <= len);
  13430. len = (end - number_buffer.begin());
  13431. }
  13432. // convert decimal point to '.'
  13433. if (decimal_point != '\0' and decimal_point != '.')
  13434. {
  13435. const auto dec_pos = std::find(number_buffer.begin(), number_buffer.end(), decimal_point);
  13436. if (dec_pos != number_buffer.end())
  13437. {
  13438. *dec_pos = '.';
  13439. }
  13440. }
  13441. o->write_characters(number_buffer.data(), static_cast<std::size_t>(len));
  13442. // determine if need to append ".0"
  13443. const bool value_is_int_like =
  13444. std::none_of(number_buffer.begin(), number_buffer.begin() + len + 1,
  13445. [](char c)
  13446. {
  13447. return c == '.' or c == 'e';
  13448. });
  13449. if (value_is_int_like)
  13450. {
  13451. o->write_characters(".0", 2);
  13452. }
  13453. }
  13454. /*!
  13455. @brief check whether a string is UTF-8 encoded
  13456. The function checks each byte of a string whether it is UTF-8 encoded. The
  13457. result of the check is stored in the @a state parameter. The function must
  13458. be called initially with state 0 (accept). State 1 means the string must
  13459. be rejected, because the current byte is not allowed. If the string is
  13460. completely processed, but the state is non-zero, the string ended
  13461. prematurely; that is, the last byte indicated more bytes should have
  13462. followed.
  13463. @param[in,out] state the state of the decoding
  13464. @param[in,out] codep codepoint (valid only if resulting state is UTF8_ACCEPT)
  13465. @param[in] byte next byte to decode
  13466. @return new state
  13467. @note The function has been edited: a std::array is used.
  13468. @copyright Copyright (c) 2008-2009 Bjoern Hoehrmann <bjoern@hoehrmann.de>
  13469. @sa http://bjoern.hoehrmann.de/utf-8/decoder/dfa/
  13470. */
  13471. static std::uint8_t decode(std::uint8_t& state, std::uint32_t& codep, const std::uint8_t byte) noexcept
  13472. {
  13473. static const std::array<std::uint8_t, 400> utf8d =
  13474. {
  13475. {
  13476. 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
  13477. 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
  13478. 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
  13479. 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
  13480. 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
  13481. 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
  13482. 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
  13483. 0xA, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x4, 0x3, 0x3, // E0..EF
  13484. 0xB, 0x6, 0x6, 0x6, 0x5, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, // F0..FF
  13485. 0x0, 0x1, 0x2, 0x3, 0x5, 0x8, 0x7, 0x1, 0x1, 0x1, 0x4, 0x6, 0x1, 0x1, 0x1, 0x1, // s0..s0
  13486. 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
  13487. 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
  13488. 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
  13489. 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
  13490. }
  13491. };
  13492. const std::uint8_t type = utf8d[byte];
  13493. codep = (state != UTF8_ACCEPT)
  13494. ? (byte & 0x3fu) | (codep << 6u)
  13495. : (0xFFu >> type) & (byte);
  13496. std::size_t index = 256u + static_cast<size_t>(state) * 16u + static_cast<size_t>(type);
  13497. assert(index < 400);
  13498. state = utf8d[index];
  13499. return state;
  13500. }
  13501. /*
  13502. * Overload to make the compiler happy while it is instantiating
  13503. * dump_integer for number_unsigned_t.
  13504. * Must never be called.
  13505. */
  13506. number_unsigned_t remove_sign(number_unsigned_t x)
  13507. {
  13508. assert(false); // LCOV_EXCL_LINE
  13509. return x; // LCOV_EXCL_LINE
  13510. }
  13511. /*
  13512. * Helper function for dump_integer
  13513. *
  13514. * This function takes a negative signed integer and returns its absolute
  13515. * value as unsigned integer. The plus/minus shuffling is necessary as we can
  13516. * not directly remove the sign of an arbitrary signed integer as the
  13517. * absolute values of INT_MIN and INT_MAX are usually not the same. See
  13518. * #1708 for details.
  13519. */
  13520. inline number_unsigned_t remove_sign(number_integer_t x) noexcept
  13521. {
  13522. assert(x < 0 and x < (std::numeric_limits<number_integer_t>::max)());
  13523. return static_cast<number_unsigned_t>(-(x + 1)) + 1;
  13524. }
  13525. private:
  13526. /// the output of the serializer
  13527. output_adapter_t<char> o = nullptr;
  13528. /// a (hopefully) large enough character buffer
  13529. std::array<char, 64> number_buffer{{}};
  13530. /// the locale
  13531. const std::lconv* loc = nullptr;
  13532. /// the locale's thousand separator character
  13533. const char thousands_sep = '\0';
  13534. /// the locale's decimal point character
  13535. const char decimal_point = '\0';
  13536. /// string buffer
  13537. std::array<char, 512> string_buffer{{}};
  13538. /// the indentation character
  13539. const char indent_char;
  13540. /// the indentation string
  13541. string_t indent_string;
  13542. /// error_handler how to react on decoding errors
  13543. const error_handler_t error_handler;
  13544. };
  13545. } // namespace detail
  13546. } // namespace nlohmann
  13547. // #include <nlohmann/detail/value_t.hpp>
  13548. // #include <nlohmann/json_fwd.hpp>
  13549. /*!
  13550. @brief namespace for Niels Lohmann
  13551. @see https://github.com/nlohmann
  13552. @since version 1.0.0
  13553. */
  13554. namespace nlohmann
  13555. {
  13556. /*!
  13557. @brief a class to store JSON values
  13558. @tparam ObjectType type for JSON objects (`std::map` by default; will be used
  13559. in @ref object_t)
  13560. @tparam ArrayType type for JSON arrays (`std::vector` by default; will be used
  13561. in @ref array_t)
  13562. @tparam StringType type for JSON strings and object keys (`std::string` by
  13563. default; will be used in @ref string_t)
  13564. @tparam BooleanType type for JSON booleans (`bool` by default; will be used
  13565. in @ref boolean_t)
  13566. @tparam NumberIntegerType type for JSON integer numbers (`int64_t` by
  13567. default; will be used in @ref number_integer_t)
  13568. @tparam NumberUnsignedType type for JSON unsigned integer numbers (@c
  13569. `uint64_t` by default; will be used in @ref number_unsigned_t)
  13570. @tparam NumberFloatType type for JSON floating-point numbers (`double` by
  13571. default; will be used in @ref number_float_t)
  13572. @tparam BinaryType type for packed binary data for compatibility with binary
  13573. serialization formats (`std::vector<std::uint8_t>` by default; will be used in
  13574. @ref binary_t)
  13575. @tparam AllocatorType type of the allocator to use (`std::allocator` by
  13576. default)
  13577. @tparam JSONSerializer the serializer to resolve internal calls to `to_json()`
  13578. and `from_json()` (@ref adl_serializer by default)
  13579. @requirement The class satisfies the following concept requirements:
  13580. - Basic
  13581. - [DefaultConstructible](https://en.cppreference.com/w/cpp/named_req/DefaultConstructible):
  13582. JSON values can be default constructed. The result will be a JSON null
  13583. value.
  13584. - [MoveConstructible](https://en.cppreference.com/w/cpp/named_req/MoveConstructible):
  13585. A JSON value can be constructed from an rvalue argument.
  13586. - [CopyConstructible](https://en.cppreference.com/w/cpp/named_req/CopyConstructible):
  13587. A JSON value can be copy-constructed from an lvalue expression.
  13588. - [MoveAssignable](https://en.cppreference.com/w/cpp/named_req/MoveAssignable):
  13589. A JSON value van be assigned from an rvalue argument.
  13590. - [CopyAssignable](https://en.cppreference.com/w/cpp/named_req/CopyAssignable):
  13591. A JSON value can be copy-assigned from an lvalue expression.
  13592. - [Destructible](https://en.cppreference.com/w/cpp/named_req/Destructible):
  13593. JSON values can be destructed.
  13594. - Layout
  13595. - [StandardLayoutType](https://en.cppreference.com/w/cpp/named_req/StandardLayoutType):
  13596. JSON values have
  13597. [standard layout](https://en.cppreference.com/w/cpp/language/data_members#Standard_layout):
  13598. All non-static data members are private and standard layout types, the
  13599. class has no virtual functions or (virtual) base classes.
  13600. - Library-wide
  13601. - [EqualityComparable](https://en.cppreference.com/w/cpp/named_req/EqualityComparable):
  13602. JSON values can be compared with `==`, see @ref
  13603. operator==(const_reference,const_reference).
  13604. - [LessThanComparable](https://en.cppreference.com/w/cpp/named_req/LessThanComparable):
  13605. JSON values can be compared with `<`, see @ref
  13606. operator<(const_reference,const_reference).
  13607. - [Swappable](https://en.cppreference.com/w/cpp/named_req/Swappable):
  13608. Any JSON lvalue or rvalue of can be swapped with any lvalue or rvalue of
  13609. other compatible types, using unqualified function call @ref swap().
  13610. - [NullablePointer](https://en.cppreference.com/w/cpp/named_req/NullablePointer):
  13611. JSON values can be compared against `std::nullptr_t` objects which are used
  13612. to model the `null` value.
  13613. - Container
  13614. - [Container](https://en.cppreference.com/w/cpp/named_req/Container):
  13615. JSON values can be used like STL containers and provide iterator access.
  13616. - [ReversibleContainer](https://en.cppreference.com/w/cpp/named_req/ReversibleContainer);
  13617. JSON values can be used like STL containers and provide reverse iterator
  13618. access.
  13619. @invariant The member variables @a m_value and @a m_type have the following
  13620. relationship:
  13621. - If `m_type == value_t::object`, then `m_value.object != nullptr`.
  13622. - If `m_type == value_t::array`, then `m_value.array != nullptr`.
  13623. - If `m_type == value_t::string`, then `m_value.string != nullptr`.
  13624. The invariants are checked by member function assert_invariant().
  13625. @internal
  13626. @note ObjectType trick from https://stackoverflow.com/a/9860911
  13627. @endinternal
  13628. @see [RFC 7159: The JavaScript Object Notation (JSON) Data Interchange
  13629. Format](http://rfc7159.net/rfc7159)
  13630. @since version 1.0.0
  13631. @nosubgrouping
  13632. */
  13633. NLOHMANN_BASIC_JSON_TPL_DECLARATION
  13634. class basic_json
  13635. {
  13636. private:
  13637. template<detail::value_t> friend struct detail::external_constructor;
  13638. friend ::nlohmann::json_pointer<basic_json>;
  13639. template<typename BasicJsonType, typename InputType>
  13640. friend class ::nlohmann::detail::parser;
  13641. friend ::nlohmann::detail::serializer<basic_json>;
  13642. template<typename BasicJsonType>
  13643. friend class ::nlohmann::detail::iter_impl;
  13644. template<typename BasicJsonType, typename CharType>
  13645. friend class ::nlohmann::detail::binary_writer;
  13646. template<typename BasicJsonType, typename InputType, typename SAX>
  13647. friend class ::nlohmann::detail::binary_reader;
  13648. template<typename BasicJsonType>
  13649. friend class ::nlohmann::detail::json_sax_dom_parser;
  13650. template<typename BasicJsonType>
  13651. friend class ::nlohmann::detail::json_sax_dom_callback_parser;
  13652. /// workaround type for MSVC
  13653. using basic_json_t = NLOHMANN_BASIC_JSON_TPL;
  13654. // convenience aliases for types residing in namespace detail;
  13655. using lexer = ::nlohmann::detail::lexer_base<basic_json>;
  13656. template<typename InputAdapterType>
  13657. static ::nlohmann::detail::parser<basic_json, InputAdapterType> parser(
  13658. InputAdapterType adapter,
  13659. detail::parser_callback_t<basic_json>cb = nullptr,
  13660. bool allow_exceptions = true
  13661. )
  13662. {
  13663. return ::nlohmann::detail::parser<basic_json, InputAdapterType>(std::move(adapter), std::move(cb), allow_exceptions);
  13664. }
  13665. using primitive_iterator_t = ::nlohmann::detail::primitive_iterator_t;
  13666. template<typename BasicJsonType>
  13667. using internal_iterator = ::nlohmann::detail::internal_iterator<BasicJsonType>;
  13668. template<typename BasicJsonType>
  13669. using iter_impl = ::nlohmann::detail::iter_impl<BasicJsonType>;
  13670. template<typename Iterator>
  13671. using iteration_proxy = ::nlohmann::detail::iteration_proxy<Iterator>;
  13672. template<typename Base> using json_reverse_iterator = ::nlohmann::detail::json_reverse_iterator<Base>;
  13673. template<typename CharType>
  13674. using output_adapter_t = ::nlohmann::detail::output_adapter_t<CharType>;
  13675. template<typename InputType>
  13676. using binary_reader = ::nlohmann::detail::binary_reader<basic_json, InputType>;
  13677. template<typename CharType> using binary_writer = ::nlohmann::detail::binary_writer<basic_json, CharType>;
  13678. using serializer = ::nlohmann::detail::serializer<basic_json>;
  13679. public:
  13680. using value_t = detail::value_t;
  13681. /// JSON Pointer, see @ref nlohmann::json_pointer
  13682. using json_pointer = ::nlohmann::json_pointer<basic_json>;
  13683. template<typename T, typename SFINAE>
  13684. using json_serializer = JSONSerializer<T, SFINAE>;
  13685. /// how to treat decoding errors
  13686. using error_handler_t = detail::error_handler_t;
  13687. /// helper type for initializer lists of basic_json values
  13688. using initializer_list_t = std::initializer_list<detail::json_ref<basic_json>>;
  13689. using input_format_t = detail::input_format_t;
  13690. /// SAX interface type, see @ref nlohmann::json_sax
  13691. using json_sax_t = json_sax<basic_json>;
  13692. ////////////////
  13693. // exceptions //
  13694. ////////////////
  13695. /// @name exceptions
  13696. /// Classes to implement user-defined exceptions.
  13697. /// @{
  13698. /// @copydoc detail::exception
  13699. using exception = detail::exception;
  13700. /// @copydoc detail::parse_error
  13701. using parse_error = detail::parse_error;
  13702. /// @copydoc detail::invalid_iterator
  13703. using invalid_iterator = detail::invalid_iterator;
  13704. /// @copydoc detail::type_error
  13705. using type_error = detail::type_error;
  13706. /// @copydoc detail::out_of_range
  13707. using out_of_range = detail::out_of_range;
  13708. /// @copydoc detail::other_error
  13709. using other_error = detail::other_error;
  13710. /// @}
  13711. /////////////////////
  13712. // container types //
  13713. /////////////////////
  13714. /// @name container types
  13715. /// The canonic container types to use @ref basic_json like any other STL
  13716. /// container.
  13717. /// @{
  13718. /// the type of elements in a basic_json container
  13719. using value_type = basic_json;
  13720. /// the type of an element reference
  13721. using reference = value_type&;
  13722. /// the type of an element const reference
  13723. using const_reference = const value_type&;
  13724. /// a type to represent differences between iterators
  13725. using difference_type = std::ptrdiff_t;
  13726. /// a type to represent container sizes
  13727. using size_type = std::size_t;
  13728. /// the allocator type
  13729. using allocator_type = AllocatorType<basic_json>;
  13730. /// the type of an element pointer
  13731. using pointer = typename std::allocator_traits<allocator_type>::pointer;
  13732. /// the type of an element const pointer
  13733. using const_pointer = typename std::allocator_traits<allocator_type>::const_pointer;
  13734. /// an iterator for a basic_json container
  13735. using iterator = iter_impl<basic_json>;
  13736. /// a const iterator for a basic_json container
  13737. using const_iterator = iter_impl<const basic_json>;
  13738. /// a reverse iterator for a basic_json container
  13739. using reverse_iterator = json_reverse_iterator<typename basic_json::iterator>;
  13740. /// a const reverse iterator for a basic_json container
  13741. using const_reverse_iterator = json_reverse_iterator<typename basic_json::const_iterator>;
  13742. /// @}
  13743. /*!
  13744. @brief returns the allocator associated with the container
  13745. */
  13746. static allocator_type get_allocator()
  13747. {
  13748. return allocator_type();
  13749. }
  13750. /*!
  13751. @brief returns version information on the library
  13752. This function returns a JSON object with information about the library,
  13753. including the version number and information on the platform and compiler.
  13754. @return JSON object holding version information
  13755. key | description
  13756. ----------- | ---------------
  13757. `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).
  13758. `copyright` | The copyright line for the library as string.
  13759. `name` | The name of the library as string.
  13760. `platform` | The used platform as string. Possible values are `win32`, `linux`, `apple`, `unix`, and `unknown`.
  13761. `url` | The URL of the project as string.
  13762. `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).
  13763. @liveexample{The following code shows an example output of the `meta()`
  13764. function.,meta}
  13765. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  13766. changes to any JSON value.
  13767. @complexity Constant.
  13768. @since 2.1.0
  13769. */
  13770. JSON_HEDLEY_WARN_UNUSED_RESULT
  13771. static basic_json meta()
  13772. {
  13773. basic_json result;
  13774. result["copyright"] = "(C) 2013-2017 Niels Lohmann";
  13775. result["name"] = "JSON for Modern C++";
  13776. result["url"] = "https://github.com/nlohmann/json";
  13777. result["version"]["string"] =
  13778. std::to_string(NLOHMANN_JSON_VERSION_MAJOR) + "." +
  13779. std::to_string(NLOHMANN_JSON_VERSION_MINOR) + "." +
  13780. std::to_string(NLOHMANN_JSON_VERSION_PATCH);
  13781. result["version"]["major"] = NLOHMANN_JSON_VERSION_MAJOR;
  13782. result["version"]["minor"] = NLOHMANN_JSON_VERSION_MINOR;
  13783. result["version"]["patch"] = NLOHMANN_JSON_VERSION_PATCH;
  13784. #ifdef _WIN32
  13785. result["platform"] = "win32";
  13786. #elif defined __linux__
  13787. result["platform"] = "linux";
  13788. #elif defined __APPLE__
  13789. result["platform"] = "apple";
  13790. #elif defined __unix__
  13791. result["platform"] = "unix";
  13792. #else
  13793. result["platform"] = "unknown";
  13794. #endif
  13795. #if defined(__ICC) || defined(__INTEL_COMPILER)
  13796. result["compiler"] = {{"family", "icc"}, {"version", __INTEL_COMPILER}};
  13797. #elif defined(__clang__)
  13798. result["compiler"] = {{"family", "clang"}, {"version", __clang_version__}};
  13799. #elif defined(__GNUC__) || defined(__GNUG__)
  13800. result["compiler"] = {{"family", "gcc"}, {"version", std::to_string(__GNUC__) + "." + std::to_string(__GNUC_MINOR__) + "." + std::to_string(__GNUC_PATCHLEVEL__)}};
  13801. #elif defined(__HP_cc) || defined(__HP_aCC)
  13802. result["compiler"] = "hp"
  13803. #elif defined(__IBMCPP__)
  13804. result["compiler"] = {{"family", "ilecpp"}, {"version", __IBMCPP__}};
  13805. #elif defined(_MSC_VER)
  13806. result["compiler"] = {{"family", "msvc"}, {"version", _MSC_VER}};
  13807. #elif defined(__PGI)
  13808. result["compiler"] = {{"family", "pgcpp"}, {"version", __PGI}};
  13809. #elif defined(__SUNPRO_CC)
  13810. result["compiler"] = {{"family", "sunpro"}, {"version", __SUNPRO_CC}};
  13811. #else
  13812. result["compiler"] = {{"family", "unknown"}, {"version", "unknown"}};
  13813. #endif
  13814. #ifdef __cplusplus
  13815. result["compiler"]["c++"] = std::to_string(__cplusplus);
  13816. #else
  13817. result["compiler"]["c++"] = "unknown";
  13818. #endif
  13819. return result;
  13820. }
  13821. ///////////////////////////
  13822. // JSON value data types //
  13823. ///////////////////////////
  13824. /// @name JSON value data types
  13825. /// The data types to store a JSON value. These types are derived from
  13826. /// the template arguments passed to class @ref basic_json.
  13827. /// @{
  13828. #if defined(JSON_HAS_CPP_14)
  13829. // Use transparent comparator if possible, combined with perfect forwarding
  13830. // on find() and count() calls prevents unnecessary string construction.
  13831. using object_comparator_t = std::less<>;
  13832. #else
  13833. using object_comparator_t = std::less<StringType>;
  13834. #endif
  13835. /*!
  13836. @brief a type for an object
  13837. [RFC 7159](http://rfc7159.net/rfc7159) describes JSON objects as follows:
  13838. > An object is an unordered collection of zero or more name/value pairs,
  13839. > where a name is a string and a value is a string, number, boolean, null,
  13840. > object, or array.
  13841. To store objects in C++, a type is defined by the template parameters
  13842. described below.
  13843. @tparam ObjectType the container to store objects (e.g., `std::map` or
  13844. `std::unordered_map`)
  13845. @tparam StringType the type of the keys or names (e.g., `std::string`).
  13846. The comparison function `std::less<StringType>` is used to order elements
  13847. inside the container.
  13848. @tparam AllocatorType the allocator to use for objects (e.g.,
  13849. `std::allocator`)
  13850. #### Default type
  13851. With the default values for @a ObjectType (`std::map`), @a StringType
  13852. (`std::string`), and @a AllocatorType (`std::allocator`), the default
  13853. value for @a object_t is:
  13854. @code {.cpp}
  13855. std::map<
  13856. std::string, // key_type
  13857. basic_json, // value_type
  13858. std::less<std::string>, // key_compare
  13859. std::allocator<std::pair<const std::string, basic_json>> // allocator_type
  13860. >
  13861. @endcode
  13862. #### Behavior
  13863. The choice of @a object_t influences the behavior of the JSON class. With
  13864. the default type, objects have the following behavior:
  13865. - When all names are unique, objects will be interoperable in the sense
  13866. that all software implementations receiving that object will agree on
  13867. the name-value mappings.
  13868. - When the names within an object are not unique, it is unspecified which
  13869. one of the values for a given key will be chosen. For instance,
  13870. `{"key": 2, "key": 1}` could be equal to either `{"key": 1}` or
  13871. `{"key": 2}`.
  13872. - Internally, name/value pairs are stored in lexicographical order of the
  13873. names. Objects will also be serialized (see @ref dump) in this order.
  13874. For instance, `{"b": 1, "a": 2}` and `{"a": 2, "b": 1}` will be stored
  13875. and serialized as `{"a": 2, "b": 1}`.
  13876. - When comparing objects, the order of the name/value pairs is irrelevant.
  13877. This makes objects interoperable in the sense that they will not be
  13878. affected by these differences. For instance, `{"b": 1, "a": 2}` and
  13879. `{"a": 2, "b": 1}` will be treated as equal.
  13880. #### Limits
  13881. [RFC 7159](http://rfc7159.net/rfc7159) specifies:
  13882. > An implementation may set limits on the maximum depth of nesting.
  13883. In this class, the object's limit of nesting is not explicitly constrained.
  13884. However, a maximum depth of nesting may be introduced by the compiler or
  13885. runtime environment. A theoretical limit can be queried by calling the
  13886. @ref max_size function of a JSON object.
  13887. #### Storage
  13888. Objects are stored as pointers in a @ref basic_json type. That is, for any
  13889. access to object values, a pointer of type `object_t*` must be
  13890. dereferenced.
  13891. @sa @ref array_t -- type for an array value
  13892. @since version 1.0.0
  13893. @note The order name/value pairs are added to the object is *not*
  13894. preserved by the library. Therefore, iterating an object may return
  13895. name/value pairs in a different order than they were originally stored. In
  13896. fact, keys will be traversed in alphabetical order as `std::map` with
  13897. `std::less` is used by default. Please note this behavior conforms to [RFC
  13898. 7159](http://rfc7159.net/rfc7159), because any order implements the
  13899. specified "unordered" nature of JSON objects.
  13900. */
  13901. using object_t = ObjectType<StringType,
  13902. basic_json,
  13903. object_comparator_t,
  13904. AllocatorType<std::pair<const StringType,
  13905. basic_json>>>;
  13906. /*!
  13907. @brief a type for an array
  13908. [RFC 7159](http://rfc7159.net/rfc7159) describes JSON arrays as follows:
  13909. > An array is an ordered sequence of zero or more values.
  13910. To store objects in C++, a type is defined by the template parameters
  13911. explained below.
  13912. @tparam ArrayType container type to store arrays (e.g., `std::vector` or
  13913. `std::list`)
  13914. @tparam AllocatorType allocator to use for arrays (e.g., `std::allocator`)
  13915. #### Default type
  13916. With the default values for @a ArrayType (`std::vector`) and @a
  13917. AllocatorType (`std::allocator`), the default value for @a array_t is:
  13918. @code {.cpp}
  13919. std::vector<
  13920. basic_json, // value_type
  13921. std::allocator<basic_json> // allocator_type
  13922. >
  13923. @endcode
  13924. #### Limits
  13925. [RFC 7159](http://rfc7159.net/rfc7159) specifies:
  13926. > An implementation may set limits on the maximum depth of nesting.
  13927. In this class, the array's limit of nesting is not explicitly constrained.
  13928. However, a maximum depth of nesting may be introduced by the compiler or
  13929. runtime environment. A theoretical limit can be queried by calling the
  13930. @ref max_size function of a JSON array.
  13931. #### Storage
  13932. Arrays are stored as pointers in a @ref basic_json type. That is, for any
  13933. access to array values, a pointer of type `array_t*` must be dereferenced.
  13934. @sa @ref object_t -- type for an object value
  13935. @since version 1.0.0
  13936. */
  13937. using array_t = ArrayType<basic_json, AllocatorType<basic_json>>;
  13938. /*!
  13939. @brief a type for a string
  13940. [RFC 7159](http://rfc7159.net/rfc7159) describes JSON strings as follows:
  13941. > A string is a sequence of zero or more Unicode characters.
  13942. To store objects in C++, a type is defined by the template parameter
  13943. described below. Unicode values are split by the JSON class into
  13944. byte-sized characters during deserialization.
  13945. @tparam StringType the container to store strings (e.g., `std::string`).
  13946. Note this container is used for keys/names in objects, see @ref object_t.
  13947. #### Default type
  13948. With the default values for @a StringType (`std::string`), the default
  13949. value for @a string_t is:
  13950. @code {.cpp}
  13951. std::string
  13952. @endcode
  13953. #### Encoding
  13954. Strings are stored in UTF-8 encoding. Therefore, functions like
  13955. `std::string::size()` or `std::string::length()` return the number of
  13956. bytes in the string rather than the number of characters or glyphs.
  13957. #### String comparison
  13958. [RFC 7159](http://rfc7159.net/rfc7159) states:
  13959. > Software implementations are typically required to test names of object
  13960. > members for equality. Implementations that transform the textual
  13961. > representation into sequences of Unicode code units and then perform the
  13962. > comparison numerically, code unit by code unit, are interoperable in the
  13963. > sense that implementations will agree in all cases on equality or
  13964. > inequality of two strings. For example, implementations that compare
  13965. > strings with escaped characters unconverted may incorrectly find that
  13966. > `"a\\b"` and `"a\u005Cb"` are not equal.
  13967. This implementation is interoperable as it does compare strings code unit
  13968. by code unit.
  13969. #### Storage
  13970. String values are stored as pointers in a @ref basic_json type. That is,
  13971. for any access to string values, a pointer of type `string_t*` must be
  13972. dereferenced.
  13973. @since version 1.0.0
  13974. */
  13975. using string_t = StringType;
  13976. /*!
  13977. @brief a type for a boolean
  13978. [RFC 7159](http://rfc7159.net/rfc7159) implicitly describes a boolean as a
  13979. type which differentiates the two literals `true` and `false`.
  13980. To store objects in C++, a type is defined by the template parameter @a
  13981. BooleanType which chooses the type to use.
  13982. #### Default type
  13983. With the default values for @a BooleanType (`bool`), the default value for
  13984. @a boolean_t is:
  13985. @code {.cpp}
  13986. bool
  13987. @endcode
  13988. #### Storage
  13989. Boolean values are stored directly inside a @ref basic_json type.
  13990. @since version 1.0.0
  13991. */
  13992. using boolean_t = BooleanType;
  13993. /*!
  13994. @brief a type for a number (integer)
  13995. [RFC 7159](http://rfc7159.net/rfc7159) describes numbers as follows:
  13996. > The representation of numbers is similar to that used in most
  13997. > programming languages. A number is represented in base 10 using decimal
  13998. > digits. It contains an integer component that may be prefixed with an
  13999. > optional minus sign, which may be followed by a fraction part and/or an
  14000. > exponent part. Leading zeros are not allowed. (...) Numeric values that
  14001. > cannot be represented in the grammar below (such as Infinity and NaN)
  14002. > are not permitted.
  14003. This description includes both integer and floating-point numbers.
  14004. However, C++ allows more precise storage if it is known whether the number
  14005. is a signed integer, an unsigned integer or a floating-point number.
  14006. Therefore, three different types, @ref number_integer_t, @ref
  14007. number_unsigned_t and @ref number_float_t are used.
  14008. To store integer numbers in C++, a type is defined by the template
  14009. parameter @a NumberIntegerType which chooses the type to use.
  14010. #### Default type
  14011. With the default values for @a NumberIntegerType (`int64_t`), the default
  14012. value for @a number_integer_t is:
  14013. @code {.cpp}
  14014. int64_t
  14015. @endcode
  14016. #### Default behavior
  14017. - The restrictions about leading zeros is not enforced in C++. Instead,
  14018. leading zeros in integer literals lead to an interpretation as octal
  14019. number. Internally, the value will be stored as decimal number. For
  14020. instance, the C++ integer literal `010` will be serialized to `8`.
  14021. During deserialization, leading zeros yield an error.
  14022. - Not-a-number (NaN) values will be serialized to `null`.
  14023. #### Limits
  14024. [RFC 7159](http://rfc7159.net/rfc7159) specifies:
  14025. > An implementation may set limits on the range and precision of numbers.
  14026. When the default type is used, the maximal integer number that can be
  14027. stored is `9223372036854775807` (INT64_MAX) and the minimal integer number
  14028. that can be stored is `-9223372036854775808` (INT64_MIN). Integer numbers
  14029. that are out of range will yield over/underflow when used in a
  14030. constructor. During deserialization, too large or small integer numbers
  14031. will be automatically be stored as @ref number_unsigned_t or @ref
  14032. number_float_t.
  14033. [RFC 7159](http://rfc7159.net/rfc7159) further states:
  14034. > Note that when such software is used, numbers that are integers and are
  14035. > in the range \f$[-2^{53}+1, 2^{53}-1]\f$ are interoperable in the sense
  14036. > that implementations will agree exactly on their numeric values.
  14037. As this range is a subrange of the exactly supported range [INT64_MIN,
  14038. INT64_MAX], this class's integer type is interoperable.
  14039. #### Storage
  14040. Integer number values are stored directly inside a @ref basic_json type.
  14041. @sa @ref number_float_t -- type for number values (floating-point)
  14042. @sa @ref number_unsigned_t -- type for number values (unsigned integer)
  14043. @since version 1.0.0
  14044. */
  14045. using number_integer_t = NumberIntegerType;
  14046. /*!
  14047. @brief a type for a number (unsigned)
  14048. [RFC 7159](http://rfc7159.net/rfc7159) describes numbers as follows:
  14049. > The representation of numbers is similar to that used in most
  14050. > programming languages. A number is represented in base 10 using decimal
  14051. > digits. It contains an integer component that may be prefixed with an
  14052. > optional minus sign, which may be followed by a fraction part and/or an
  14053. > exponent part. Leading zeros are not allowed. (...) Numeric values that
  14054. > cannot be represented in the grammar below (such as Infinity and NaN)
  14055. > are not permitted.
  14056. This description includes both integer and floating-point numbers.
  14057. However, C++ allows more precise storage if it is known whether the number
  14058. is a signed integer, an unsigned integer or a floating-point number.
  14059. Therefore, three different types, @ref number_integer_t, @ref
  14060. number_unsigned_t and @ref number_float_t are used.
  14061. To store unsigned integer numbers in C++, a type is defined by the
  14062. template parameter @a NumberUnsignedType which chooses the type to use.
  14063. #### Default type
  14064. With the default values for @a NumberUnsignedType (`uint64_t`), the
  14065. default value for @a number_unsigned_t is:
  14066. @code {.cpp}
  14067. uint64_t
  14068. @endcode
  14069. #### Default behavior
  14070. - The restrictions about leading zeros is not enforced in C++. Instead,
  14071. leading zeros in integer literals lead to an interpretation as octal
  14072. number. Internally, the value will be stored as decimal number. For
  14073. instance, the C++ integer literal `010` will be serialized to `8`.
  14074. During deserialization, leading zeros yield an error.
  14075. - Not-a-number (NaN) values will be serialized to `null`.
  14076. #### Limits
  14077. [RFC 7159](http://rfc7159.net/rfc7159) specifies:
  14078. > An implementation may set limits on the range and precision of numbers.
  14079. When the default type is used, the maximal integer number that can be
  14080. stored is `18446744073709551615` (UINT64_MAX) and the minimal integer
  14081. number that can be stored is `0`. Integer numbers that are out of range
  14082. will yield over/underflow when used in a constructor. During
  14083. deserialization, too large or small integer numbers will be automatically
  14084. be stored as @ref number_integer_t or @ref number_float_t.
  14085. [RFC 7159](http://rfc7159.net/rfc7159) further states:
  14086. > Note that when such software is used, numbers that are integers and are
  14087. > in the range \f$[-2^{53}+1, 2^{53}-1]\f$ are interoperable in the sense
  14088. > that implementations will agree exactly on their numeric values.
  14089. As this range is a subrange (when considered in conjunction with the
  14090. number_integer_t type) of the exactly supported range [0, UINT64_MAX],
  14091. this class's integer type is interoperable.
  14092. #### Storage
  14093. Integer number values are stored directly inside a @ref basic_json type.
  14094. @sa @ref number_float_t -- type for number values (floating-point)
  14095. @sa @ref number_integer_t -- type for number values (integer)
  14096. @since version 2.0.0
  14097. */
  14098. using number_unsigned_t = NumberUnsignedType;
  14099. /*!
  14100. @brief a type for a number (floating-point)
  14101. [RFC 7159](http://rfc7159.net/rfc7159) describes numbers as follows:
  14102. > The representation of numbers is similar to that used in most
  14103. > programming languages. A number is represented in base 10 using decimal
  14104. > digits. It contains an integer component that may be prefixed with an
  14105. > optional minus sign, which may be followed by a fraction part and/or an
  14106. > exponent part. Leading zeros are not allowed. (...) Numeric values that
  14107. > cannot be represented in the grammar below (such as Infinity and NaN)
  14108. > are not permitted.
  14109. This description includes both integer and floating-point numbers.
  14110. However, C++ allows more precise storage if it is known whether the number
  14111. is a signed integer, an unsigned integer or a floating-point number.
  14112. Therefore, three different types, @ref number_integer_t, @ref
  14113. number_unsigned_t and @ref number_float_t are used.
  14114. To store floating-point numbers in C++, a type is defined by the template
  14115. parameter @a NumberFloatType which chooses the type to use.
  14116. #### Default type
  14117. With the default values for @a NumberFloatType (`double`), the default
  14118. value for @a number_float_t is:
  14119. @code {.cpp}
  14120. double
  14121. @endcode
  14122. #### Default behavior
  14123. - The restrictions about leading zeros is not enforced in C++. Instead,
  14124. leading zeros in floating-point literals will be ignored. Internally,
  14125. the value will be stored as decimal number. For instance, the C++
  14126. floating-point literal `01.2` will be serialized to `1.2`. During
  14127. deserialization, leading zeros yield an error.
  14128. - Not-a-number (NaN) values will be serialized to `null`.
  14129. #### Limits
  14130. [RFC 7159](http://rfc7159.net/rfc7159) states:
  14131. > This specification allows implementations to set limits on the range and
  14132. > precision of numbers accepted. Since software that implements IEEE
  14133. > 754-2008 binary64 (double precision) numbers is generally available and
  14134. > widely used, good interoperability can be achieved by implementations
  14135. > that expect no more precision or range than these provide, in the sense
  14136. > that implementations will approximate JSON numbers within the expected
  14137. > precision.
  14138. This implementation does exactly follow this approach, as it uses double
  14139. precision floating-point numbers. Note values smaller than
  14140. `-1.79769313486232e+308` and values greater than `1.79769313486232e+308`
  14141. will be stored as NaN internally and be serialized to `null`.
  14142. #### Storage
  14143. Floating-point number values are stored directly inside a @ref basic_json
  14144. type.
  14145. @sa @ref number_integer_t -- type for number values (integer)
  14146. @sa @ref number_unsigned_t -- type for number values (unsigned integer)
  14147. @since version 1.0.0
  14148. */
  14149. using number_float_t = NumberFloatType;
  14150. /*!
  14151. @brief a type for a packed binary type
  14152. This type is a type designed to carry binary data that appears in various
  14153. serialized formats, such as CBOR's Major Type 2, MessagePack's bin, and
  14154. BSON's generic binary subtype. This type is NOT a part of standard JSON and
  14155. exists solely for compatibility with these binary types. As such, it is
  14156. simply defined as an ordered sequence of zero or more byte values.
  14157. Additionally, as an implementation detail, the subtype of the binary data is
  14158. carried around as a `unint8_t`, which is compatible with both of the binary
  14159. data formats that use binary subtyping, (though the specific numbering is
  14160. incompatible with each other, and it is up to the user to translate between
  14161. them).
  14162. [CBOR's RFC 7049](https://tools.ietf.org/html/rfc7049) describes this type
  14163. as:
  14164. > Major type 2: a byte string. The string's length in bytes is
  14165. > represented following the rules for positive integers (major type
  14166. > 0).
  14167. [MessagePack's documentation on the bin type
  14168. family](https://github.com/msgpack/msgpack/blob/master/spec.md#bin-format-family)
  14169. describes this type as:
  14170. > Bin format family stores an byte array in 2, 3, or 5 bytes of extra bytes
  14171. > in addition to the size of the byte array.
  14172. [BSON's specifications](http://bsonspec.org/spec.html) describe several
  14173. binary types; however, this type is intended to represent the generic binary
  14174. type which has the description:
  14175. > Generic binary subtype - This is the most commonly used binary subtype and
  14176. > should be the 'default' for drivers and tools.
  14177. None of these impose any limitations on the internal representation other
  14178. than the basic unit of storage be some type of array whose parts are
  14179. decomposible into bytes.
  14180. The default representation of this binary format is a
  14181. `std::vector<std::uint8_t>`, which is a very common way to represent a byte
  14182. array in modern C++.
  14183. #### Default type
  14184. The default values for @a BinaryType is `std::vector<std::uint8_t>`
  14185. #### Storage
  14186. Binary Arrays are stored as pointers in a @ref basic_json type. That is,
  14187. for any access to array values, a pointer of the type `binary_t*` must be
  14188. dereferenced.
  14189. @sa @ref array_t -- type for an array value
  14190. @since version 3.8.0
  14191. */
  14192. using binary_t = BinaryType;
  14193. /*!
  14194. @brief an internal type for a backed binary type
  14195. This type is designed to be `binary_t` but with the subtype implementation
  14196. detail. This type exists so that the user does not have to specify a struct
  14197. his- or herself with a specific naming scheme in order to override the
  14198. binary type. I.e. it's for ease of use.
  14199. */
  14200. struct internal_binary_t : public BinaryType
  14201. {
  14202. using BinaryType::BinaryType;
  14203. internal_binary_t() noexcept(noexcept(BinaryType()))
  14204. : BinaryType()
  14205. {}
  14206. internal_binary_t(const BinaryType& bint) noexcept(noexcept(BinaryType(bint)))
  14207. : BinaryType(bint)
  14208. {}
  14209. internal_binary_t(BinaryType&& bint) noexcept(noexcept(BinaryType(std::move(bint))))
  14210. : BinaryType(std::move(bint))
  14211. {}
  14212. internal_binary_t(const BinaryType& bint, std::uint8_t st) noexcept(noexcept(BinaryType(bint)))
  14213. : BinaryType(bint)
  14214. , subtype(st)
  14215. , has_subtype(true)
  14216. {}
  14217. internal_binary_t(BinaryType&& bint, std::uint8_t st) noexcept(noexcept(BinaryType(std::move(bint))))
  14218. : BinaryType(std::move(bint))
  14219. , subtype(st)
  14220. , has_subtype(true)
  14221. {}
  14222. // TOOD: If minimum C++ version is ever bumped to C++17, this field
  14223. // deserves to be a std::optional
  14224. std::uint8_t subtype = 0;
  14225. bool has_subtype = false;
  14226. };
  14227. /// @}
  14228. private:
  14229. /// helper for exception-safe object creation
  14230. template<typename T, typename... Args>
  14231. JSON_HEDLEY_RETURNS_NON_NULL
  14232. static T* create(Args&& ... args)
  14233. {
  14234. AllocatorType<T> alloc;
  14235. using AllocatorTraits = std::allocator_traits<AllocatorType<T>>;
  14236. auto deleter = [&](T * object)
  14237. {
  14238. AllocatorTraits::deallocate(alloc, object, 1);
  14239. };
  14240. std::unique_ptr<T, decltype(deleter)> object(AllocatorTraits::allocate(alloc, 1), deleter);
  14241. AllocatorTraits::construct(alloc, object.get(), std::forward<Args>(args)...);
  14242. assert(object != nullptr);
  14243. return object.release();
  14244. }
  14245. ////////////////////////
  14246. // JSON value storage //
  14247. ////////////////////////
  14248. /*!
  14249. @brief a JSON value
  14250. The actual storage for a JSON value of the @ref basic_json class. This
  14251. union combines the different storage types for the JSON value types
  14252. defined in @ref value_t.
  14253. JSON type | value_t type | used type
  14254. --------- | --------------- | ------------------------
  14255. object | object | pointer to @ref object_t
  14256. array | array | pointer to @ref array_t
  14257. string | string | pointer to @ref string_t
  14258. boolean | boolean | @ref boolean_t
  14259. number | number_integer | @ref number_integer_t
  14260. number | number_unsigned | @ref number_unsigned_t
  14261. number | number_float | @ref number_float_t
  14262. binary | binary | pointer to @ref internal_binary_t
  14263. null | null | *no value is stored*
  14264. @note Variable-length types (objects, arrays, and strings) are stored as
  14265. pointers. The size of the union should not exceed 64 bits if the default
  14266. value types are used.
  14267. @since version 1.0.0
  14268. */
  14269. union json_value
  14270. {
  14271. /// object (stored with pointer to save storage)
  14272. object_t* object;
  14273. /// array (stored with pointer to save storage)
  14274. array_t* array;
  14275. /// string (stored with pointer to save storage)
  14276. string_t* string;
  14277. /// binary (stored with pointer to save storage)
  14278. internal_binary_t* binary;
  14279. /// boolean
  14280. boolean_t boolean;
  14281. /// number (integer)
  14282. number_integer_t number_integer;
  14283. /// number (unsigned integer)
  14284. number_unsigned_t number_unsigned;
  14285. /// number (floating-point)
  14286. number_float_t number_float;
  14287. /// default constructor (for null values)
  14288. json_value() = default;
  14289. /// constructor for booleans
  14290. json_value(boolean_t v) noexcept : boolean(v) {}
  14291. /// constructor for numbers (integer)
  14292. json_value(number_integer_t v) noexcept : number_integer(v) {}
  14293. /// constructor for numbers (unsigned)
  14294. json_value(number_unsigned_t v) noexcept : number_unsigned(v) {}
  14295. /// constructor for numbers (floating-point)
  14296. json_value(number_float_t v) noexcept : number_float(v) {}
  14297. /// constructor for empty values of a given type
  14298. json_value(value_t t)
  14299. {
  14300. switch (t)
  14301. {
  14302. case value_t::object:
  14303. {
  14304. object = create<object_t>();
  14305. break;
  14306. }
  14307. case value_t::array:
  14308. {
  14309. array = create<array_t>();
  14310. break;
  14311. }
  14312. case value_t::string:
  14313. {
  14314. string = create<string_t>("");
  14315. break;
  14316. }
  14317. case value_t::binary:
  14318. {
  14319. binary = create<internal_binary_t>();
  14320. break;
  14321. }
  14322. case value_t::boolean:
  14323. {
  14324. boolean = boolean_t(false);
  14325. break;
  14326. }
  14327. case value_t::number_integer:
  14328. {
  14329. number_integer = number_integer_t(0);
  14330. break;
  14331. }
  14332. case value_t::number_unsigned:
  14333. {
  14334. number_unsigned = number_unsigned_t(0);
  14335. break;
  14336. }
  14337. case value_t::number_float:
  14338. {
  14339. number_float = number_float_t(0.0);
  14340. break;
  14341. }
  14342. case value_t::null:
  14343. {
  14344. object = nullptr; // silence warning, see #821
  14345. break;
  14346. }
  14347. default:
  14348. {
  14349. object = nullptr; // silence warning, see #821
  14350. if (JSON_HEDLEY_UNLIKELY(t == value_t::null))
  14351. {
  14352. JSON_THROW(other_error::create(500, "961c151d2e87f2686a955a9be24d316f1362bf21 3.7.3")); // LCOV_EXCL_LINE
  14353. }
  14354. break;
  14355. }
  14356. }
  14357. }
  14358. /// constructor for strings
  14359. json_value(const string_t& value)
  14360. {
  14361. string = create<string_t>(value);
  14362. }
  14363. /// constructor for rvalue strings
  14364. json_value(string_t&& value)
  14365. {
  14366. string = create<string_t>(std::move(value));
  14367. }
  14368. /// constructor for objects
  14369. json_value(const object_t& value)
  14370. {
  14371. object = create<object_t>(value);
  14372. }
  14373. /// constructor for rvalue objects
  14374. json_value(object_t&& value)
  14375. {
  14376. object = create<object_t>(std::move(value));
  14377. }
  14378. /// constructor for arrays
  14379. json_value(const array_t& value)
  14380. {
  14381. array = create<array_t>(value);
  14382. }
  14383. /// constructor for rvalue arrays
  14384. json_value(array_t&& value)
  14385. {
  14386. array = create<array_t>(std::move(value));
  14387. }
  14388. /// constructor for binary arrays
  14389. json_value(const binary_t& value)
  14390. {
  14391. binary = create<internal_binary_t>(value);
  14392. }
  14393. /// constructor for rvalue binary arrays
  14394. json_value(binary_t&& value)
  14395. {
  14396. binary = create<internal_binary_t>(std::move(value));
  14397. }
  14398. /// constructor for binary arrays (internal type)
  14399. json_value(const internal_binary_t& value)
  14400. {
  14401. binary = create<internal_binary_t>(value);
  14402. }
  14403. /// constructor for rvalue binary arrays (internal type)
  14404. json_value(internal_binary_t&& value)
  14405. {
  14406. binary = create<internal_binary_t>(std::move(value));
  14407. }
  14408. void destroy(value_t t) noexcept
  14409. {
  14410. // flatten the current json_value to a heap-allocated stack
  14411. std::vector<basic_json> stack;
  14412. // move the top-level items to stack
  14413. if (t == value_t::array)
  14414. {
  14415. stack.reserve(array->size());
  14416. std::move(array->begin(), array->end(), std::back_inserter(stack));
  14417. }
  14418. else if (t == value_t::object)
  14419. {
  14420. stack.reserve(object->size());
  14421. for (auto&& it : *object)
  14422. {
  14423. stack.push_back(std::move(it.second));
  14424. }
  14425. }
  14426. while (not stack.empty())
  14427. {
  14428. // move the last item to local variable to be processed
  14429. basic_json current_item(std::move(stack.back()));
  14430. stack.pop_back();
  14431. // if current_item is array/object, move
  14432. // its children to the stack to be processed later
  14433. if (current_item.is_array())
  14434. {
  14435. std::move(current_item.m_value.array->begin(), current_item.m_value.array->end(),
  14436. std::back_inserter(stack));
  14437. current_item.m_value.array->clear();
  14438. }
  14439. else if (current_item.is_object())
  14440. {
  14441. for (auto&& it : *current_item.m_value.object)
  14442. {
  14443. stack.push_back(std::move(it.second));
  14444. }
  14445. current_item.m_value.object->clear();
  14446. }
  14447. // it's now safe that current_item get destructed
  14448. // since it doesn't have any children
  14449. }
  14450. switch (t)
  14451. {
  14452. case value_t::object:
  14453. {
  14454. AllocatorType<object_t> alloc;
  14455. std::allocator_traits<decltype(alloc)>::destroy(alloc, object);
  14456. std::allocator_traits<decltype(alloc)>::deallocate(alloc, object, 1);
  14457. break;
  14458. }
  14459. case value_t::array:
  14460. {
  14461. AllocatorType<array_t> alloc;
  14462. std::allocator_traits<decltype(alloc)>::destroy(alloc, array);
  14463. std::allocator_traits<decltype(alloc)>::deallocate(alloc, array, 1);
  14464. break;
  14465. }
  14466. case value_t::string:
  14467. {
  14468. AllocatorType<string_t> alloc;
  14469. std::allocator_traits<decltype(alloc)>::destroy(alloc, string);
  14470. std::allocator_traits<decltype(alloc)>::deallocate(alloc, string, 1);
  14471. break;
  14472. }
  14473. case value_t::binary:
  14474. {
  14475. AllocatorType<internal_binary_t> alloc;
  14476. std::allocator_traits<decltype(alloc)>::destroy(alloc, binary);
  14477. std::allocator_traits<decltype(alloc)>::deallocate(alloc, binary, 1);
  14478. break;
  14479. }
  14480. default:
  14481. {
  14482. break;
  14483. }
  14484. }
  14485. }
  14486. };
  14487. /*!
  14488. @brief checks the class invariants
  14489. This function asserts the class invariants. It needs to be called at the
  14490. end of every constructor to make sure that created objects respect the
  14491. invariant. Furthermore, it has to be called each time the type of a JSON
  14492. value is changed, because the invariant expresses a relationship between
  14493. @a m_type and @a m_value.
  14494. */
  14495. void assert_invariant() const noexcept
  14496. {
  14497. assert(m_type != value_t::object or m_value.object != nullptr);
  14498. assert(m_type != value_t::array or m_value.array != nullptr);
  14499. assert(m_type != value_t::string or m_value.string != nullptr);
  14500. assert(m_type != value_t::binary or m_value.binary != nullptr);
  14501. }
  14502. public:
  14503. //////////////////////////
  14504. // JSON parser callback //
  14505. //////////////////////////
  14506. /*!
  14507. @brief parser event types
  14508. The parser callback distinguishes the following events:
  14509. - `object_start`: the parser read `{` and started to process a JSON object
  14510. - `key`: the parser read a key of a value in an object
  14511. - `object_end`: the parser read `}` and finished processing a JSON object
  14512. - `array_start`: the parser read `[` and started to process a JSON array
  14513. - `array_end`: the parser read `]` and finished processing a JSON array
  14514. - `value`: the parser finished reading a JSON value
  14515. @image html callback_events.png "Example when certain parse events are triggered"
  14516. @sa @ref parser_callback_t for more information and examples
  14517. */
  14518. using parse_event_t = detail::parse_event_t;
  14519. /*!
  14520. @brief per-element parser callback type
  14521. With a parser callback function, the result of parsing a JSON text can be
  14522. influenced. When passed to @ref parse, it is called on certain events
  14523. (passed as @ref parse_event_t via parameter @a event) with a set recursion
  14524. depth @a depth and context JSON value @a parsed. The return value of the
  14525. callback function is a boolean indicating whether the element that emitted
  14526. the callback shall be kept or not.
  14527. We distinguish six scenarios (determined by the event type) in which the
  14528. callback function can be called. The following table describes the values
  14529. of the parameters @a depth, @a event, and @a parsed.
  14530. parameter @a event | description | parameter @a depth | parameter @a parsed
  14531. ------------------ | ----------- | ------------------ | -------------------
  14532. 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
  14533. 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
  14534. 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
  14535. 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
  14536. 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
  14537. parse_event_t::value | the parser finished reading a JSON value | depth of the value | the parsed JSON value
  14538. @image html callback_events.png "Example when certain parse events are triggered"
  14539. Discarding a value (i.e., returning `false`) has different effects
  14540. depending on the context in which function was called:
  14541. - Discarded values in structured types are skipped. That is, the parser
  14542. will behave as if the discarded value was never read.
  14543. - In case a value outside a structured type is skipped, it is replaced
  14544. with `null`. This case happens if the top-level element is skipped.
  14545. @param[in] depth the depth of the recursion during parsing
  14546. @param[in] event an event of type parse_event_t indicating the context in
  14547. the callback function has been called
  14548. @param[in,out] parsed the current intermediate parse result; note that
  14549. writing to this value has no effect for parse_event_t::key events
  14550. @return Whether the JSON value which called the function during parsing
  14551. should be kept (`true`) or not (`false`). In the latter case, it is either
  14552. skipped completely or replaced by an empty discarded object.
  14553. @sa @ref parse for examples
  14554. @since version 1.0.0
  14555. */
  14556. using parser_callback_t = detail::parser_callback_t<basic_json>;
  14557. //////////////////
  14558. // constructors //
  14559. //////////////////
  14560. /// @name constructors and destructors
  14561. /// Constructors of class @ref basic_json, copy/move constructor, copy
  14562. /// assignment, static functions creating objects, and the destructor.
  14563. /// @{
  14564. /*!
  14565. @brief create an empty value with a given type
  14566. Create an empty JSON value with a given type. The value will be default
  14567. initialized with an empty value which depends on the type:
  14568. Value type | initial value
  14569. ----------- | -------------
  14570. null | `null`
  14571. boolean | `false`
  14572. string | `""`
  14573. number | `0`
  14574. object | `{}`
  14575. array | `[]`
  14576. binary | empty array
  14577. @param[in] v the type of the value to create
  14578. @complexity Constant.
  14579. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  14580. changes to any JSON value.
  14581. @liveexample{The following code shows the constructor for different @ref
  14582. value_t values,basic_json__value_t}
  14583. @sa @ref clear() -- restores the postcondition of this constructor
  14584. @since version 1.0.0
  14585. */
  14586. basic_json(const value_t v)
  14587. : m_type(v), m_value(v)
  14588. {
  14589. assert_invariant();
  14590. }
  14591. /*!
  14592. @brief create a null object
  14593. Create a `null` JSON value. It either takes a null pointer as parameter
  14594. (explicitly creating `null`) or no parameter (implicitly creating `null`).
  14595. The passed null pointer itself is not read -- it is only used to choose
  14596. the right constructor.
  14597. @complexity Constant.
  14598. @exceptionsafety No-throw guarantee: this constructor never throws
  14599. exceptions.
  14600. @liveexample{The following code shows the constructor with and without a
  14601. null pointer parameter.,basic_json__nullptr_t}
  14602. @since version 1.0.0
  14603. */
  14604. basic_json(std::nullptr_t = nullptr) noexcept
  14605. : basic_json(value_t::null)
  14606. {
  14607. assert_invariant();
  14608. }
  14609. /*!
  14610. @brief create a JSON value
  14611. This is a "catch all" constructor for all compatible JSON types; that is,
  14612. types for which a `to_json()` method exists. The constructor forwards the
  14613. parameter @a val to that method (to `json_serializer<U>::to_json` method
  14614. with `U = uncvref_t<CompatibleType>`, to be exact).
  14615. Template type @a CompatibleType includes, but is not limited to, the
  14616. following types:
  14617. - **arrays**: @ref array_t and all kinds of compatible containers such as
  14618. `std::vector`, `std::deque`, `std::list`, `std::forward_list`,
  14619. `std::array`, `std::valarray`, `std::set`, `std::unordered_set`,
  14620. `std::multiset`, and `std::unordered_multiset` with a `value_type` from
  14621. which a @ref basic_json value can be constructed.
  14622. - **objects**: @ref object_t and all kinds of compatible associative
  14623. containers such as `std::map`, `std::unordered_map`, `std::multimap`,
  14624. and `std::unordered_multimap` with a `key_type` compatible to
  14625. @ref string_t and a `value_type` from which a @ref basic_json value can
  14626. be constructed.
  14627. - **strings**: @ref string_t, string literals, and all compatible string
  14628. containers can be used.
  14629. - **numbers**: @ref number_integer_t, @ref number_unsigned_t,
  14630. @ref number_float_t, and all convertible number types such as `int`,
  14631. `size_t`, `int64_t`, `float` or `double` can be used.
  14632. - **boolean**: @ref boolean_t / `bool` can be used.
  14633. - **binary**: @ref binary_t / `std::vector<uint8_t>` may be used,
  14634. unfortunately because string literals cannot be distinguished from binary
  14635. character arrays by the C++ type system, all types compatible with `const
  14636. char*` will be directed to the string constructor instead. This is both
  14637. for backwards compatibility, and due to the fact that a binary type is not
  14638. a standard JSON type.
  14639. See the examples below.
  14640. @tparam CompatibleType a type such that:
  14641. - @a CompatibleType is not derived from `std::istream`,
  14642. - @a CompatibleType is not @ref basic_json (to avoid hijacking copy/move
  14643. constructors),
  14644. - @a CompatibleType is not a different @ref basic_json type (i.e. with different template arguments)
  14645. - @a CompatibleType is not a @ref basic_json nested type (e.g.,
  14646. @ref json_pointer, @ref iterator, etc ...)
  14647. - @ref @ref json_serializer<U> has a
  14648. `to_json(basic_json_t&, CompatibleType&&)` method
  14649. @tparam U = `uncvref_t<CompatibleType>`
  14650. @param[in] val the value to be forwarded to the respective constructor
  14651. @complexity Usually linear in the size of the passed @a val, also
  14652. depending on the implementation of the called `to_json()`
  14653. method.
  14654. @exceptionsafety Depends on the called constructor. For types directly
  14655. supported by the library (i.e., all types for which no `to_json()` function
  14656. was provided), strong guarantee holds: if an exception is thrown, there are
  14657. no changes to any JSON value.
  14658. @liveexample{The following code shows the constructor with several
  14659. compatible types.,basic_json__CompatibleType}
  14660. @since version 2.1.0
  14661. */
  14662. template <typename CompatibleType,
  14663. typename U = detail::uncvref_t<CompatibleType>,
  14664. detail::enable_if_t<
  14665. not detail::is_basic_json<U>::value and detail::is_compatible_type<basic_json_t, U>::value, int> = 0>
  14666. basic_json(CompatibleType && val) noexcept(noexcept(
  14667. JSONSerializer<U>::to_json(std::declval<basic_json_t&>(),
  14668. std::forward<CompatibleType>(val))))
  14669. {
  14670. JSONSerializer<U>::to_json(*this, std::forward<CompatibleType>(val));
  14671. assert_invariant();
  14672. }
  14673. /*!
  14674. @brief create a JSON value from an existing one
  14675. This is a constructor for existing @ref basic_json types.
  14676. It does not hijack copy/move constructors, since the parameter has different
  14677. template arguments than the current ones.
  14678. The constructor tries to convert the internal @ref m_value of the parameter.
  14679. @tparam BasicJsonType a type such that:
  14680. - @a BasicJsonType is a @ref basic_json type.
  14681. - @a BasicJsonType has different template arguments than @ref basic_json_t.
  14682. @param[in] val the @ref basic_json value to be converted.
  14683. @complexity Usually linear in the size of the passed @a val, also
  14684. depending on the implementation of the called `to_json()`
  14685. method.
  14686. @exceptionsafety Depends on the called constructor. For types directly
  14687. supported by the library (i.e., all types for which no `to_json()` function
  14688. was provided), strong guarantee holds: if an exception is thrown, there are
  14689. no changes to any JSON value.
  14690. @since version 3.2.0
  14691. */
  14692. template <typename BasicJsonType,
  14693. detail::enable_if_t<
  14694. detail::is_basic_json<BasicJsonType>::value and not std::is_same<basic_json, BasicJsonType>::value, int> = 0>
  14695. basic_json(const BasicJsonType& val)
  14696. {
  14697. using other_boolean_t = typename BasicJsonType::boolean_t;
  14698. using other_number_float_t = typename BasicJsonType::number_float_t;
  14699. using other_number_integer_t = typename BasicJsonType::number_integer_t;
  14700. using other_number_unsigned_t = typename BasicJsonType::number_unsigned_t;
  14701. using other_string_t = typename BasicJsonType::string_t;
  14702. using other_object_t = typename BasicJsonType::object_t;
  14703. using other_array_t = typename BasicJsonType::array_t;
  14704. using other_binary_t = typename BasicJsonType::internal_binary_t;
  14705. switch (val.type())
  14706. {
  14707. case value_t::boolean:
  14708. JSONSerializer<other_boolean_t>::to_json(*this, val.template get<other_boolean_t>());
  14709. break;
  14710. case value_t::number_float:
  14711. JSONSerializer<other_number_float_t>::to_json(*this, val.template get<other_number_float_t>());
  14712. break;
  14713. case value_t::number_integer:
  14714. JSONSerializer<other_number_integer_t>::to_json(*this, val.template get<other_number_integer_t>());
  14715. break;
  14716. case value_t::number_unsigned:
  14717. JSONSerializer<other_number_unsigned_t>::to_json(*this, val.template get<other_number_unsigned_t>());
  14718. break;
  14719. case value_t::string:
  14720. JSONSerializer<other_string_t>::to_json(*this, val.template get_ref<const other_string_t&>());
  14721. break;
  14722. case value_t::object:
  14723. JSONSerializer<other_object_t>::to_json(*this, val.template get_ref<const other_object_t&>());
  14724. break;
  14725. case value_t::array:
  14726. JSONSerializer<other_array_t>::to_json(*this, val.template get_ref<const other_array_t&>());
  14727. break;
  14728. case value_t::binary:
  14729. JSONSerializer<other_binary_t>::to_json(*this, val.template get_ref<const other_binary_t&>());
  14730. break;
  14731. case value_t::null:
  14732. *this = nullptr;
  14733. break;
  14734. case value_t::discarded:
  14735. m_type = value_t::discarded;
  14736. break;
  14737. default: // LCOV_EXCL_LINE
  14738. assert(false); // LCOV_EXCL_LINE
  14739. }
  14740. assert_invariant();
  14741. }
  14742. /*!
  14743. @brief create a container (array or object) from an initializer list
  14744. Creates a JSON value of type array or object from the passed initializer
  14745. list @a init. In case @a type_deduction is `true` (default), the type of
  14746. the JSON value to be created is deducted from the initializer list @a init
  14747. according to the following rules:
  14748. 1. If the list is empty, an empty JSON object value `{}` is created.
  14749. 2. If the list consists of pairs whose first element is a string, a JSON
  14750. object value is created where the first elements of the pairs are
  14751. treated as keys and the second elements are as values.
  14752. 3. In all other cases, an array is created.
  14753. The rules aim to create the best fit between a C++ initializer list and
  14754. JSON values. The rationale is as follows:
  14755. 1. The empty initializer list is written as `{}` which is exactly an empty
  14756. JSON object.
  14757. 2. C++ has no way of describing mapped types other than to list a list of
  14758. pairs. As JSON requires that keys must be of type string, rule 2 is the
  14759. weakest constraint one can pose on initializer lists to interpret them
  14760. as an object.
  14761. 3. In all other cases, the initializer list could not be interpreted as
  14762. JSON object type, so interpreting it as JSON array type is safe.
  14763. With the rules described above, the following JSON values cannot be
  14764. expressed by an initializer list:
  14765. - the empty array (`[]`): use @ref array(initializer_list_t)
  14766. with an empty initializer list in this case
  14767. - arrays whose elements satisfy rule 2: use @ref
  14768. array(initializer_list_t) with the same initializer list
  14769. in this case
  14770. @note When used without parentheses around an empty initializer list, @ref
  14771. basic_json() is called instead of this function, yielding the JSON null
  14772. value.
  14773. @param[in] init initializer list with JSON values
  14774. @param[in] type_deduction internal parameter; when set to `true`, the type
  14775. of the JSON value is deducted from the initializer list @a init; when set
  14776. to `false`, the type provided via @a manual_type is forced. This mode is
  14777. used by the functions @ref array(initializer_list_t) and
  14778. @ref object(initializer_list_t).
  14779. @param[in] manual_type internal parameter; when @a type_deduction is set
  14780. to `false`, the created JSON value will use the provided type (only @ref
  14781. value_t::array and @ref value_t::object are valid); when @a type_deduction
  14782. is set to `true`, this parameter has no effect
  14783. @throw type_error.301 if @a type_deduction is `false`, @a manual_type is
  14784. `value_t::object`, but @a init contains an element which is not a pair
  14785. whose first element is a string. In this case, the constructor could not
  14786. create an object. If @a type_deduction would have be `true`, an array
  14787. would have been created. See @ref object(initializer_list_t)
  14788. for an example.
  14789. @complexity Linear in the size of the initializer list @a init.
  14790. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  14791. changes to any JSON value.
  14792. @liveexample{The example below shows how JSON values are created from
  14793. initializer lists.,basic_json__list_init_t}
  14794. @sa @ref array(initializer_list_t) -- create a JSON array
  14795. value from an initializer list
  14796. @sa @ref object(initializer_list_t) -- create a JSON object
  14797. value from an initializer list
  14798. @since version 1.0.0
  14799. */
  14800. basic_json(initializer_list_t init,
  14801. bool type_deduction = true,
  14802. value_t manual_type = value_t::array)
  14803. {
  14804. // check if each element is an array with two elements whose first
  14805. // element is a string
  14806. bool is_an_object = std::all_of(init.begin(), init.end(),
  14807. [](const detail::json_ref<basic_json>& element_ref)
  14808. {
  14809. return element_ref->is_array() and element_ref->size() == 2 and (*element_ref)[0].is_string();
  14810. });
  14811. // adjust type if type deduction is not wanted
  14812. if (not type_deduction)
  14813. {
  14814. // if array is wanted, do not create an object though possible
  14815. if (manual_type == value_t::array)
  14816. {
  14817. is_an_object = false;
  14818. }
  14819. // if object is wanted but impossible, throw an exception
  14820. if (JSON_HEDLEY_UNLIKELY(manual_type == value_t::object and not is_an_object))
  14821. {
  14822. JSON_THROW(type_error::create(301, "cannot create object from initializer list"));
  14823. }
  14824. }
  14825. if (is_an_object)
  14826. {
  14827. // the initializer list is a list of pairs -> create object
  14828. m_type = value_t::object;
  14829. m_value = value_t::object;
  14830. std::for_each(init.begin(), init.end(), [this](const detail::json_ref<basic_json>& element_ref)
  14831. {
  14832. auto element = element_ref.moved_or_copied();
  14833. m_value.object->emplace(
  14834. std::move(*((*element.m_value.array)[0].m_value.string)),
  14835. std::move((*element.m_value.array)[1]));
  14836. });
  14837. }
  14838. else
  14839. {
  14840. // the initializer list describes an array -> create array
  14841. m_type = value_t::array;
  14842. m_value.array = create<array_t>(init.begin(), init.end());
  14843. }
  14844. assert_invariant();
  14845. }
  14846. /*!
  14847. @brief explicitly create a binary array from an already constructed copy of
  14848. its base type
  14849. Creates a JSON binary array value from a given `binary_t`. Binary values are
  14850. part of various binary formats, such as CBOR, MsgPack, and BSON. And this
  14851. constructor is used to create a value for serialization to those formats.
  14852. @note Note, this function exists because of the difficulty in correctly
  14853. specifying the correct template overload in the standard value ctor, as both
  14854. JSON arrays and JSON binary arrays are backed with some form of a
  14855. `std::vector`. Because JSON binary arrays are a non-standard extension it
  14856. was decided that it would be best to prevent automatic initialization of a
  14857. binary array type, for backwards compatibility and so it does not happen on
  14858. accident.
  14859. @param[in] init `binary_t` with JSON values to create a binary array from
  14860. @return JSON binary array value
  14861. @complexity Linear in the size of @a init.
  14862. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  14863. changes to any JSON value.
  14864. @since version 3.8.0
  14865. */
  14866. JSON_HEDLEY_WARN_UNUSED_RESULT
  14867. static basic_json binary_array(const binary_t& init)
  14868. {
  14869. auto res = basic_json();
  14870. res.m_type = value_t::binary;
  14871. res.m_value = init;
  14872. return res;
  14873. }
  14874. JSON_HEDLEY_WARN_UNUSED_RESULT
  14875. static basic_json binary_array(const binary_t& init, std::uint8_t subtype)
  14876. {
  14877. auto res = basic_json();
  14878. res.m_type = value_t::binary;
  14879. res.m_value = internal_binary_t(init, subtype);
  14880. return res;
  14881. }
  14882. /*!
  14883. @brief explicitly create a binary array from an already constructed rvalue
  14884. copy of its base type
  14885. Creates a JSON binary array value from a given `binary_t`. Binary values are
  14886. part of various binary formats, such as CBOR, MsgPack, and BSON. And this
  14887. constructor is used to create a value for serialization to those formats.
  14888. @note Note, this function exists because of the difficulty in correctly
  14889. specifying the correct template overload in the standard value ctor, as both
  14890. JSON arrays and JSON binary arrays are backed with some form of a
  14891. `std::vector`. Because JSON binary arrays are a non-standard extension it
  14892. was decided that it would be best to prevent automatic initialization of a
  14893. binary array type, for backwards compatibility and so it doesn't happen on
  14894. accident.
  14895. @param[in] init `binary_t` with JSON values to create a binary array from
  14896. @return JSON binary array value
  14897. @complexity Linear in the size of @a init.
  14898. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  14899. changes to any JSON value.
  14900. @since version 3.8.0
  14901. */
  14902. JSON_HEDLEY_WARN_UNUSED_RESULT
  14903. static basic_json binary_array(binary_t&& init)
  14904. {
  14905. auto res = basic_json();
  14906. res.m_type = value_t::binary;
  14907. res.m_value = std::move(init);
  14908. return res;
  14909. }
  14910. JSON_HEDLEY_WARN_UNUSED_RESULT
  14911. static basic_json binary_array(binary_t&& init, std::uint8_t subtype)
  14912. {
  14913. auto res = basic_json();
  14914. res.m_type = value_t::binary;
  14915. res.m_value = internal_binary_t(std::move(init), subtype);
  14916. return res;
  14917. }
  14918. /*!
  14919. @brief explicitly create an array from an initializer list
  14920. Creates a JSON array value from a given initializer list. That is, given a
  14921. list of values `a, b, c`, creates the JSON value `[a, b, c]`. If the
  14922. initializer list is empty, the empty array `[]` is created.
  14923. @note This function is only needed to express two edge cases that cannot
  14924. be realized with the initializer list constructor (@ref
  14925. basic_json(initializer_list_t, bool, value_t)). These cases
  14926. are:
  14927. 1. creating an array whose elements are all pairs whose first element is a
  14928. string -- in this case, the initializer list constructor would create an
  14929. object, taking the first elements as keys
  14930. 2. creating an empty array -- passing the empty initializer list to the
  14931. initializer list constructor yields an empty object
  14932. @param[in] init initializer list with JSON values to create an array from
  14933. (optional)
  14934. @return JSON array value
  14935. @complexity Linear in the size of @a init.
  14936. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  14937. changes to any JSON value.
  14938. @liveexample{The following code shows an example for the `array`
  14939. function.,array}
  14940. @sa @ref basic_json(initializer_list_t, bool, value_t) --
  14941. create a JSON value from an initializer list
  14942. @sa @ref object(initializer_list_t) -- create a JSON object
  14943. value from an initializer list
  14944. @since version 1.0.0
  14945. */
  14946. JSON_HEDLEY_WARN_UNUSED_RESULT
  14947. static basic_json array(initializer_list_t init = {})
  14948. {
  14949. return basic_json(init, false, value_t::array);
  14950. }
  14951. /*!
  14952. @brief explicitly create an object from an initializer list
  14953. Creates a JSON object value from a given initializer list. The initializer
  14954. lists elements must be pairs, and their first elements must be strings. If
  14955. the initializer list is empty, the empty object `{}` is created.
  14956. @note This function is only added for symmetry reasons. In contrast to the
  14957. related function @ref array(initializer_list_t), there are
  14958. no cases which can only be expressed by this function. That is, any
  14959. initializer list @a init can also be passed to the initializer list
  14960. constructor @ref basic_json(initializer_list_t, bool, value_t).
  14961. @param[in] init initializer list to create an object from (optional)
  14962. @return JSON object value
  14963. @throw type_error.301 if @a init is not a list of pairs whose first
  14964. elements are strings. In this case, no object can be created. When such a
  14965. value is passed to @ref basic_json(initializer_list_t, bool, value_t),
  14966. an array would have been created from the passed initializer list @a init.
  14967. See example below.
  14968. @complexity Linear in the size of @a init.
  14969. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  14970. changes to any JSON value.
  14971. @liveexample{The following code shows an example for the `object`
  14972. function.,object}
  14973. @sa @ref basic_json(initializer_list_t, bool, value_t) --
  14974. create a JSON value from an initializer list
  14975. @sa @ref array(initializer_list_t) -- create a JSON array
  14976. value from an initializer list
  14977. @since version 1.0.0
  14978. */
  14979. JSON_HEDLEY_WARN_UNUSED_RESULT
  14980. static basic_json object(initializer_list_t init = {})
  14981. {
  14982. return basic_json(init, false, value_t::object);
  14983. }
  14984. /*!
  14985. @brief construct an array with count copies of given value
  14986. Constructs a JSON array value by creating @a cnt copies of a passed value.
  14987. In case @a cnt is `0`, an empty array is created.
  14988. @param[in] cnt the number of JSON copies of @a val to create
  14989. @param[in] val the JSON value to copy
  14990. @post `std::distance(begin(),end()) == cnt` holds.
  14991. @complexity Linear in @a cnt.
  14992. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  14993. changes to any JSON value.
  14994. @liveexample{The following code shows examples for the @ref
  14995. basic_json(size_type\, const basic_json&)
  14996. constructor.,basic_json__size_type_basic_json}
  14997. @since version 1.0.0
  14998. */
  14999. basic_json(size_type cnt, const basic_json& val)
  15000. : m_type(value_t::array)
  15001. {
  15002. m_value.array = create<array_t>(cnt, val);
  15003. assert_invariant();
  15004. }
  15005. /*!
  15006. @brief construct a JSON container given an iterator range
  15007. Constructs the JSON value with the contents of the range `[first, last)`.
  15008. The semantics depends on the different types a JSON value can have:
  15009. - In case of a null type, invalid_iterator.206 is thrown.
  15010. - In case of other primitive types (number, boolean, or string), @a first
  15011. must be `begin()` and @a last must be `end()`. In this case, the value is
  15012. copied. Otherwise, invalid_iterator.204 is thrown.
  15013. - In case of structured types (array, object), the constructor behaves as
  15014. similar versions for `std::vector` or `std::map`; that is, a JSON array
  15015. or object is constructed from the values in the range.
  15016. @tparam InputIT an input iterator type (@ref iterator or @ref
  15017. const_iterator)
  15018. @param[in] first begin of the range to copy from (included)
  15019. @param[in] last end of the range to copy from (excluded)
  15020. @pre Iterators @a first and @a last must be initialized. **This
  15021. precondition is enforced with an assertion (see warning).** If
  15022. assertions are switched off, a violation of this precondition yields
  15023. undefined behavior.
  15024. @pre Range `[first, last)` is valid. Usually, this precondition cannot be
  15025. checked efficiently. Only certain edge cases are detected; see the
  15026. description of the exceptions below. A violation of this precondition
  15027. yields undefined behavior.
  15028. @warning A precondition is enforced with a runtime assertion that will
  15029. result in calling `std::abort` if this precondition is not met.
  15030. Assertions can be disabled by defining `NDEBUG` at compile time.
  15031. See https://en.cppreference.com/w/cpp/error/assert for more
  15032. information.
  15033. @throw invalid_iterator.201 if iterators @a first and @a last are not
  15034. compatible (i.e., do not belong to the same JSON value). In this case,
  15035. the range `[first, last)` is undefined.
  15036. @throw invalid_iterator.204 if iterators @a first and @a last belong to a
  15037. primitive type (number, boolean, or string), but @a first does not point
  15038. to the first element any more. In this case, the range `[first, last)` is
  15039. undefined. See example code below.
  15040. @throw invalid_iterator.206 if iterators @a first and @a last belong to a
  15041. null value. In this case, the range `[first, last)` is undefined.
  15042. @complexity Linear in distance between @a first and @a last.
  15043. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  15044. changes to any JSON value.
  15045. @liveexample{The example below shows several ways to create JSON values by
  15046. specifying a subrange with iterators.,basic_json__InputIt_InputIt}
  15047. @since version 1.0.0
  15048. */
  15049. template<class InputIT, typename std::enable_if<
  15050. std::is_same<InputIT, typename basic_json_t::iterator>::value or
  15051. std::is_same<InputIT, typename basic_json_t::const_iterator>::value, int>::type = 0>
  15052. basic_json(InputIT first, InputIT last)
  15053. {
  15054. assert(first.m_object != nullptr);
  15055. assert(last.m_object != nullptr);
  15056. // make sure iterator fits the current value
  15057. if (JSON_HEDLEY_UNLIKELY(first.m_object != last.m_object))
  15058. {
  15059. JSON_THROW(invalid_iterator::create(201, "iterators are not compatible"));
  15060. }
  15061. // copy type from first iterator
  15062. m_type = first.m_object->m_type;
  15063. // check if iterator range is complete for primitive values
  15064. switch (m_type)
  15065. {
  15066. case value_t::boolean:
  15067. case value_t::number_float:
  15068. case value_t::number_integer:
  15069. case value_t::number_unsigned:
  15070. case value_t::string:
  15071. {
  15072. if (JSON_HEDLEY_UNLIKELY(not first.m_it.primitive_iterator.is_begin()
  15073. or not last.m_it.primitive_iterator.is_end()))
  15074. {
  15075. JSON_THROW(invalid_iterator::create(204, "iterators out of range"));
  15076. }
  15077. break;
  15078. }
  15079. default:
  15080. break;
  15081. }
  15082. switch (m_type)
  15083. {
  15084. case value_t::number_integer:
  15085. {
  15086. m_value.number_integer = first.m_object->m_value.number_integer;
  15087. break;
  15088. }
  15089. case value_t::number_unsigned:
  15090. {
  15091. m_value.number_unsigned = first.m_object->m_value.number_unsigned;
  15092. break;
  15093. }
  15094. case value_t::number_float:
  15095. {
  15096. m_value.number_float = first.m_object->m_value.number_float;
  15097. break;
  15098. }
  15099. case value_t::boolean:
  15100. {
  15101. m_value.boolean = first.m_object->m_value.boolean;
  15102. break;
  15103. }
  15104. case value_t::string:
  15105. {
  15106. m_value = *first.m_object->m_value.string;
  15107. break;
  15108. }
  15109. case value_t::object:
  15110. {
  15111. m_value.object = create<object_t>(first.m_it.object_iterator,
  15112. last.m_it.object_iterator);
  15113. break;
  15114. }
  15115. case value_t::array:
  15116. {
  15117. m_value.array = create<array_t>(first.m_it.array_iterator,
  15118. last.m_it.array_iterator);
  15119. break;
  15120. }
  15121. case value_t::binary:
  15122. {
  15123. m_value = *first.m_object->m_value.binary;
  15124. break;
  15125. }
  15126. default:
  15127. JSON_THROW(invalid_iterator::create(206, "cannot construct with iterators from " +
  15128. std::string(first.m_object->type_name())));
  15129. }
  15130. assert_invariant();
  15131. }
  15132. ///////////////////////////////////////
  15133. // other constructors and destructor //
  15134. ///////////////////////////////////////
  15135. template <typename JsonRef,
  15136. detail::enable_if_t<detail::conjunction<detail::is_json_ref<JsonRef>,
  15137. std::is_same<typename JsonRef::value_type, basic_json>>::value, int> = 0 >
  15138. basic_json(const JsonRef& ref) : basic_json(ref.moved_or_copied()) {}
  15139. /*!
  15140. @brief copy constructor
  15141. Creates a copy of a given JSON value.
  15142. @param[in] other the JSON value to copy
  15143. @post `*this == other`
  15144. @complexity Linear in the size of @a other.
  15145. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  15146. changes to any JSON value.
  15147. @requirement This function helps `basic_json` satisfying the
  15148. [Container](https://en.cppreference.com/w/cpp/named_req/Container)
  15149. requirements:
  15150. - The complexity is linear.
  15151. - As postcondition, it holds: `other == basic_json(other)`.
  15152. @liveexample{The following code shows an example for the copy
  15153. constructor.,basic_json__basic_json}
  15154. @since version 1.0.0
  15155. */
  15156. basic_json(const basic_json& other)
  15157. : m_type(other.m_type)
  15158. {
  15159. // check of passed value is valid
  15160. other.assert_invariant();
  15161. switch (m_type)
  15162. {
  15163. case value_t::object:
  15164. {
  15165. m_value = *other.m_value.object;
  15166. break;
  15167. }
  15168. case value_t::array:
  15169. {
  15170. m_value = *other.m_value.array;
  15171. break;
  15172. }
  15173. case value_t::string:
  15174. {
  15175. m_value = *other.m_value.string;
  15176. break;
  15177. }
  15178. case value_t::boolean:
  15179. {
  15180. m_value = other.m_value.boolean;
  15181. break;
  15182. }
  15183. case value_t::number_integer:
  15184. {
  15185. m_value = other.m_value.number_integer;
  15186. break;
  15187. }
  15188. case value_t::number_unsigned:
  15189. {
  15190. m_value = other.m_value.number_unsigned;
  15191. break;
  15192. }
  15193. case value_t::number_float:
  15194. {
  15195. m_value = other.m_value.number_float;
  15196. break;
  15197. }
  15198. case value_t::binary:
  15199. {
  15200. m_value = *other.m_value.binary;
  15201. break;
  15202. }
  15203. default:
  15204. break;
  15205. }
  15206. assert_invariant();
  15207. }
  15208. /*!
  15209. @brief move constructor
  15210. Move constructor. Constructs a JSON value with the contents of the given
  15211. value @a other using move semantics. It "steals" the resources from @a
  15212. other and leaves it as JSON null value.
  15213. @param[in,out] other value to move to this object
  15214. @post `*this` has the same value as @a other before the call.
  15215. @post @a other is a JSON null value.
  15216. @complexity Constant.
  15217. @exceptionsafety No-throw guarantee: this constructor never throws
  15218. exceptions.
  15219. @requirement This function helps `basic_json` satisfying the
  15220. [MoveConstructible](https://en.cppreference.com/w/cpp/named_req/MoveConstructible)
  15221. requirements.
  15222. @liveexample{The code below shows the move constructor explicitly called
  15223. via std::move.,basic_json__moveconstructor}
  15224. @since version 1.0.0
  15225. */
  15226. basic_json(basic_json&& other) noexcept
  15227. : m_type(std::move(other.m_type)),
  15228. m_value(std::move(other.m_value))
  15229. {
  15230. // check that passed value is valid
  15231. other.assert_invariant();
  15232. // invalidate payload
  15233. other.m_type = value_t::null;
  15234. other.m_value = {};
  15235. assert_invariant();
  15236. }
  15237. /*!
  15238. @brief copy assignment
  15239. Copy assignment operator. Copies a JSON value via the "copy and swap"
  15240. strategy: It is expressed in terms of the copy constructor, destructor,
  15241. and the `swap()` member function.
  15242. @param[in] other value to copy from
  15243. @complexity Linear.
  15244. @requirement This function helps `basic_json` satisfying the
  15245. [Container](https://en.cppreference.com/w/cpp/named_req/Container)
  15246. requirements:
  15247. - The complexity is linear.
  15248. @liveexample{The code below shows and example for the copy assignment. It
  15249. creates a copy of value `a` which is then swapped with `b`. Finally\, the
  15250. copy of `a` (which is the null value after the swap) is
  15251. destroyed.,basic_json__copyassignment}
  15252. @since version 1.0.0
  15253. */
  15254. basic_json& operator=(basic_json other) noexcept (
  15255. std::is_nothrow_move_constructible<value_t>::value and
  15256. std::is_nothrow_move_assignable<value_t>::value and
  15257. std::is_nothrow_move_constructible<json_value>::value and
  15258. std::is_nothrow_move_assignable<json_value>::value
  15259. )
  15260. {
  15261. // check that passed value is valid
  15262. other.assert_invariant();
  15263. using std::swap;
  15264. swap(m_type, other.m_type);
  15265. swap(m_value, other.m_value);
  15266. assert_invariant();
  15267. return *this;
  15268. }
  15269. /*!
  15270. @brief destructor
  15271. Destroys the JSON value and frees all allocated memory.
  15272. @complexity Linear.
  15273. @requirement This function helps `basic_json` satisfying the
  15274. [Container](https://en.cppreference.com/w/cpp/named_req/Container)
  15275. requirements:
  15276. - The complexity is linear.
  15277. - All stored elements are destroyed and all memory is freed.
  15278. @since version 1.0.0
  15279. */
  15280. ~basic_json() noexcept
  15281. {
  15282. assert_invariant();
  15283. m_value.destroy(m_type);
  15284. }
  15285. /// @}
  15286. public:
  15287. ///////////////////////
  15288. // object inspection //
  15289. ///////////////////////
  15290. /// @name object inspection
  15291. /// Functions to inspect the type of a JSON value.
  15292. /// @{
  15293. /*!
  15294. @brief serialization
  15295. Serialization function for JSON values. The function tries to mimic
  15296. Python's `json.dumps()` function, and currently supports its @a indent
  15297. and @a ensure_ascii parameters.
  15298. @param[in] indent If indent is nonnegative, then array elements and object
  15299. members will be pretty-printed with that indent level. An indent level of
  15300. `0` will only insert newlines. `-1` (the default) selects the most compact
  15301. representation.
  15302. @param[in] indent_char The character to use for indentation if @a indent is
  15303. greater than `0`. The default is ` ` (space).
  15304. @param[in] ensure_ascii If @a ensure_ascii is true, all non-ASCII characters
  15305. in the output are escaped with `\uXXXX` sequences, and the result consists
  15306. of ASCII characters only.
  15307. @param[in] error_handler how to react on decoding errors; there are three
  15308. possible values: `strict` (throws and exception in case a decoding error
  15309. occurs; default), `replace` (replace invalid UTF-8 sequences with U+FFFD),
  15310. and `ignore` (ignore invalid UTF-8 sequences during serialization).
  15311. @param[in] serialize_binary Whether or not to allow serialization of binary
  15312. types to JSON. Because binary types are non-standard, this will produce
  15313. non-conformant JSON, and is disabled by default. This flag is primarily
  15314. useful for debugging. Will output the binary value as a list of 8-bit
  15315. numbers prefixed by "b" (e.g. "bindata" = b[3, 0, 42, 255]).
  15316. @return string containing the serialization of the JSON value
  15317. @throw type_error.316 if a string stored inside the JSON value is not
  15318. UTF-8 encoded
  15319. @complexity Linear.
  15320. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  15321. changes in the JSON value.
  15322. @liveexample{The following example shows the effect of different @a indent\,
  15323. @a indent_char\, and @a ensure_ascii parameters to the result of the
  15324. serialization.,dump}
  15325. @see https://docs.python.org/2/library/json.html#json.dump
  15326. @since version 1.0.0; indentation character @a indent_char, option
  15327. @a ensure_ascii and exceptions added in version 3.0.0; error
  15328. handlers added in version 3.4.0.
  15329. */
  15330. string_t dump(const int indent = -1,
  15331. const char indent_char = ' ',
  15332. const bool ensure_ascii = false,
  15333. const error_handler_t error_handler = error_handler_t::strict,
  15334. const bool serialize_binary = false) const
  15335. {
  15336. string_t result;
  15337. serializer s(detail::output_adapter<char, string_t>(result), indent_char, error_handler);
  15338. if (indent >= 0)
  15339. {
  15340. s.dump(*this, true, ensure_ascii, static_cast<unsigned int>(indent), 0, serialize_binary);
  15341. }
  15342. else
  15343. {
  15344. s.dump(*this, false, ensure_ascii, 0, 0, serialize_binary);
  15345. }
  15346. return result;
  15347. }
  15348. /*!
  15349. @brief return the type of the JSON value (explicit)
  15350. Return the type of the JSON value as a value from the @ref value_t
  15351. enumeration.
  15352. @return the type of the JSON value
  15353. Value type | return value
  15354. ------------------------- | -------------------------
  15355. null | value_t::null
  15356. boolean | value_t::boolean
  15357. string | value_t::string
  15358. number (integer) | value_t::number_integer
  15359. number (unsigned integer) | value_t::number_unsigned
  15360. number (floating-point) | value_t::number_float
  15361. object | value_t::object
  15362. array | value_t::array
  15363. binary | value_t::binary
  15364. discarded | value_t::discarded
  15365. @complexity Constant.
  15366. @exceptionsafety No-throw guarantee: this member function never throws
  15367. exceptions.
  15368. @liveexample{The following code exemplifies `type()` for all JSON
  15369. types.,type}
  15370. @sa @ref operator value_t() -- return the type of the JSON value (implicit)
  15371. @sa @ref type_name() -- return the type as string
  15372. @since version 1.0.0
  15373. */
  15374. constexpr value_t type() const noexcept
  15375. {
  15376. return m_type;
  15377. }
  15378. /*!
  15379. @brief return whether type is primitive
  15380. This function returns true if and only if the JSON type is primitive
  15381. (string, number, boolean, or null).
  15382. @return `true` if type is primitive (string, number, boolean, or null),
  15383. `false` otherwise.
  15384. @complexity Constant.
  15385. @exceptionsafety No-throw guarantee: this member function never throws
  15386. exceptions.
  15387. @liveexample{The following code exemplifies `is_primitive()` for all JSON
  15388. types.,is_primitive}
  15389. @sa @ref is_structured() -- returns whether JSON value is structured
  15390. @sa @ref is_null() -- returns whether JSON value is `null`
  15391. @sa @ref is_string() -- returns whether JSON value is a string
  15392. @sa @ref is_boolean() -- returns whether JSON value is a boolean
  15393. @sa @ref is_number() -- returns whether JSON value is a number
  15394. @sa @ref is_binary() -- returns whether JSON value is a binary array
  15395. @since version 1.0.0
  15396. */
  15397. constexpr bool is_primitive() const noexcept
  15398. {
  15399. return is_null() or is_string() or is_boolean() or is_number() or is_binary();
  15400. }
  15401. /*!
  15402. @brief return whether type is structured
  15403. This function returns true if and only if the JSON type is structured
  15404. (array or object).
  15405. @return `true` if type is structured (array or object), `false` otherwise.
  15406. @complexity Constant.
  15407. @exceptionsafety No-throw guarantee: this member function never throws
  15408. exceptions.
  15409. @liveexample{The following code exemplifies `is_structured()` for all JSON
  15410. types.,is_structured}
  15411. @sa @ref is_primitive() -- returns whether value is primitive
  15412. @sa @ref is_array() -- returns whether value is an array
  15413. @sa @ref is_object() -- returns whether value is an object
  15414. @since version 1.0.0
  15415. */
  15416. constexpr bool is_structured() const noexcept
  15417. {
  15418. return is_array() or is_object();
  15419. }
  15420. /*!
  15421. @brief return whether value is null
  15422. This function returns true if and only if the JSON value is null.
  15423. @return `true` if type is null, `false` otherwise.
  15424. @complexity Constant.
  15425. @exceptionsafety No-throw guarantee: this member function never throws
  15426. exceptions.
  15427. @liveexample{The following code exemplifies `is_null()` for all JSON
  15428. types.,is_null}
  15429. @since version 1.0.0
  15430. */
  15431. constexpr bool is_null() const noexcept
  15432. {
  15433. return m_type == value_t::null;
  15434. }
  15435. /*!
  15436. @brief return whether value is a boolean
  15437. This function returns true if and only if the JSON value is a boolean.
  15438. @return `true` if type is boolean, `false` otherwise.
  15439. @complexity Constant.
  15440. @exceptionsafety No-throw guarantee: this member function never throws
  15441. exceptions.
  15442. @liveexample{The following code exemplifies `is_boolean()` for all JSON
  15443. types.,is_boolean}
  15444. @since version 1.0.0
  15445. */
  15446. constexpr bool is_boolean() const noexcept
  15447. {
  15448. return m_type == value_t::boolean;
  15449. }
  15450. /*!
  15451. @brief return whether value is a number
  15452. This function returns true if and only if the JSON value is a number. This
  15453. includes both integer (signed and unsigned) and floating-point values.
  15454. @return `true` if type is number (regardless whether integer, unsigned
  15455. integer or floating-type), `false` otherwise.
  15456. @complexity Constant.
  15457. @exceptionsafety No-throw guarantee: this member function never throws
  15458. exceptions.
  15459. @liveexample{The following code exemplifies `is_number()` for all JSON
  15460. types.,is_number}
  15461. @sa @ref is_number_integer() -- check if value is an integer or unsigned
  15462. integer number
  15463. @sa @ref is_number_unsigned() -- check if value is an unsigned integer
  15464. number
  15465. @sa @ref is_number_float() -- check if value is a floating-point number
  15466. @since version 1.0.0
  15467. */
  15468. constexpr bool is_number() const noexcept
  15469. {
  15470. return is_number_integer() or is_number_float();
  15471. }
  15472. /*!
  15473. @brief return whether value is an integer number
  15474. This function returns true if and only if the JSON value is a signed or
  15475. unsigned integer number. This excludes floating-point values.
  15476. @return `true` if type is an integer or unsigned integer number, `false`
  15477. otherwise.
  15478. @complexity Constant.
  15479. @exceptionsafety No-throw guarantee: this member function never throws
  15480. exceptions.
  15481. @liveexample{The following code exemplifies `is_number_integer()` for all
  15482. JSON types.,is_number_integer}
  15483. @sa @ref is_number() -- check if value is a number
  15484. @sa @ref is_number_unsigned() -- check if value is an unsigned integer
  15485. number
  15486. @sa @ref is_number_float() -- check if value is a floating-point number
  15487. @since version 1.0.0
  15488. */
  15489. constexpr bool is_number_integer() const noexcept
  15490. {
  15491. return m_type == value_t::number_integer or m_type == value_t::number_unsigned;
  15492. }
  15493. /*!
  15494. @brief return whether value is an unsigned integer number
  15495. This function returns true if and only if the JSON value is an unsigned
  15496. integer number. This excludes floating-point and signed integer values.
  15497. @return `true` if type is an unsigned integer number, `false` otherwise.
  15498. @complexity Constant.
  15499. @exceptionsafety No-throw guarantee: this member function never throws
  15500. exceptions.
  15501. @liveexample{The following code exemplifies `is_number_unsigned()` for all
  15502. JSON types.,is_number_unsigned}
  15503. @sa @ref is_number() -- check if value is a number
  15504. @sa @ref is_number_integer() -- check if value is an integer or unsigned
  15505. integer number
  15506. @sa @ref is_number_float() -- check if value is a floating-point number
  15507. @since version 2.0.0
  15508. */
  15509. constexpr bool is_number_unsigned() const noexcept
  15510. {
  15511. return m_type == value_t::number_unsigned;
  15512. }
  15513. /*!
  15514. @brief return whether value is a floating-point number
  15515. This function returns true if and only if the JSON value is a
  15516. floating-point number. This excludes signed and unsigned integer values.
  15517. @return `true` if type is a floating-point number, `false` otherwise.
  15518. @complexity Constant.
  15519. @exceptionsafety No-throw guarantee: this member function never throws
  15520. exceptions.
  15521. @liveexample{The following code exemplifies `is_number_float()` for all
  15522. JSON types.,is_number_float}
  15523. @sa @ref is_number() -- check if value is number
  15524. @sa @ref is_number_integer() -- check if value is an integer number
  15525. @sa @ref is_number_unsigned() -- check if value is an unsigned integer
  15526. number
  15527. @since version 1.0.0
  15528. */
  15529. constexpr bool is_number_float() const noexcept
  15530. {
  15531. return m_type == value_t::number_float;
  15532. }
  15533. /*!
  15534. @brief return whether value is an object
  15535. This function returns true if and only if the JSON value is an object.
  15536. @return `true` if type is object, `false` otherwise.
  15537. @complexity Constant.
  15538. @exceptionsafety No-throw guarantee: this member function never throws
  15539. exceptions.
  15540. @liveexample{The following code exemplifies `is_object()` for all JSON
  15541. types.,is_object}
  15542. @since version 1.0.0
  15543. */
  15544. constexpr bool is_object() const noexcept
  15545. {
  15546. return m_type == value_t::object;
  15547. }
  15548. /*!
  15549. @brief return whether value is an array
  15550. This function returns true if and only if the JSON value is an array.
  15551. @return `true` if type is array, `false` otherwise.
  15552. @complexity Constant.
  15553. @exceptionsafety No-throw guarantee: this member function never throws
  15554. exceptions.
  15555. @liveexample{The following code exemplifies `is_array()` for all JSON
  15556. types.,is_array}
  15557. @since version 1.0.0
  15558. */
  15559. constexpr bool is_array() const noexcept
  15560. {
  15561. return m_type == value_t::array;
  15562. }
  15563. /*!
  15564. @brief return whether value is a string
  15565. This function returns true if and only if the JSON value is a string.
  15566. @return `true` if type is string, `false` otherwise.
  15567. @complexity Constant.
  15568. @exceptionsafety No-throw guarantee: this member function never throws
  15569. exceptions.
  15570. @liveexample{The following code exemplifies `is_string()` for all JSON
  15571. types.,is_string}
  15572. @since version 1.0.0
  15573. */
  15574. constexpr bool is_string() const noexcept
  15575. {
  15576. return m_type == value_t::string;
  15577. }
  15578. /*!
  15579. @brief return whether value is a binary array
  15580. This function returns true if and only if the JSON value is a binary array.
  15581. @return `true` if type is binary array, `false` otherwise.
  15582. @complexity Constant.
  15583. @exceptionsafety No-throw guarantee: this member function never throws
  15584. exceptions.
  15585. @liveexample{The following code exemplifies `is_binary()` for all JSON
  15586. types.,is_binary}
  15587. @since version 3.8.0
  15588. */
  15589. constexpr bool is_binary() const noexcept
  15590. {
  15591. return m_type == value_t::binary;
  15592. }
  15593. /*!
  15594. @brief return whether value is discarded
  15595. This function returns true if and only if the JSON value was discarded
  15596. during parsing with a callback function (see @ref parser_callback_t).
  15597. @note This function will always be `false` for JSON values after parsing.
  15598. That is, discarded values can only occur during parsing, but will be
  15599. removed when inside a structured value or replaced by null in other cases.
  15600. @return `true` if type is discarded, `false` otherwise.
  15601. @complexity Constant.
  15602. @exceptionsafety No-throw guarantee: this member function never throws
  15603. exceptions.
  15604. @liveexample{The following code exemplifies `is_discarded()` for all JSON
  15605. types.,is_discarded}
  15606. @since version 1.0.0
  15607. */
  15608. constexpr bool is_discarded() const noexcept
  15609. {
  15610. return m_type == value_t::discarded;
  15611. }
  15612. /*!
  15613. @brief return the type of the JSON value (implicit)
  15614. Implicitly return the type of the JSON value as a value from the @ref
  15615. value_t enumeration.
  15616. @return the type of the JSON value
  15617. @complexity Constant.
  15618. @exceptionsafety No-throw guarantee: this member function never throws
  15619. exceptions.
  15620. @liveexample{The following code exemplifies the @ref value_t operator for
  15621. all JSON types.,operator__value_t}
  15622. @sa @ref type() -- return the type of the JSON value (explicit)
  15623. @sa @ref type_name() -- return the type as string
  15624. @since version 1.0.0
  15625. */
  15626. constexpr operator value_t() const noexcept
  15627. {
  15628. return m_type;
  15629. }
  15630. /// @}
  15631. private:
  15632. //////////////////
  15633. // value access //
  15634. //////////////////
  15635. /// get a boolean (explicit)
  15636. boolean_t get_impl(boolean_t* /*unused*/) const
  15637. {
  15638. if (JSON_HEDLEY_LIKELY(is_boolean()))
  15639. {
  15640. return m_value.boolean;
  15641. }
  15642. JSON_THROW(type_error::create(302, "type must be boolean, but is " + std::string(type_name())));
  15643. }
  15644. /// get a pointer to the value (object)
  15645. object_t* get_impl_ptr(object_t* /*unused*/) noexcept
  15646. {
  15647. return is_object() ? m_value.object : nullptr;
  15648. }
  15649. /// get a pointer to the value (object)
  15650. constexpr const object_t* get_impl_ptr(const object_t* /*unused*/) const noexcept
  15651. {
  15652. return is_object() ? m_value.object : nullptr;
  15653. }
  15654. /// get a pointer to the value (array)
  15655. array_t* get_impl_ptr(array_t* /*unused*/) noexcept
  15656. {
  15657. return is_array() ? m_value.array : nullptr;
  15658. }
  15659. /// get a pointer to the value (array)
  15660. constexpr const array_t* get_impl_ptr(const array_t* /*unused*/) const noexcept
  15661. {
  15662. return is_array() ? m_value.array : nullptr;
  15663. }
  15664. /// get a pointer to the value (string)
  15665. string_t* get_impl_ptr(string_t* /*unused*/) noexcept
  15666. {
  15667. return is_string() ? m_value.string : nullptr;
  15668. }
  15669. /// get a pointer to the value (string)
  15670. constexpr const string_t* get_impl_ptr(const string_t* /*unused*/) const noexcept
  15671. {
  15672. return is_string() ? m_value.string : nullptr;
  15673. }
  15674. /// get a pointer to the value (boolean)
  15675. boolean_t* get_impl_ptr(boolean_t* /*unused*/) noexcept
  15676. {
  15677. return is_boolean() ? &m_value.boolean : nullptr;
  15678. }
  15679. /// get a pointer to the value (boolean)
  15680. constexpr const boolean_t* get_impl_ptr(const boolean_t* /*unused*/) const noexcept
  15681. {
  15682. return is_boolean() ? &m_value.boolean : nullptr;
  15683. }
  15684. /// get a pointer to the value (integer number)
  15685. number_integer_t* get_impl_ptr(number_integer_t* /*unused*/) noexcept
  15686. {
  15687. return is_number_integer() ? &m_value.number_integer : nullptr;
  15688. }
  15689. /// get a pointer to the value (integer number)
  15690. constexpr const number_integer_t* get_impl_ptr(const number_integer_t* /*unused*/) const noexcept
  15691. {
  15692. return is_number_integer() ? &m_value.number_integer : nullptr;
  15693. }
  15694. /// get a pointer to the value (unsigned number)
  15695. number_unsigned_t* get_impl_ptr(number_unsigned_t* /*unused*/) noexcept
  15696. {
  15697. return is_number_unsigned() ? &m_value.number_unsigned : nullptr;
  15698. }
  15699. /// get a pointer to the value (unsigned number)
  15700. constexpr const number_unsigned_t* get_impl_ptr(const number_unsigned_t* /*unused*/) const noexcept
  15701. {
  15702. return is_number_unsigned() ? &m_value.number_unsigned : nullptr;
  15703. }
  15704. /// get a pointer to the value (floating-point number)
  15705. number_float_t* get_impl_ptr(number_float_t* /*unused*/) noexcept
  15706. {
  15707. return is_number_float() ? &m_value.number_float : nullptr;
  15708. }
  15709. /// get a pointer to the value (floating-point number)
  15710. constexpr const number_float_t* get_impl_ptr(const number_float_t* /*unused*/) const noexcept
  15711. {
  15712. return is_number_float() ? &m_value.number_float : nullptr;
  15713. }
  15714. /// get a pointer to the value (binary)
  15715. binary_t* get_impl_ptr(binary_t* /*unused*/) noexcept
  15716. {
  15717. return is_binary() ? reinterpret_cast<binary_t*>(m_value.binary) : nullptr;
  15718. }
  15719. /// get a pointer to the value (binary)
  15720. constexpr const binary_t* get_impl_ptr(const binary_t* /*unused*/) const noexcept
  15721. {
  15722. return is_binary() ? m_value.binary : nullptr;
  15723. }
  15724. /// get a pointer to the value (binary)
  15725. internal_binary_t* get_impl_ptr(internal_binary_t* /*unused*/) noexcept
  15726. {
  15727. return is_binary() ? m_value.binary : nullptr;
  15728. }
  15729. /// get a pointer to the value (binary)
  15730. constexpr const internal_binary_t* get_impl_ptr(const internal_binary_t* /*unused*/) const noexcept
  15731. {
  15732. return is_binary() ? m_value.binary : nullptr;
  15733. }
  15734. /*!
  15735. @brief helper function to implement get_ref()
  15736. This function helps to implement get_ref() without code duplication for
  15737. const and non-const overloads
  15738. @tparam ThisType will be deduced as `basic_json` or `const basic_json`
  15739. @throw type_error.303 if ReferenceType does not match underlying value
  15740. type of the current JSON
  15741. */
  15742. template<typename ReferenceType, typename ThisType>
  15743. static ReferenceType get_ref_impl(ThisType& obj)
  15744. {
  15745. // delegate the call to get_ptr<>()
  15746. auto ptr = obj.template get_ptr<typename std::add_pointer<ReferenceType>::type>();
  15747. if (JSON_HEDLEY_LIKELY(ptr != nullptr))
  15748. {
  15749. return *ptr;
  15750. }
  15751. JSON_THROW(type_error::create(303, "incompatible ReferenceType for get_ref, actual type is " + std::string(obj.type_name())));
  15752. }
  15753. public:
  15754. /// @name value access
  15755. /// Direct access to the stored value of a JSON value.
  15756. /// @{
  15757. /*!
  15758. @brief get special-case overload
  15759. This overloads avoids a lot of template boilerplate, it can be seen as the
  15760. identity method
  15761. @tparam BasicJsonType == @ref basic_json
  15762. @return a copy of *this
  15763. @complexity Constant.
  15764. @since version 2.1.0
  15765. */
  15766. template<typename BasicJsonType, detail::enable_if_t<
  15767. std::is_same<typename std::remove_const<BasicJsonType>::type, basic_json_t>::value,
  15768. int> = 0>
  15769. basic_json get() const
  15770. {
  15771. return *this;
  15772. }
  15773. /*!
  15774. @brief get special-case overload
  15775. This overloads converts the current @ref basic_json in a different
  15776. @ref basic_json type
  15777. @tparam BasicJsonType == @ref basic_json
  15778. @return a copy of *this, converted into @tparam BasicJsonType
  15779. @complexity Depending on the implementation of the called `from_json()`
  15780. method.
  15781. @since version 3.2.0
  15782. */
  15783. template<typename BasicJsonType, detail::enable_if_t<
  15784. not std::is_same<BasicJsonType, basic_json>::value and
  15785. detail::is_basic_json<BasicJsonType>::value, int> = 0>
  15786. BasicJsonType get() const
  15787. {
  15788. return *this;
  15789. }
  15790. /*!
  15791. @brief get a value (explicit)
  15792. Explicit type conversion between the JSON value and a compatible value
  15793. which is [CopyConstructible](https://en.cppreference.com/w/cpp/named_req/CopyConstructible)
  15794. and [DefaultConstructible](https://en.cppreference.com/w/cpp/named_req/DefaultConstructible).
  15795. The value is converted by calling the @ref json_serializer<ValueType>
  15796. `from_json()` method.
  15797. The function is equivalent to executing
  15798. @code {.cpp}
  15799. ValueType ret;
  15800. JSONSerializer<ValueType>::from_json(*this, ret);
  15801. return ret;
  15802. @endcode
  15803. This overloads is chosen if:
  15804. - @a ValueType is not @ref basic_json,
  15805. - @ref json_serializer<ValueType> has a `from_json()` method of the form
  15806. `void from_json(const basic_json&, ValueType&)`, and
  15807. - @ref json_serializer<ValueType> does not have a `from_json()` method of
  15808. the form `ValueType from_json(const basic_json&)`
  15809. @tparam ValueTypeCV the provided value type
  15810. @tparam ValueType the returned value type
  15811. @return copy of the JSON value, converted to @a ValueType
  15812. @throw what @ref json_serializer<ValueType> `from_json()` method throws
  15813. @liveexample{The example below shows several conversions from JSON values
  15814. to other types. There a few things to note: (1) Floating-point numbers can
  15815. be converted to integers\, (2) A JSON array can be converted to a standard
  15816. `std::vector<short>`\, (3) A JSON object can be converted to C++
  15817. associative containers such as `std::unordered_map<std::string\,
  15818. json>`.,get__ValueType_const}
  15819. @since version 2.1.0
  15820. */
  15821. template<typename ValueTypeCV, typename ValueType = detail::uncvref_t<ValueTypeCV>,
  15822. detail::enable_if_t <
  15823. not detail::is_basic_json<ValueType>::value and
  15824. detail::has_from_json<basic_json_t, ValueType>::value and
  15825. not detail::has_non_default_from_json<basic_json_t, ValueType>::value,
  15826. int> = 0>
  15827. ValueType get() const noexcept(noexcept(
  15828. JSONSerializer<ValueType>::from_json(std::declval<const basic_json_t&>(), std::declval<ValueType&>())))
  15829. {
  15830. // we cannot static_assert on ValueTypeCV being non-const, because
  15831. // there is support for get<const basic_json_t>(), which is why we
  15832. // still need the uncvref
  15833. static_assert(not std::is_reference<ValueTypeCV>::value,
  15834. "get() cannot be used with reference types, you might want to use get_ref()");
  15835. static_assert(std::is_default_constructible<ValueType>::value,
  15836. "types must be DefaultConstructible when used with get()");
  15837. ValueType ret;
  15838. JSONSerializer<ValueType>::from_json(*this, ret);
  15839. return ret;
  15840. }
  15841. /*!
  15842. @brief get a value (explicit); special case
  15843. Explicit type conversion between the JSON value and a compatible value
  15844. which is **not** [CopyConstructible](https://en.cppreference.com/w/cpp/named_req/CopyConstructible)
  15845. and **not** [DefaultConstructible](https://en.cppreference.com/w/cpp/named_req/DefaultConstructible).
  15846. The value is converted by calling the @ref json_serializer<ValueType>
  15847. `from_json()` method.
  15848. The function is equivalent to executing
  15849. @code {.cpp}
  15850. return JSONSerializer<ValueTypeCV>::from_json(*this);
  15851. @endcode
  15852. This overloads is chosen if:
  15853. - @a ValueType is not @ref basic_json and
  15854. - @ref json_serializer<ValueType> has a `from_json()` method of the form
  15855. `ValueType from_json(const basic_json&)`
  15856. @note If @ref json_serializer<ValueType> has both overloads of
  15857. `from_json()`, this one is chosen.
  15858. @tparam ValueTypeCV the provided value type
  15859. @tparam ValueType the returned value type
  15860. @return copy of the JSON value, converted to @a ValueType
  15861. @throw what @ref json_serializer<ValueType> `from_json()` method throws
  15862. @since version 2.1.0
  15863. */
  15864. template<typename ValueTypeCV, typename ValueType = detail::uncvref_t<ValueTypeCV>,
  15865. detail::enable_if_t<not std::is_same<basic_json_t, ValueType>::value and
  15866. detail::has_non_default_from_json<basic_json_t, ValueType>::value,
  15867. int> = 0>
  15868. ValueType get() const noexcept(noexcept(
  15869. JSONSerializer<ValueType>::from_json(std::declval<const basic_json_t&>())))
  15870. {
  15871. static_assert(not std::is_reference<ValueTypeCV>::value,
  15872. "get() cannot be used with reference types, you might want to use get_ref()");
  15873. return JSONSerializer<ValueType>::from_json(*this);
  15874. }
  15875. /*!
  15876. @brief get a value (explicit)
  15877. Explicit type conversion between the JSON value and a compatible value.
  15878. The value is filled into the input parameter by calling the @ref json_serializer<ValueType>
  15879. `from_json()` method.
  15880. The function is equivalent to executing
  15881. @code {.cpp}
  15882. ValueType v;
  15883. JSONSerializer<ValueType>::from_json(*this, v);
  15884. @endcode
  15885. This overloads is chosen if:
  15886. - @a ValueType is not @ref basic_json,
  15887. - @ref json_serializer<ValueType> has a `from_json()` method of the form
  15888. `void from_json(const basic_json&, ValueType&)`, and
  15889. @tparam ValueType the input parameter type.
  15890. @return the input parameter, allowing chaining calls.
  15891. @throw what @ref json_serializer<ValueType> `from_json()` method throws
  15892. @liveexample{The example below shows several conversions from JSON values
  15893. to other types. There a few things to note: (1) Floating-point numbers can
  15894. be converted to integers\, (2) A JSON array can be converted to a standard
  15895. `std::vector<short>`\, (3) A JSON object can be converted to C++
  15896. associative containers such as `std::unordered_map<std::string\,
  15897. json>`.,get_to}
  15898. @since version 3.3.0
  15899. */
  15900. template<typename ValueType,
  15901. detail::enable_if_t <
  15902. not detail::is_basic_json<ValueType>::value and
  15903. detail::has_from_json<basic_json_t, ValueType>::value,
  15904. int> = 0>
  15905. ValueType & get_to(ValueType& v) const noexcept(noexcept(
  15906. JSONSerializer<ValueType>::from_json(std::declval<const basic_json_t&>(), v)))
  15907. {
  15908. JSONSerializer<ValueType>::from_json(*this, v);
  15909. return v;
  15910. }
  15911. template <
  15912. typename T, std::size_t N,
  15913. typename Array = T (&)[N],
  15914. detail::enable_if_t <
  15915. detail::has_from_json<basic_json_t, Array>::value, int > = 0 >
  15916. Array get_to(T (&v)[N]) const
  15917. noexcept(noexcept(JSONSerializer<Array>::from_json(
  15918. std::declval<const basic_json_t&>(), v)))
  15919. {
  15920. JSONSerializer<Array>::from_json(*this, v);
  15921. return v;
  15922. }
  15923. /*!
  15924. @brief get a pointer value (implicit)
  15925. Implicit pointer access to the internally stored JSON value. No copies are
  15926. made.
  15927. @warning Writing data to the pointee of the result yields an undefined
  15928. state.
  15929. @tparam PointerType pointer type; must be a pointer to @ref array_t, @ref
  15930. object_t, @ref string_t, @ref boolean_t, @ref number_integer_t,
  15931. @ref number_unsigned_t, or @ref number_float_t. Enforced by a static
  15932. assertion.
  15933. @return pointer to the internally stored JSON value if the requested
  15934. pointer type @a PointerType fits to the JSON value; `nullptr` otherwise
  15935. @complexity Constant.
  15936. @liveexample{The example below shows how pointers to internal values of a
  15937. JSON value can be requested. Note that no type conversions are made and a
  15938. `nullptr` is returned if the value and the requested pointer type does not
  15939. match.,get_ptr}
  15940. @since version 1.0.0
  15941. */
  15942. template<typename PointerType, typename std::enable_if<
  15943. std::is_pointer<PointerType>::value, int>::type = 0>
  15944. auto get_ptr() noexcept -> decltype(std::declval<basic_json_t&>().get_impl_ptr(std::declval<PointerType>()))
  15945. {
  15946. // delegate the call to get_impl_ptr<>()
  15947. return get_impl_ptr(static_cast<PointerType>(nullptr));
  15948. }
  15949. /*!
  15950. @brief get a pointer value (implicit)
  15951. @copydoc get_ptr()
  15952. */
  15953. template<typename PointerType, typename std::enable_if<
  15954. std::is_pointer<PointerType>::value and
  15955. std::is_const<typename std::remove_pointer<PointerType>::type>::value, int>::type = 0>
  15956. constexpr auto get_ptr() const noexcept -> decltype(std::declval<const basic_json_t&>().get_impl_ptr(std::declval<PointerType>()))
  15957. {
  15958. // delegate the call to get_impl_ptr<>() const
  15959. return get_impl_ptr(static_cast<PointerType>(nullptr));
  15960. }
  15961. /*!
  15962. @brief get a pointer value (explicit)
  15963. Explicit pointer access to the internally stored JSON value. No copies are
  15964. made.
  15965. @warning The pointer becomes invalid if the underlying JSON object
  15966. changes.
  15967. @tparam PointerType pointer type; must be a pointer to @ref array_t, @ref
  15968. object_t, @ref string_t, @ref boolean_t, @ref number_integer_t,
  15969. @ref number_unsigned_t, or @ref number_float_t.
  15970. @return pointer to the internally stored JSON value if the requested
  15971. pointer type @a PointerType fits to the JSON value; `nullptr` otherwise
  15972. @complexity Constant.
  15973. @liveexample{The example below shows how pointers to internal values of a
  15974. JSON value can be requested. Note that no type conversions are made and a
  15975. `nullptr` is returned if the value and the requested pointer type does not
  15976. match.,get__PointerType}
  15977. @sa @ref get_ptr() for explicit pointer-member access
  15978. @since version 1.0.0
  15979. */
  15980. template<typename PointerType, typename std::enable_if<
  15981. std::is_pointer<PointerType>::value, int>::type = 0>
  15982. auto get() noexcept -> decltype(std::declval<basic_json_t&>().template get_ptr<PointerType>())
  15983. {
  15984. // delegate the call to get_ptr
  15985. return get_ptr<PointerType>();
  15986. }
  15987. /*!
  15988. @brief get a pointer value (explicit)
  15989. @copydoc get()
  15990. */
  15991. template<typename PointerType, typename std::enable_if<
  15992. std::is_pointer<PointerType>::value, int>::type = 0>
  15993. constexpr auto get() const noexcept -> decltype(std::declval<const basic_json_t&>().template get_ptr<PointerType>())
  15994. {
  15995. // delegate the call to get_ptr
  15996. return get_ptr<PointerType>();
  15997. }
  15998. /*!
  15999. @brief get a reference value (implicit)
  16000. Implicit reference access to the internally stored JSON value. No copies
  16001. are made.
  16002. @warning Writing data to the referee of the result yields an undefined
  16003. state.
  16004. @tparam ReferenceType reference type; must be a reference to @ref array_t,
  16005. @ref object_t, @ref string_t, @ref boolean_t, @ref number_integer_t, or
  16006. @ref number_float_t. Enforced by static assertion.
  16007. @return reference to the internally stored JSON value if the requested
  16008. reference type @a ReferenceType fits to the JSON value; throws
  16009. type_error.303 otherwise
  16010. @throw type_error.303 in case passed type @a ReferenceType is incompatible
  16011. with the stored JSON value; see example below
  16012. @complexity Constant.
  16013. @liveexample{The example shows several calls to `get_ref()`.,get_ref}
  16014. @since version 1.1.0
  16015. */
  16016. template<typename ReferenceType, typename std::enable_if<
  16017. std::is_reference<ReferenceType>::value, int>::type = 0>
  16018. ReferenceType get_ref()
  16019. {
  16020. // delegate call to get_ref_impl
  16021. return get_ref_impl<ReferenceType>(*this);
  16022. }
  16023. /*!
  16024. @brief get a reference value (implicit)
  16025. @copydoc get_ref()
  16026. */
  16027. template<typename ReferenceType, typename std::enable_if<
  16028. std::is_reference<ReferenceType>::value and
  16029. std::is_const<typename std::remove_reference<ReferenceType>::type>::value, int>::type = 0>
  16030. ReferenceType get_ref() const
  16031. {
  16032. // delegate call to get_ref_impl
  16033. return get_ref_impl<ReferenceType>(*this);
  16034. }
  16035. /*!
  16036. @brief get a value (implicit)
  16037. Implicit type conversion between the JSON value and a compatible value.
  16038. The call is realized by calling @ref get() const.
  16039. @tparam ValueType non-pointer type compatible to the JSON value, for
  16040. instance `int` for JSON integer numbers, `bool` for JSON booleans, or
  16041. `std::vector` types for JSON arrays. The character type of @ref string_t
  16042. as well as an initializer list of this type is excluded to avoid
  16043. ambiguities as these types implicitly convert to `std::string`.
  16044. @return copy of the JSON value, converted to type @a ValueType
  16045. @throw type_error.302 in case passed type @a ValueType is incompatible
  16046. to the JSON value type (e.g., the JSON value is of type boolean, but a
  16047. string is requested); see example below
  16048. @complexity Linear in the size of the JSON value.
  16049. @liveexample{The example below shows several conversions from JSON values
  16050. to other types. There a few things to note: (1) Floating-point numbers can
  16051. be converted to integers\, (2) A JSON array can be converted to a standard
  16052. `std::vector<short>`\, (3) A JSON object can be converted to C++
  16053. associative containers such as `std::unordered_map<std::string\,
  16054. json>`.,operator__ValueType}
  16055. @since version 1.0.0
  16056. */
  16057. template < typename ValueType, typename std::enable_if <
  16058. not std::is_pointer<ValueType>::value and
  16059. not std::is_same<ValueType, detail::json_ref<basic_json>>::value and
  16060. not std::is_same<ValueType, typename string_t::value_type>::value and
  16061. not detail::is_basic_json<ValueType>::value
  16062. and not std::is_same<ValueType, std::initializer_list<typename string_t::value_type>>::value
  16063. #if defined(JSON_HAS_CPP_17) && (defined(__GNUC__) || (defined(_MSC_VER) and _MSC_VER <= 1914))
  16064. and not std::is_same<ValueType, typename std::string_view>::value
  16065. #endif
  16066. and detail::is_detected<detail::get_template_function, const basic_json_t&, ValueType>::value
  16067. , int >::type = 0 >
  16068. operator ValueType() const
  16069. {
  16070. // delegate the call to get<>() const
  16071. return get<ValueType>();
  16072. }
  16073. /// @}
  16074. ////////////////////
  16075. // element access //
  16076. ////////////////////
  16077. /// @name element access
  16078. /// Access to the JSON value.
  16079. /// @{
  16080. /*!
  16081. @brief access specified array element with bounds checking
  16082. Returns a reference to the element at specified location @a idx, with
  16083. bounds checking.
  16084. @param[in] idx index of the element to access
  16085. @return reference to the element at index @a idx
  16086. @throw type_error.304 if the JSON value is not an array; in this case,
  16087. calling `at` with an index makes no sense. See example below.
  16088. @throw out_of_range.401 if the index @a idx is out of range of the array;
  16089. that is, `idx >= size()`. See example below.
  16090. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  16091. changes in the JSON value.
  16092. @complexity Constant.
  16093. @since version 1.0.0
  16094. @liveexample{The example below shows how array elements can be read and
  16095. written using `at()`. It also demonstrates the different exceptions that
  16096. can be thrown.,at__size_type}
  16097. */
  16098. reference at(size_type idx)
  16099. {
  16100. // at only works for arrays
  16101. if (JSON_HEDLEY_LIKELY(is_array()))
  16102. {
  16103. JSON_TRY
  16104. {
  16105. return m_value.array->at(idx);
  16106. }
  16107. JSON_CATCH (std::out_of_range&)
  16108. {
  16109. // create better exception explanation
  16110. JSON_THROW(out_of_range::create(401, "array index " + std::to_string(idx) + " is out of range"));
  16111. }
  16112. }
  16113. else
  16114. {
  16115. JSON_THROW(type_error::create(304, "cannot use at() with " + std::string(type_name())));
  16116. }
  16117. }
  16118. /*!
  16119. @brief access specified array element with bounds checking
  16120. Returns a const reference to the element at specified location @a idx,
  16121. with bounds checking.
  16122. @param[in] idx index of the element to access
  16123. @return const reference to the element at index @a idx
  16124. @throw type_error.304 if the JSON value is not an array; in this case,
  16125. calling `at` with an index makes no sense. See example below.
  16126. @throw out_of_range.401 if the index @a idx is out of range of the array;
  16127. that is, `idx >= size()`. See example below.
  16128. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  16129. changes in the JSON value.
  16130. @complexity Constant.
  16131. @since version 1.0.0
  16132. @liveexample{The example below shows how array elements can be read using
  16133. `at()`. It also demonstrates the different exceptions that can be thrown.,
  16134. at__size_type_const}
  16135. */
  16136. const_reference at(size_type idx) const
  16137. {
  16138. // at only works for arrays
  16139. if (JSON_HEDLEY_LIKELY(is_array()))
  16140. {
  16141. JSON_TRY
  16142. {
  16143. return m_value.array->at(idx);
  16144. }
  16145. JSON_CATCH (std::out_of_range&)
  16146. {
  16147. // create better exception explanation
  16148. JSON_THROW(out_of_range::create(401, "array index " + std::to_string(idx) + " is out of range"));
  16149. }
  16150. }
  16151. else
  16152. {
  16153. JSON_THROW(type_error::create(304, "cannot use at() with " + std::string(type_name())));
  16154. }
  16155. }
  16156. /*!
  16157. @brief access specified object element with bounds checking
  16158. Returns a reference to the element at with specified key @a key, with
  16159. bounds checking.
  16160. @param[in] key key of the element to access
  16161. @return reference to the element at key @a key
  16162. @throw type_error.304 if the JSON value is not an object; in this case,
  16163. calling `at` with a key makes no sense. See example below.
  16164. @throw out_of_range.403 if the key @a key is is not stored in the object;
  16165. that is, `find(key) == end()`. See example below.
  16166. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  16167. changes in the JSON value.
  16168. @complexity Logarithmic in the size of the container.
  16169. @sa @ref operator[](const typename object_t::key_type&) for unchecked
  16170. access by reference
  16171. @sa @ref value() for access by value with a default value
  16172. @since version 1.0.0
  16173. @liveexample{The example below shows how object elements can be read and
  16174. written using `at()`. It also demonstrates the different exceptions that
  16175. can be thrown.,at__object_t_key_type}
  16176. */
  16177. reference at(const typename object_t::key_type& key)
  16178. {
  16179. // at only works for objects
  16180. if (JSON_HEDLEY_LIKELY(is_object()))
  16181. {
  16182. JSON_TRY
  16183. {
  16184. return m_value.object->at(key);
  16185. }
  16186. JSON_CATCH (std::out_of_range&)
  16187. {
  16188. // create better exception explanation
  16189. JSON_THROW(out_of_range::create(403, "key '" + key + "' not found"));
  16190. }
  16191. }
  16192. else
  16193. {
  16194. JSON_THROW(type_error::create(304, "cannot use at() with " + std::string(type_name())));
  16195. }
  16196. }
  16197. /*!
  16198. @brief access specified object element with bounds checking
  16199. Returns a const reference to the element at with specified key @a key,
  16200. with bounds checking.
  16201. @param[in] key key of the element to access
  16202. @return const reference to the element at key @a key
  16203. @throw type_error.304 if the JSON value is not an object; in this case,
  16204. calling `at` with a key makes no sense. See example below.
  16205. @throw out_of_range.403 if the key @a key is is not stored in the object;
  16206. that is, `find(key) == end()`. See example below.
  16207. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  16208. changes in the JSON value.
  16209. @complexity Logarithmic in the size of the container.
  16210. @sa @ref operator[](const typename object_t::key_type&) for unchecked
  16211. access by reference
  16212. @sa @ref value() for access by value with a default value
  16213. @since version 1.0.0
  16214. @liveexample{The example below shows how object elements can be read using
  16215. `at()`. It also demonstrates the different exceptions that can be thrown.,
  16216. at__object_t_key_type_const}
  16217. */
  16218. const_reference at(const typename object_t::key_type& key) const
  16219. {
  16220. // at only works for objects
  16221. if (JSON_HEDLEY_LIKELY(is_object()))
  16222. {
  16223. JSON_TRY
  16224. {
  16225. return m_value.object->at(key);
  16226. }
  16227. JSON_CATCH (std::out_of_range&)
  16228. {
  16229. // create better exception explanation
  16230. JSON_THROW(out_of_range::create(403, "key '" + key + "' not found"));
  16231. }
  16232. }
  16233. else
  16234. {
  16235. JSON_THROW(type_error::create(304, "cannot use at() with " + std::string(type_name())));
  16236. }
  16237. }
  16238. /*!
  16239. @brief access specified array element
  16240. Returns a reference to the element at specified location @a idx.
  16241. @note If @a idx is beyond the range of the array (i.e., `idx >= size()`),
  16242. then the array is silently filled up with `null` values to make `idx` a
  16243. valid reference to the last stored element.
  16244. @param[in] idx index of the element to access
  16245. @return reference to the element at index @a idx
  16246. @throw type_error.305 if the JSON value is not an array or null; in that
  16247. cases, using the [] operator with an index makes no sense.
  16248. @complexity Constant if @a idx is in the range of the array. Otherwise
  16249. linear in `idx - size()`.
  16250. @liveexample{The example below shows how array elements can be read and
  16251. written using `[]` operator. Note the addition of `null`
  16252. values.,operatorarray__size_type}
  16253. @since version 1.0.0
  16254. */
  16255. reference operator[](size_type idx)
  16256. {
  16257. // implicitly convert null value to an empty array
  16258. if (is_null())
  16259. {
  16260. m_type = value_t::array;
  16261. m_value.array = create<array_t>();
  16262. assert_invariant();
  16263. }
  16264. // operator[] only works for arrays
  16265. if (JSON_HEDLEY_LIKELY(is_array()))
  16266. {
  16267. // fill up array with null values if given idx is outside range
  16268. if (idx >= m_value.array->size())
  16269. {
  16270. m_value.array->insert(m_value.array->end(),
  16271. idx - m_value.array->size() + 1,
  16272. basic_json());
  16273. }
  16274. return m_value.array->operator[](idx);
  16275. }
  16276. JSON_THROW(type_error::create(305, "cannot use operator[] with a numeric argument with " + std::string(type_name())));
  16277. }
  16278. /*!
  16279. @brief access specified array element
  16280. Returns a const reference to the element at specified location @a idx.
  16281. @param[in] idx index of the element to access
  16282. @return const reference to the element at index @a idx
  16283. @throw type_error.305 if the JSON value is not an array; in that case,
  16284. using the [] operator with an index makes no sense.
  16285. @complexity Constant.
  16286. @liveexample{The example below shows how array elements can be read using
  16287. the `[]` operator.,operatorarray__size_type_const}
  16288. @since version 1.0.0
  16289. */
  16290. const_reference operator[](size_type idx) const
  16291. {
  16292. // const operator[] only works for arrays
  16293. if (JSON_HEDLEY_LIKELY(is_array()))
  16294. {
  16295. return m_value.array->operator[](idx);
  16296. }
  16297. JSON_THROW(type_error::create(305, "cannot use operator[] with a numeric argument with " + std::string(type_name())));
  16298. }
  16299. /*!
  16300. @brief access specified object element
  16301. Returns a reference to the element at with specified key @a key.
  16302. @note If @a key is not found in the object, then it is silently added to
  16303. the object and filled with a `null` value to make `key` a valid reference.
  16304. In case the value was `null` before, it is converted to an object.
  16305. @param[in] key key of the element to access
  16306. @return reference to the element at key @a key
  16307. @throw type_error.305 if the JSON value is not an object or null; in that
  16308. cases, using the [] operator with a key makes no sense.
  16309. @complexity Logarithmic in the size of the container.
  16310. @liveexample{The example below shows how object elements can be read and
  16311. written using the `[]` operator.,operatorarray__key_type}
  16312. @sa @ref at(const typename object_t::key_type&) for access by reference
  16313. with range checking
  16314. @sa @ref value() for access by value with a default value
  16315. @since version 1.0.0
  16316. */
  16317. reference operator[](const typename object_t::key_type& key)
  16318. {
  16319. // implicitly convert null value to an empty object
  16320. if (is_null())
  16321. {
  16322. m_type = value_t::object;
  16323. m_value.object = create<object_t>();
  16324. assert_invariant();
  16325. }
  16326. // operator[] only works for objects
  16327. if (JSON_HEDLEY_LIKELY(is_object()))
  16328. {
  16329. return m_value.object->operator[](key);
  16330. }
  16331. JSON_THROW(type_error::create(305, "cannot use operator[] with a string argument with " + std::string(type_name())));
  16332. }
  16333. /*!
  16334. @brief read-only access specified object element
  16335. Returns a const reference to the element at with specified key @a key. No
  16336. bounds checking is performed.
  16337. @warning If the element with key @a key does not exist, the behavior is
  16338. undefined.
  16339. @param[in] key key of the element to access
  16340. @return const reference to the element at key @a key
  16341. @pre The element with key @a key must exist. **This precondition is
  16342. enforced with an assertion.**
  16343. @throw type_error.305 if the JSON value is not an object; in that case,
  16344. using the [] operator with a key makes no sense.
  16345. @complexity Logarithmic in the size of the container.
  16346. @liveexample{The example below shows how object elements can be read using
  16347. the `[]` operator.,operatorarray__key_type_const}
  16348. @sa @ref at(const typename object_t::key_type&) for access by reference
  16349. with range checking
  16350. @sa @ref value() for access by value with a default value
  16351. @since version 1.0.0
  16352. */
  16353. const_reference operator[](const typename object_t::key_type& key) const
  16354. {
  16355. // const operator[] only works for objects
  16356. if (JSON_HEDLEY_LIKELY(is_object()))
  16357. {
  16358. assert(m_value.object->find(key) != m_value.object->end());
  16359. return m_value.object->find(key)->second;
  16360. }
  16361. JSON_THROW(type_error::create(305, "cannot use operator[] with a string argument with " + std::string(type_name())));
  16362. }
  16363. /*!
  16364. @brief access specified object element
  16365. Returns a reference to the element at with specified key @a key.
  16366. @note If @a key is not found in the object, then it is silently added to
  16367. the object and filled with a `null` value to make `key` a valid reference.
  16368. In case the value was `null` before, it is converted to an object.
  16369. @param[in] key key of the element to access
  16370. @return reference to the element at key @a key
  16371. @throw type_error.305 if the JSON value is not an object or null; in that
  16372. cases, using the [] operator with a key makes no sense.
  16373. @complexity Logarithmic in the size of the container.
  16374. @liveexample{The example below shows how object elements can be read and
  16375. written using the `[]` operator.,operatorarray__key_type}
  16376. @sa @ref at(const typename object_t::key_type&) for access by reference
  16377. with range checking
  16378. @sa @ref value() for access by value with a default value
  16379. @since version 1.1.0
  16380. */
  16381. template<typename T>
  16382. JSON_HEDLEY_NON_NULL(2)
  16383. reference operator[](T* key)
  16384. {
  16385. // implicitly convert null to object
  16386. if (is_null())
  16387. {
  16388. m_type = value_t::object;
  16389. m_value = value_t::object;
  16390. assert_invariant();
  16391. }
  16392. // at only works for objects
  16393. if (JSON_HEDLEY_LIKELY(is_object()))
  16394. {
  16395. return m_value.object->operator[](key);
  16396. }
  16397. JSON_THROW(type_error::create(305, "cannot use operator[] with a string argument with " + std::string(type_name())));
  16398. }
  16399. /*!
  16400. @brief read-only access specified object element
  16401. Returns a const reference to the element at with specified key @a key. No
  16402. bounds checking is performed.
  16403. @warning If the element with key @a key does not exist, the behavior is
  16404. undefined.
  16405. @param[in] key key of the element to access
  16406. @return const reference to the element at key @a key
  16407. @pre The element with key @a key must exist. **This precondition is
  16408. enforced with an assertion.**
  16409. @throw type_error.305 if the JSON value is not an object; in that case,
  16410. using the [] operator with a key makes no sense.
  16411. @complexity Logarithmic in the size of the container.
  16412. @liveexample{The example below shows how object elements can be read using
  16413. the `[]` operator.,operatorarray__key_type_const}
  16414. @sa @ref at(const typename object_t::key_type&) for access by reference
  16415. with range checking
  16416. @sa @ref value() for access by value with a default value
  16417. @since version 1.1.0
  16418. */
  16419. template<typename T>
  16420. JSON_HEDLEY_NON_NULL(2)
  16421. const_reference operator[](T* key) const
  16422. {
  16423. // at only works for objects
  16424. if (JSON_HEDLEY_LIKELY(is_object()))
  16425. {
  16426. assert(m_value.object->find(key) != m_value.object->end());
  16427. return m_value.object->find(key)->second;
  16428. }
  16429. JSON_THROW(type_error::create(305, "cannot use operator[] with a string argument with " + std::string(type_name())));
  16430. }
  16431. /*!
  16432. @brief access specified object element with default value
  16433. Returns either a copy of an object's element at the specified key @a key
  16434. or a given default value if no element with key @a key exists.
  16435. The function is basically equivalent to executing
  16436. @code {.cpp}
  16437. try {
  16438. return at(key);
  16439. } catch(out_of_range) {
  16440. return default_value;
  16441. }
  16442. @endcode
  16443. @note Unlike @ref at(const typename object_t::key_type&), this function
  16444. does not throw if the given key @a key was not found.
  16445. @note Unlike @ref operator[](const typename object_t::key_type& key), this
  16446. function does not implicitly add an element to the position defined by @a
  16447. key. This function is furthermore also applicable to const objects.
  16448. @param[in] key key of the element to access
  16449. @param[in] default_value the value to return if @a key is not found
  16450. @tparam ValueType type compatible to JSON values, for instance `int` for
  16451. JSON integer numbers, `bool` for JSON booleans, or `std::vector` types for
  16452. JSON arrays. Note the type of the expected value at @a key and the default
  16453. value @a default_value must be compatible.
  16454. @return copy of the element at key @a key or @a default_value if @a key
  16455. is not found
  16456. @throw type_error.302 if @a default_value does not match the type of the
  16457. value at @a key
  16458. @throw type_error.306 if the JSON value is not an object; in that case,
  16459. using `value()` with a key makes no sense.
  16460. @complexity Logarithmic in the size of the container.
  16461. @liveexample{The example below shows how object elements can be queried
  16462. with a default value.,basic_json__value}
  16463. @sa @ref at(const typename object_t::key_type&) for access by reference
  16464. with range checking
  16465. @sa @ref operator[](const typename object_t::key_type&) for unchecked
  16466. access by reference
  16467. @since version 1.0.0
  16468. */
  16469. template<class ValueType, typename std::enable_if<
  16470. std::is_convertible<basic_json_t, ValueType>::value, int>::type = 0>
  16471. ValueType value(const typename object_t::key_type& key, const ValueType& default_value) const
  16472. {
  16473. // at only works for objects
  16474. if (JSON_HEDLEY_LIKELY(is_object()))
  16475. {
  16476. // if key is found, return value and given default value otherwise
  16477. const auto it = find(key);
  16478. if (it != end())
  16479. {
  16480. return *it;
  16481. }
  16482. return default_value;
  16483. }
  16484. JSON_THROW(type_error::create(306, "cannot use value() with " + std::string(type_name())));
  16485. }
  16486. /*!
  16487. @brief overload for a default value of type const char*
  16488. @copydoc basic_json::value(const typename object_t::key_type&, const ValueType&) const
  16489. */
  16490. string_t value(const typename object_t::key_type& key, const char* default_value) const
  16491. {
  16492. return value(key, string_t(default_value));
  16493. }
  16494. /*!
  16495. @brief access specified object element via JSON Pointer with default value
  16496. Returns either a copy of an object's element at the specified key @a key
  16497. or a given default value if no element with key @a key exists.
  16498. The function is basically equivalent to executing
  16499. @code {.cpp}
  16500. try {
  16501. return at(ptr);
  16502. } catch(out_of_range) {
  16503. return default_value;
  16504. }
  16505. @endcode
  16506. @note Unlike @ref at(const json_pointer&), this function does not throw
  16507. if the given key @a key was not found.
  16508. @param[in] ptr a JSON pointer to the element to access
  16509. @param[in] default_value the value to return if @a ptr found no value
  16510. @tparam ValueType type compatible to JSON values, for instance `int` for
  16511. JSON integer numbers, `bool` for JSON booleans, or `std::vector` types for
  16512. JSON arrays. Note the type of the expected value at @a key and the default
  16513. value @a default_value must be compatible.
  16514. @return copy of the element at key @a key or @a default_value if @a key
  16515. is not found
  16516. @throw type_error.302 if @a default_value does not match the type of the
  16517. value at @a ptr
  16518. @throw type_error.306 if the JSON value is not an object; in that case,
  16519. using `value()` with a key makes no sense.
  16520. @complexity Logarithmic in the size of the container.
  16521. @liveexample{The example below shows how object elements can be queried
  16522. with a default value.,basic_json__value_ptr}
  16523. @sa @ref operator[](const json_pointer&) for unchecked access by reference
  16524. @since version 2.0.2
  16525. */
  16526. template<class ValueType, typename std::enable_if<
  16527. std::is_convertible<basic_json_t, ValueType>::value, int>::type = 0>
  16528. ValueType value(const json_pointer& ptr, const ValueType& default_value) const
  16529. {
  16530. // at only works for objects
  16531. if (JSON_HEDLEY_LIKELY(is_object()))
  16532. {
  16533. // if pointer resolves a value, return it or use default value
  16534. JSON_TRY
  16535. {
  16536. return ptr.get_checked(this);
  16537. }
  16538. JSON_INTERNAL_CATCH (out_of_range&)
  16539. {
  16540. return default_value;
  16541. }
  16542. }
  16543. JSON_THROW(type_error::create(306, "cannot use value() with " + std::string(type_name())));
  16544. }
  16545. /*!
  16546. @brief overload for a default value of type const char*
  16547. @copydoc basic_json::value(const json_pointer&, ValueType) const
  16548. */
  16549. JSON_HEDLEY_NON_NULL(3)
  16550. string_t value(const json_pointer& ptr, const char* default_value) const
  16551. {
  16552. return value(ptr, string_t(default_value));
  16553. }
  16554. /*!
  16555. @brief return the binary subtype
  16556. Returns the numerical subtype of the JSON value, if the JSON value is of
  16557. type "binary", and it has a subtype. If it does not have a subtype (or the
  16558. object is not of type binary) this function will return size_t(-1) as a
  16559. sentinel value.
  16560. @return the numerical subtype of the binary JSON value
  16561. @complexity Constant.
  16562. @exceptionsafety No-throw guarantee: this member function never throws
  16563. exceptions.
  16564. @sa @ref set_subtype() -- sets the binary subtype
  16565. @sa @ref clear_subtype() -- clears the binary subtype
  16566. @sa @ref has_subtype() -- returns whether or not the binary value has a
  16567. subtype
  16568. @since version 3.8.0
  16569. */
  16570. std::size_t get_subtype() const noexcept
  16571. {
  16572. if (is_binary() and m_value.binary->has_subtype)
  16573. {
  16574. return m_value.binary->subtype;
  16575. }
  16576. return std::size_t(-1);
  16577. }
  16578. /*!
  16579. @brief sets the binary subtype
  16580. Sets the binary subtype of the JSON value, also flags a binary JSON value as
  16581. having a subtype, which has implications for serialization to msgpack (will
  16582. prefer ext file formats over bin). If the JSON value is not a binary value,
  16583. this function does nothing.
  16584. @complexity Constant.
  16585. @exceptionsafety No-throw guarantee: this member function never throws
  16586. exceptions.
  16587. @sa @ref get_subtype() -- return the binary subtype
  16588. @sa @ref clear_subtype() -- clears the binary subtype
  16589. @sa @ref has_subtype() -- returns whether or not the binary value has a
  16590. subtype
  16591. @since version 3.8.0
  16592. */
  16593. void set_subtype(std::uint8_t subtype) noexcept
  16594. {
  16595. if (is_binary())
  16596. {
  16597. m_value.binary->has_subtype = true;
  16598. m_value.binary->subtype = subtype;
  16599. }
  16600. }
  16601. /*!
  16602. @brief clears the binary subtype
  16603. Clears the binary subtype of the JSON value, also flags a binary JSON value
  16604. as not having a subtype, which has implications for serialization to msgpack
  16605. (will prefer bin file formats over ext). If the JSON value is not a binary
  16606. value, this function does nothing.
  16607. @complexity Constant.
  16608. @exceptionsafety No-throw guarantee: this member function never throws
  16609. exceptions.
  16610. @sa @ref get_subtype() -- return the binary subtype
  16611. @sa @ref set_subtype() -- sets the binary subtype
  16612. @sa @ref has_subtype() -- returns whether or not the binary value has a
  16613. subtype
  16614. @since version 3.8.0
  16615. */
  16616. void clear_subtype() noexcept
  16617. {
  16618. if (is_binary())
  16619. {
  16620. m_value.binary->has_subtype = false;
  16621. m_value.binary->subtype = 0;
  16622. }
  16623. }
  16624. /*!
  16625. @brief return whether or not the binary subtype has a value
  16626. Returns whether or not the binary subtype has a value.
  16627. @return whether or not the binary subtype has a value.
  16628. @complexity Constant.
  16629. @exceptionsafety No-throw guarantee: this member function never throws
  16630. exceptions.
  16631. @sa @ref get_subtype() -- return the binary subtype
  16632. @sa @ref set_subtype() -- sets the binary subtype
  16633. @sa @ref clear_subtype() -- clears the binary subtype
  16634. @since version 3.8.0
  16635. */
  16636. bool has_subtype() const noexcept
  16637. {
  16638. return is_binary() and m_value.binary->has_subtype;
  16639. }
  16640. /*!
  16641. @brief access the first element
  16642. Returns a reference to the first element in the container. For a JSON
  16643. container `c`, the expression `c.front()` is equivalent to `*c.begin()`.
  16644. @return In case of a structured type (array or object), a reference to the
  16645. first element is returned. In case of number, string, boolean, or binary
  16646. values, a reference to the value is returned.
  16647. @complexity Constant.
  16648. @pre The JSON value must not be `null` (would throw `std::out_of_range`)
  16649. or an empty array or object (undefined behavior, **guarded by
  16650. assertions**).
  16651. @post The JSON value remains unchanged.
  16652. @throw invalid_iterator.214 when called on `null` value
  16653. @liveexample{The following code shows an example for `front()`.,front}
  16654. @sa @ref back() -- access the last element
  16655. @since version 1.0.0
  16656. */
  16657. reference front()
  16658. {
  16659. return *begin();
  16660. }
  16661. /*!
  16662. @copydoc basic_json::front()
  16663. */
  16664. const_reference front() const
  16665. {
  16666. return *cbegin();
  16667. }
  16668. /*!
  16669. @brief access the last element
  16670. Returns a reference to the last element in the container. For a JSON
  16671. container `c`, the expression `c.back()` is equivalent to
  16672. @code {.cpp}
  16673. auto tmp = c.end();
  16674. --tmp;
  16675. return *tmp;
  16676. @endcode
  16677. @return In case of a structured type (array or object), a reference to the
  16678. last element is returned. In case of number, string, boolean, or binary
  16679. values, a reference to the value is returned.
  16680. @complexity Constant.
  16681. @pre The JSON value must not be `null` (would throw `std::out_of_range`)
  16682. or an empty array or object (undefined behavior, **guarded by
  16683. assertions**).
  16684. @post The JSON value remains unchanged.
  16685. @throw invalid_iterator.214 when called on a `null` value. See example
  16686. below.
  16687. @liveexample{The following code shows an example for `back()`.,back}
  16688. @sa @ref front() -- access the first element
  16689. @since version 1.0.0
  16690. */
  16691. reference back()
  16692. {
  16693. auto tmp = end();
  16694. --tmp;
  16695. return *tmp;
  16696. }
  16697. /*!
  16698. @copydoc basic_json::back()
  16699. */
  16700. const_reference back() const
  16701. {
  16702. auto tmp = cend();
  16703. --tmp;
  16704. return *tmp;
  16705. }
  16706. /*!
  16707. @brief remove element given an iterator
  16708. Removes the element specified by iterator @a pos. The iterator @a pos must
  16709. be valid and dereferenceable. Thus the `end()` iterator (which is valid,
  16710. but is not dereferenceable) cannot be used as a value for @a pos.
  16711. If called on a primitive type other than `null`, the resulting JSON value
  16712. will be `null`.
  16713. @param[in] pos iterator to the element to remove
  16714. @return Iterator following the last removed element. If the iterator @a
  16715. pos refers to the last element, the `end()` iterator is returned.
  16716. @tparam IteratorType an @ref iterator or @ref const_iterator
  16717. @post Invalidates iterators and references at or after the point of the
  16718. erase, including the `end()` iterator.
  16719. @throw type_error.307 if called on a `null` value; example: `"cannot use
  16720. erase() with null"`
  16721. @throw invalid_iterator.202 if called on an iterator which does not belong
  16722. to the current JSON value; example: `"iterator does not fit current
  16723. value"`
  16724. @throw invalid_iterator.205 if called on a primitive type with invalid
  16725. iterator (i.e., any iterator which is not `begin()`); example: `"iterator
  16726. out of range"`
  16727. @complexity The complexity depends on the type:
  16728. - objects: amortized constant
  16729. - arrays: linear in distance between @a pos and the end of the container
  16730. - strings and binary: linear in the length of the member
  16731. - other types: constant
  16732. @liveexample{The example shows the result of `erase()` for different JSON
  16733. types.,erase__IteratorType}
  16734. @sa @ref erase(IteratorType, IteratorType) -- removes the elements in
  16735. the given range
  16736. @sa @ref erase(const typename object_t::key_type&) -- removes the element
  16737. from an object at the given key
  16738. @sa @ref erase(const size_type) -- removes the element from an array at
  16739. the given index
  16740. @since version 1.0.0
  16741. */
  16742. template<class IteratorType, typename std::enable_if<
  16743. std::is_same<IteratorType, typename basic_json_t::iterator>::value or
  16744. std::is_same<IteratorType, typename basic_json_t::const_iterator>::value, int>::type
  16745. = 0>
  16746. IteratorType erase(IteratorType pos)
  16747. {
  16748. // make sure iterator fits the current value
  16749. if (JSON_HEDLEY_UNLIKELY(this != pos.m_object))
  16750. {
  16751. JSON_THROW(invalid_iterator::create(202, "iterator does not fit current value"));
  16752. }
  16753. IteratorType result = end();
  16754. switch (m_type)
  16755. {
  16756. case value_t::boolean:
  16757. case value_t::number_float:
  16758. case value_t::number_integer:
  16759. case value_t::number_unsigned:
  16760. case value_t::string:
  16761. case value_t::binary:
  16762. {
  16763. if (JSON_HEDLEY_UNLIKELY(not pos.m_it.primitive_iterator.is_begin()))
  16764. {
  16765. JSON_THROW(invalid_iterator::create(205, "iterator out of range"));
  16766. }
  16767. if (is_string())
  16768. {
  16769. AllocatorType<string_t> alloc;
  16770. std::allocator_traits<decltype(alloc)>::destroy(alloc, m_value.string);
  16771. std::allocator_traits<decltype(alloc)>::deallocate(alloc, m_value.string, 1);
  16772. m_value.string = nullptr;
  16773. }
  16774. else if (is_binary())
  16775. {
  16776. AllocatorType<internal_binary_t> alloc;
  16777. std::allocator_traits<decltype(alloc)>::destroy(alloc, m_value.binary);
  16778. std::allocator_traits<decltype(alloc)>::deallocate(alloc, m_value.binary, 1);
  16779. m_value.binary = nullptr;
  16780. }
  16781. m_type = value_t::null;
  16782. assert_invariant();
  16783. break;
  16784. }
  16785. case value_t::object:
  16786. {
  16787. result.m_it.object_iterator = m_value.object->erase(pos.m_it.object_iterator);
  16788. break;
  16789. }
  16790. case value_t::array:
  16791. {
  16792. result.m_it.array_iterator = m_value.array->erase(pos.m_it.array_iterator);
  16793. break;
  16794. }
  16795. default:
  16796. JSON_THROW(type_error::create(307, "cannot use erase() with " + std::string(type_name())));
  16797. }
  16798. return result;
  16799. }
  16800. /*!
  16801. @brief remove elements given an iterator range
  16802. Removes the element specified by the range `[first; last)`. The iterator
  16803. @a first does not need to be dereferenceable if `first == last`: erasing
  16804. an empty range is a no-op.
  16805. If called on a primitive type other than `null`, the resulting JSON value
  16806. will be `null`.
  16807. @param[in] first iterator to the beginning of the range to remove
  16808. @param[in] last iterator past the end of the range to remove
  16809. @return Iterator following the last removed element. If the iterator @a
  16810. second refers to the last element, the `end()` iterator is returned.
  16811. @tparam IteratorType an @ref iterator or @ref const_iterator
  16812. @post Invalidates iterators and references at or after the point of the
  16813. erase, including the `end()` iterator.
  16814. @throw type_error.307 if called on a `null` value; example: `"cannot use
  16815. erase() with null"`
  16816. @throw invalid_iterator.203 if called on iterators which does not belong
  16817. to the current JSON value; example: `"iterators do not fit current value"`
  16818. @throw invalid_iterator.204 if called on a primitive type with invalid
  16819. iterators (i.e., if `first != begin()` and `last != end()`); example:
  16820. `"iterators out of range"`
  16821. @complexity The complexity depends on the type:
  16822. - objects: `log(size()) + std::distance(first, last)`
  16823. - arrays: linear in the distance between @a first and @a last, plus linear
  16824. in the distance between @a last and end of the container
  16825. - strings and binary: linear in the length of the member
  16826. - other types: constant
  16827. @liveexample{The example shows the result of `erase()` for different JSON
  16828. types.,erase__IteratorType_IteratorType}
  16829. @sa @ref erase(IteratorType) -- removes the element at a given position
  16830. @sa @ref erase(const typename object_t::key_type&) -- removes the element
  16831. from an object at the given key
  16832. @sa @ref erase(const size_type) -- removes the element from an array at
  16833. the given index
  16834. @since version 1.0.0
  16835. */
  16836. template<class IteratorType, typename std::enable_if<
  16837. std::is_same<IteratorType, typename basic_json_t::iterator>::value or
  16838. std::is_same<IteratorType, typename basic_json_t::const_iterator>::value, int>::type
  16839. = 0>
  16840. IteratorType erase(IteratorType first, IteratorType last)
  16841. {
  16842. // make sure iterator fits the current value
  16843. if (JSON_HEDLEY_UNLIKELY(this != first.m_object or this != last.m_object))
  16844. {
  16845. JSON_THROW(invalid_iterator::create(203, "iterators do not fit current value"));
  16846. }
  16847. IteratorType result = end();
  16848. switch (m_type)
  16849. {
  16850. case value_t::boolean:
  16851. case value_t::number_float:
  16852. case value_t::number_integer:
  16853. case value_t::number_unsigned:
  16854. case value_t::string:
  16855. case value_t::binary:
  16856. {
  16857. if (JSON_HEDLEY_LIKELY(not first.m_it.primitive_iterator.is_begin()
  16858. or not last.m_it.primitive_iterator.is_end()))
  16859. {
  16860. JSON_THROW(invalid_iterator::create(204, "iterators out of range"));
  16861. }
  16862. if (is_string())
  16863. {
  16864. AllocatorType<string_t> alloc;
  16865. std::allocator_traits<decltype(alloc)>::destroy(alloc, m_value.string);
  16866. std::allocator_traits<decltype(alloc)>::deallocate(alloc, m_value.string, 1);
  16867. m_value.string = nullptr;
  16868. }
  16869. else if (is_binary())
  16870. {
  16871. AllocatorType<internal_binary_t> alloc;
  16872. std::allocator_traits<decltype(alloc)>::destroy(alloc, m_value.binary);
  16873. std::allocator_traits<decltype(alloc)>::deallocate(alloc, m_value.binary, 1);
  16874. m_value.binary = nullptr;
  16875. }
  16876. m_type = value_t::null;
  16877. assert_invariant();
  16878. break;
  16879. }
  16880. case value_t::object:
  16881. {
  16882. result.m_it.object_iterator = m_value.object->erase(first.m_it.object_iterator,
  16883. last.m_it.object_iterator);
  16884. break;
  16885. }
  16886. case value_t::array:
  16887. {
  16888. result.m_it.array_iterator = m_value.array->erase(first.m_it.array_iterator,
  16889. last.m_it.array_iterator);
  16890. break;
  16891. }
  16892. default:
  16893. JSON_THROW(type_error::create(307, "cannot use erase() with " + std::string(type_name())));
  16894. }
  16895. return result;
  16896. }
  16897. /*!
  16898. @brief remove element from a JSON object given a key
  16899. Removes elements from a JSON object with the key value @a key.
  16900. @param[in] key value of the elements to remove
  16901. @return Number of elements removed. If @a ObjectType is the default
  16902. `std::map` type, the return value will always be `0` (@a key was not
  16903. found) or `1` (@a key was found).
  16904. @post References and iterators to the erased elements are invalidated.
  16905. Other references and iterators are not affected.
  16906. @throw type_error.307 when called on a type other than JSON object;
  16907. example: `"cannot use erase() with null"`
  16908. @complexity `log(size()) + count(key)`
  16909. @liveexample{The example shows the effect of `erase()`.,erase__key_type}
  16910. @sa @ref erase(IteratorType) -- removes the element at a given position
  16911. @sa @ref erase(IteratorType, IteratorType) -- removes the elements in
  16912. the given range
  16913. @sa @ref erase(const size_type) -- removes the element from an array at
  16914. the given index
  16915. @since version 1.0.0
  16916. */
  16917. size_type erase(const typename object_t::key_type& key)
  16918. {
  16919. // this erase only works for objects
  16920. if (JSON_HEDLEY_LIKELY(is_object()))
  16921. {
  16922. return m_value.object->erase(key);
  16923. }
  16924. JSON_THROW(type_error::create(307, "cannot use erase() with " + std::string(type_name())));
  16925. }
  16926. /*!
  16927. @brief remove element from a JSON array given an index
  16928. Removes element from a JSON array at the index @a idx.
  16929. @param[in] idx index of the element to remove
  16930. @throw type_error.307 when called on a type other than JSON object;
  16931. example: `"cannot use erase() with null"`
  16932. @throw out_of_range.401 when `idx >= size()`; example: `"array index 17
  16933. is out of range"`
  16934. @complexity Linear in distance between @a idx and the end of the container.
  16935. @liveexample{The example shows the effect of `erase()`.,erase__size_type}
  16936. @sa @ref erase(IteratorType) -- removes the element at a given position
  16937. @sa @ref erase(IteratorType, IteratorType) -- removes the elements in
  16938. the given range
  16939. @sa @ref erase(const typename object_t::key_type&) -- removes the element
  16940. from an object at the given key
  16941. @since version 1.0.0
  16942. */
  16943. void erase(const size_type idx)
  16944. {
  16945. // this erase only works for arrays
  16946. if (JSON_HEDLEY_LIKELY(is_array()))
  16947. {
  16948. if (JSON_HEDLEY_UNLIKELY(idx >= size()))
  16949. {
  16950. JSON_THROW(out_of_range::create(401, "array index " + std::to_string(idx) + " is out of range"));
  16951. }
  16952. m_value.array->erase(m_value.array->begin() + static_cast<difference_type>(idx));
  16953. }
  16954. else
  16955. {
  16956. JSON_THROW(type_error::create(307, "cannot use erase() with " + std::string(type_name())));
  16957. }
  16958. }
  16959. /// @}
  16960. ////////////
  16961. // lookup //
  16962. ////////////
  16963. /// @name lookup
  16964. /// @{
  16965. /*!
  16966. @brief find an element in a JSON object
  16967. Finds an element in a JSON object with key equivalent to @a key. If the
  16968. element is not found or the JSON value is not an object, end() is
  16969. returned.
  16970. @note This method always returns @ref end() when executed on a JSON type
  16971. that is not an object.
  16972. @param[in] key key value of the element to search for.
  16973. @return Iterator to an element with key equivalent to @a key. If no such
  16974. element is found or the JSON value is not an object, past-the-end (see
  16975. @ref end()) iterator is returned.
  16976. @complexity Logarithmic in the size of the JSON object.
  16977. @liveexample{The example shows how `find()` is used.,find__key_type}
  16978. @sa @ref contains(KeyT&&) const -- checks whether a key exists
  16979. @since version 1.0.0
  16980. */
  16981. template<typename KeyT>
  16982. iterator find(KeyT&& key)
  16983. {
  16984. auto result = end();
  16985. if (is_object())
  16986. {
  16987. result.m_it.object_iterator = m_value.object->find(std::forward<KeyT>(key));
  16988. }
  16989. return result;
  16990. }
  16991. /*!
  16992. @brief find an element in a JSON object
  16993. @copydoc find(KeyT&&)
  16994. */
  16995. template<typename KeyT>
  16996. const_iterator find(KeyT&& key) const
  16997. {
  16998. auto result = cend();
  16999. if (is_object())
  17000. {
  17001. result.m_it.object_iterator = m_value.object->find(std::forward<KeyT>(key));
  17002. }
  17003. return result;
  17004. }
  17005. /*!
  17006. @brief returns the number of occurrences of a key in a JSON object
  17007. Returns the number of elements with key @a key. If ObjectType is the
  17008. default `std::map` type, the return value will always be `0` (@a key was
  17009. not found) or `1` (@a key was found).
  17010. @note This method always returns `0` when executed on a JSON type that is
  17011. not an object.
  17012. @param[in] key key value of the element to count
  17013. @return Number of elements with key @a key. If the JSON value is not an
  17014. object, the return value will be `0`.
  17015. @complexity Logarithmic in the size of the JSON object.
  17016. @liveexample{The example shows how `count()` is used.,count}
  17017. @since version 1.0.0
  17018. */
  17019. template<typename KeyT>
  17020. size_type count(KeyT&& key) const
  17021. {
  17022. // return 0 for all nonobject types
  17023. return is_object() ? m_value.object->count(std::forward<KeyT>(key)) : 0;
  17024. }
  17025. /*!
  17026. @brief check the existence of an element in a JSON object
  17027. Check whether an element exists in a JSON object with key equivalent to
  17028. @a key. If the element is not found or the JSON value is not an object,
  17029. false is returned.
  17030. @note This method always returns false when executed on a JSON type
  17031. that is not an object.
  17032. @param[in] key key value to check its existence.
  17033. @return true if an element with specified @a key exists. If no such
  17034. element with such key is found or the JSON value is not an object,
  17035. false is returned.
  17036. @complexity Logarithmic in the size of the JSON object.
  17037. @liveexample{The following code shows an example for `contains()`.,contains}
  17038. @sa @ref find(KeyT&&) -- returns an iterator to an object element
  17039. @sa @ref contains(const json_pointer&) const -- checks the existence for a JSON pointer
  17040. @since version 3.6.0
  17041. */
  17042. template<typename KeyT, typename std::enable_if<
  17043. not std::is_same<typename std::decay<KeyT>::type, json_pointer>::value, int>::type = 0>
  17044. bool contains(KeyT && key) const
  17045. {
  17046. return is_object() and m_value.object->find(std::forward<KeyT>(key)) != m_value.object->end();
  17047. }
  17048. /*!
  17049. @brief check the existence of an element in a JSON object given a JSON pointer
  17050. Check whether the given JSON pointer @a ptr can be resolved in the current
  17051. JSON value.
  17052. @note This method can be executed on any JSON value type.
  17053. @param[in] ptr JSON pointer to check its existence.
  17054. @return true if the JSON pointer can be resolved to a stored value, false
  17055. otherwise.
  17056. @post If `j.contains(ptr)` returns true, it is safe to call `j[ptr]`.
  17057. @throw parse_error.106 if an array index begins with '0'
  17058. @throw parse_error.109 if an array index was not a number
  17059. @complexity Logarithmic in the size of the JSON object.
  17060. @liveexample{The following code shows an example for `contains()`.,contains_json_pointer}
  17061. @sa @ref contains(KeyT &&) const -- checks the existence of a key
  17062. @since version 3.7.0
  17063. */
  17064. bool contains(const json_pointer& ptr) const
  17065. {
  17066. return ptr.contains(this);
  17067. }
  17068. /// @}
  17069. ///////////////
  17070. // iterators //
  17071. ///////////////
  17072. /// @name iterators
  17073. /// @{
  17074. /*!
  17075. @brief returns an iterator to the first element
  17076. Returns an iterator to the first element.
  17077. @image html range-begin-end.svg "Illustration from cppreference.com"
  17078. @return iterator to the first element
  17079. @complexity Constant.
  17080. @requirement This function helps `basic_json` satisfying the
  17081. [Container](https://en.cppreference.com/w/cpp/named_req/Container)
  17082. requirements:
  17083. - The complexity is constant.
  17084. @liveexample{The following code shows an example for `begin()`.,begin}
  17085. @sa @ref cbegin() -- returns a const iterator to the beginning
  17086. @sa @ref end() -- returns an iterator to the end
  17087. @sa @ref cend() -- returns a const iterator to the end
  17088. @since version 1.0.0
  17089. */
  17090. iterator begin() noexcept
  17091. {
  17092. iterator result(this);
  17093. result.set_begin();
  17094. return result;
  17095. }
  17096. /*!
  17097. @copydoc basic_json::cbegin()
  17098. */
  17099. const_iterator begin() const noexcept
  17100. {
  17101. return cbegin();
  17102. }
  17103. /*!
  17104. @brief returns a const iterator to the first element
  17105. Returns a const iterator to the first element.
  17106. @image html range-begin-end.svg "Illustration from cppreference.com"
  17107. @return const iterator to the first element
  17108. @complexity Constant.
  17109. @requirement This function helps `basic_json` satisfying the
  17110. [Container](https://en.cppreference.com/w/cpp/named_req/Container)
  17111. requirements:
  17112. - The complexity is constant.
  17113. - Has the semantics of `const_cast<const basic_json&>(*this).begin()`.
  17114. @liveexample{The following code shows an example for `cbegin()`.,cbegin}
  17115. @sa @ref begin() -- returns an iterator to the beginning
  17116. @sa @ref end() -- returns an iterator to the end
  17117. @sa @ref cend() -- returns a const iterator to the end
  17118. @since version 1.0.0
  17119. */
  17120. const_iterator cbegin() const noexcept
  17121. {
  17122. const_iterator result(this);
  17123. result.set_begin();
  17124. return result;
  17125. }
  17126. /*!
  17127. @brief returns an iterator to one past the last element
  17128. Returns an iterator to one past the last element.
  17129. @image html range-begin-end.svg "Illustration from cppreference.com"
  17130. @return iterator one past the last element
  17131. @complexity Constant.
  17132. @requirement This function helps `basic_json` satisfying the
  17133. [Container](https://en.cppreference.com/w/cpp/named_req/Container)
  17134. requirements:
  17135. - The complexity is constant.
  17136. @liveexample{The following code shows an example for `end()`.,end}
  17137. @sa @ref cend() -- returns a const iterator to the end
  17138. @sa @ref begin() -- returns an iterator to the beginning
  17139. @sa @ref cbegin() -- returns a const iterator to the beginning
  17140. @since version 1.0.0
  17141. */
  17142. iterator end() noexcept
  17143. {
  17144. iterator result(this);
  17145. result.set_end();
  17146. return result;
  17147. }
  17148. /*!
  17149. @copydoc basic_json::cend()
  17150. */
  17151. const_iterator end() const noexcept
  17152. {
  17153. return cend();
  17154. }
  17155. /*!
  17156. @brief returns a const iterator to one past the last element
  17157. Returns a const iterator to one past the last element.
  17158. @image html range-begin-end.svg "Illustration from cppreference.com"
  17159. @return const iterator one past the last element
  17160. @complexity Constant.
  17161. @requirement This function helps `basic_json` satisfying the
  17162. [Container](https://en.cppreference.com/w/cpp/named_req/Container)
  17163. requirements:
  17164. - The complexity is constant.
  17165. - Has the semantics of `const_cast<const basic_json&>(*this).end()`.
  17166. @liveexample{The following code shows an example for `cend()`.,cend}
  17167. @sa @ref end() -- returns an iterator to the end
  17168. @sa @ref begin() -- returns an iterator to the beginning
  17169. @sa @ref cbegin() -- returns a const iterator to the beginning
  17170. @since version 1.0.0
  17171. */
  17172. const_iterator cend() const noexcept
  17173. {
  17174. const_iterator result(this);
  17175. result.set_end();
  17176. return result;
  17177. }
  17178. /*!
  17179. @brief returns an iterator to the reverse-beginning
  17180. Returns an iterator to the reverse-beginning; that is, the last element.
  17181. @image html range-rbegin-rend.svg "Illustration from cppreference.com"
  17182. @complexity Constant.
  17183. @requirement This function helps `basic_json` satisfying the
  17184. [ReversibleContainer](https://en.cppreference.com/w/cpp/named_req/ReversibleContainer)
  17185. requirements:
  17186. - The complexity is constant.
  17187. - Has the semantics of `reverse_iterator(end())`.
  17188. @liveexample{The following code shows an example for `rbegin()`.,rbegin}
  17189. @sa @ref crbegin() -- returns a const reverse iterator to the beginning
  17190. @sa @ref rend() -- returns a reverse iterator to the end
  17191. @sa @ref crend() -- returns a const reverse iterator to the end
  17192. @since version 1.0.0
  17193. */
  17194. reverse_iterator rbegin() noexcept
  17195. {
  17196. return reverse_iterator(end());
  17197. }
  17198. /*!
  17199. @copydoc basic_json::crbegin()
  17200. */
  17201. const_reverse_iterator rbegin() const noexcept
  17202. {
  17203. return crbegin();
  17204. }
  17205. /*!
  17206. @brief returns an iterator to the reverse-end
  17207. Returns an iterator to the reverse-end; that is, one before the first
  17208. element.
  17209. @image html range-rbegin-rend.svg "Illustration from cppreference.com"
  17210. @complexity Constant.
  17211. @requirement This function helps `basic_json` satisfying the
  17212. [ReversibleContainer](https://en.cppreference.com/w/cpp/named_req/ReversibleContainer)
  17213. requirements:
  17214. - The complexity is constant.
  17215. - Has the semantics of `reverse_iterator(begin())`.
  17216. @liveexample{The following code shows an example for `rend()`.,rend}
  17217. @sa @ref crend() -- returns a const reverse iterator to the end
  17218. @sa @ref rbegin() -- returns a reverse iterator to the beginning
  17219. @sa @ref crbegin() -- returns a const reverse iterator to the beginning
  17220. @since version 1.0.0
  17221. */
  17222. reverse_iterator rend() noexcept
  17223. {
  17224. return reverse_iterator(begin());
  17225. }
  17226. /*!
  17227. @copydoc basic_json::crend()
  17228. */
  17229. const_reverse_iterator rend() const noexcept
  17230. {
  17231. return crend();
  17232. }
  17233. /*!
  17234. @brief returns a const reverse iterator to the last element
  17235. Returns a const iterator to the reverse-beginning; that is, the last
  17236. element.
  17237. @image html range-rbegin-rend.svg "Illustration from cppreference.com"
  17238. @complexity Constant.
  17239. @requirement This function helps `basic_json` satisfying the
  17240. [ReversibleContainer](https://en.cppreference.com/w/cpp/named_req/ReversibleContainer)
  17241. requirements:
  17242. - The complexity is constant.
  17243. - Has the semantics of `const_cast<const basic_json&>(*this).rbegin()`.
  17244. @liveexample{The following code shows an example for `crbegin()`.,crbegin}
  17245. @sa @ref rbegin() -- returns a reverse iterator to the beginning
  17246. @sa @ref rend() -- returns a reverse iterator to the end
  17247. @sa @ref crend() -- returns a const reverse iterator to the end
  17248. @since version 1.0.0
  17249. */
  17250. const_reverse_iterator crbegin() const noexcept
  17251. {
  17252. return const_reverse_iterator(cend());
  17253. }
  17254. /*!
  17255. @brief returns a const reverse iterator to one before the first
  17256. Returns a const reverse iterator to the reverse-end; that is, one before
  17257. the first element.
  17258. @image html range-rbegin-rend.svg "Illustration from cppreference.com"
  17259. @complexity Constant.
  17260. @requirement This function helps `basic_json` satisfying the
  17261. [ReversibleContainer](https://en.cppreference.com/w/cpp/named_req/ReversibleContainer)
  17262. requirements:
  17263. - The complexity is constant.
  17264. - Has the semantics of `const_cast<const basic_json&>(*this).rend()`.
  17265. @liveexample{The following code shows an example for `crend()`.,crend}
  17266. @sa @ref rend() -- returns a reverse iterator to the end
  17267. @sa @ref rbegin() -- returns a reverse iterator to the beginning
  17268. @sa @ref crbegin() -- returns a const reverse iterator to the beginning
  17269. @since version 1.0.0
  17270. */
  17271. const_reverse_iterator crend() const noexcept
  17272. {
  17273. return const_reverse_iterator(cbegin());
  17274. }
  17275. public:
  17276. /*!
  17277. @brief wrapper to access iterator member functions in range-based for
  17278. This function allows to access @ref iterator::key() and @ref
  17279. iterator::value() during range-based for loops. In these loops, a
  17280. reference to the JSON values is returned, so there is no access to the
  17281. underlying iterator.
  17282. For loop without iterator_wrapper:
  17283. @code{cpp}
  17284. for (auto it = j_object.begin(); it != j_object.end(); ++it)
  17285. {
  17286. std::cout << "key: " << it.key() << ", value:" << it.value() << '\n';
  17287. }
  17288. @endcode
  17289. Range-based for loop without iterator proxy:
  17290. @code{cpp}
  17291. for (auto it : j_object)
  17292. {
  17293. // "it" is of type json::reference and has no key() member
  17294. std::cout << "value: " << it << '\n';
  17295. }
  17296. @endcode
  17297. Range-based for loop with iterator proxy:
  17298. @code{cpp}
  17299. for (auto it : json::iterator_wrapper(j_object))
  17300. {
  17301. std::cout << "key: " << it.key() << ", value:" << it.value() << '\n';
  17302. }
  17303. @endcode
  17304. @note When iterating over an array, `key()` will return the index of the
  17305. element as string (see example).
  17306. @param[in] ref reference to a JSON value
  17307. @return iteration proxy object wrapping @a ref with an interface to use in
  17308. range-based for loops
  17309. @liveexample{The following code shows how the wrapper is used,iterator_wrapper}
  17310. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  17311. changes in the JSON value.
  17312. @complexity Constant.
  17313. @note The name of this function is not yet final and may change in the
  17314. future.
  17315. @deprecated This stream operator is deprecated and will be removed in
  17316. future 4.0.0 of the library. Please use @ref items() instead;
  17317. that is, replace `json::iterator_wrapper(j)` with `j.items()`.
  17318. */
  17319. JSON_HEDLEY_DEPRECATED(3.1.0)
  17320. static iteration_proxy<iterator> iterator_wrapper(reference ref) noexcept
  17321. {
  17322. return ref.items();
  17323. }
  17324. /*!
  17325. @copydoc iterator_wrapper(reference)
  17326. */
  17327. JSON_HEDLEY_DEPRECATED(3.1.0)
  17328. static iteration_proxy<const_iterator> iterator_wrapper(const_reference ref) noexcept
  17329. {
  17330. return ref.items();
  17331. }
  17332. /*!
  17333. @brief helper to access iterator member functions in range-based for
  17334. This function allows to access @ref iterator::key() and @ref
  17335. iterator::value() during range-based for loops. In these loops, a
  17336. reference to the JSON values is returned, so there is no access to the
  17337. underlying iterator.
  17338. For loop without `items()` function:
  17339. @code{cpp}
  17340. for (auto it = j_object.begin(); it != j_object.end(); ++it)
  17341. {
  17342. std::cout << "key: " << it.key() << ", value:" << it.value() << '\n';
  17343. }
  17344. @endcode
  17345. Range-based for loop without `items()` function:
  17346. @code{cpp}
  17347. for (auto it : j_object)
  17348. {
  17349. // "it" is of type json::reference and has no key() member
  17350. std::cout << "value: " << it << '\n';
  17351. }
  17352. @endcode
  17353. Range-based for loop with `items()` function:
  17354. @code{cpp}
  17355. for (auto& el : j_object.items())
  17356. {
  17357. std::cout << "key: " << el.key() << ", value:" << el.value() << '\n';
  17358. }
  17359. @endcode
  17360. The `items()` function also allows to use
  17361. [structured bindings](https://en.cppreference.com/w/cpp/language/structured_binding)
  17362. (C++17):
  17363. @code{cpp}
  17364. for (auto& [key, val] : j_object.items())
  17365. {
  17366. std::cout << "key: " << key << ", value:" << val << '\n';
  17367. }
  17368. @endcode
  17369. @note When iterating over an array, `key()` will return the index of the
  17370. element as string (see example). For primitive types (e.g., numbers),
  17371. `key()` returns an empty string.
  17372. @warning Using `items()` on temporary objects is dangerous. Make sure the
  17373. object's lifetime exeeds the iteration. See
  17374. <https://github.com/nlohmann/json/issues/2040> for more
  17375. information.
  17376. @return iteration proxy object wrapping @a ref with an interface to use in
  17377. range-based for loops
  17378. @liveexample{The following code shows how the function is used.,items}
  17379. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  17380. changes in the JSON value.
  17381. @complexity Constant.
  17382. @since version 3.1.0, structured bindings support since 3.5.0.
  17383. */
  17384. iteration_proxy<iterator> items() noexcept
  17385. {
  17386. return iteration_proxy<iterator>(*this);
  17387. }
  17388. /*!
  17389. @copydoc items()
  17390. */
  17391. iteration_proxy<const_iterator> items() const noexcept
  17392. {
  17393. return iteration_proxy<const_iterator>(*this);
  17394. }
  17395. /// @}
  17396. //////////////
  17397. // capacity //
  17398. //////////////
  17399. /// @name capacity
  17400. /// @{
  17401. /*!
  17402. @brief checks whether the container is empty.
  17403. Checks if a JSON value has no elements (i.e. whether its @ref size is `0`).
  17404. @return The return value depends on the different types and is
  17405. defined as follows:
  17406. Value type | return value
  17407. ----------- | -------------
  17408. null | `true`
  17409. boolean | `false`
  17410. string | `false`
  17411. number | `false`
  17412. binary | `false`
  17413. object | result of function `object_t::empty()`
  17414. array | result of function `array_t::empty()`
  17415. @liveexample{The following code uses `empty()` to check if a JSON
  17416. object contains any elements.,empty}
  17417. @complexity Constant, as long as @ref array_t and @ref object_t satisfy
  17418. the Container concept; that is, their `empty()` functions have constant
  17419. complexity.
  17420. @iterators No changes.
  17421. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  17422. @note This function does not return whether a string stored as JSON value
  17423. is empty - it returns whether the JSON container itself is empty which is
  17424. false in the case of a string.
  17425. @requirement This function helps `basic_json` satisfying the
  17426. [Container](https://en.cppreference.com/w/cpp/named_req/Container)
  17427. requirements:
  17428. - The complexity is constant.
  17429. - Has the semantics of `begin() == end()`.
  17430. @sa @ref size() -- returns the number of elements
  17431. @since version 1.0.0
  17432. */
  17433. bool empty() const noexcept
  17434. {
  17435. switch (m_type)
  17436. {
  17437. case value_t::null:
  17438. {
  17439. // null values are empty
  17440. return true;
  17441. }
  17442. case value_t::array:
  17443. {
  17444. // delegate call to array_t::empty()
  17445. return m_value.array->empty();
  17446. }
  17447. case value_t::object:
  17448. {
  17449. // delegate call to object_t::empty()
  17450. return m_value.object->empty();
  17451. }
  17452. default:
  17453. {
  17454. // all other types are nonempty
  17455. return false;
  17456. }
  17457. }
  17458. }
  17459. /*!
  17460. @brief returns the number of elements
  17461. Returns the number of elements in a JSON value.
  17462. @return The return value depends on the different types and is
  17463. defined as follows:
  17464. Value type | return value
  17465. ----------- | -------------
  17466. null | `0`
  17467. boolean | `1`
  17468. string | `1`
  17469. number | `1`
  17470. binary | `1`
  17471. object | result of function object_t::size()
  17472. array | result of function array_t::size()
  17473. @liveexample{The following code calls `size()` on the different value
  17474. types.,size}
  17475. @complexity Constant, as long as @ref array_t and @ref object_t satisfy
  17476. the Container concept; that is, their size() functions have constant
  17477. complexity.
  17478. @iterators No changes.
  17479. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  17480. @note This function does not return the length of a string stored as JSON
  17481. value - it returns the number of elements in the JSON value which is 1 in
  17482. the case of a string.
  17483. @requirement This function helps `basic_json` satisfying the
  17484. [Container](https://en.cppreference.com/w/cpp/named_req/Container)
  17485. requirements:
  17486. - The complexity is constant.
  17487. - Has the semantics of `std::distance(begin(), end())`.
  17488. @sa @ref empty() -- checks whether the container is empty
  17489. @sa @ref max_size() -- returns the maximal number of elements
  17490. @since version 1.0.0
  17491. */
  17492. size_type size() const noexcept
  17493. {
  17494. switch (m_type)
  17495. {
  17496. case value_t::null:
  17497. {
  17498. // null values are empty
  17499. return 0;
  17500. }
  17501. case value_t::array:
  17502. {
  17503. // delegate call to array_t::size()
  17504. return m_value.array->size();
  17505. }
  17506. case value_t::object:
  17507. {
  17508. // delegate call to object_t::size()
  17509. return m_value.object->size();
  17510. }
  17511. default:
  17512. {
  17513. // all other types have size 1
  17514. return 1;
  17515. }
  17516. }
  17517. }
  17518. /*!
  17519. @brief returns the maximum possible number of elements
  17520. Returns the maximum number of elements a JSON value is able to hold due to
  17521. system or library implementation limitations, i.e. `std::distance(begin(),
  17522. end())` for the JSON value.
  17523. @return The return value depends on the different types and is
  17524. defined as follows:
  17525. Value type | return value
  17526. ----------- | -------------
  17527. null | `0` (same as `size()`)
  17528. boolean | `1` (same as `size()`)
  17529. string | `1` (same as `size()`)
  17530. number | `1` (same as `size()`)
  17531. binary | `1` (same as `size()`)
  17532. object | result of function `object_t::max_size()`
  17533. array | result of function `array_t::max_size()`
  17534. @liveexample{The following code calls `max_size()` on the different value
  17535. types. Note the output is implementation specific.,max_size}
  17536. @complexity Constant, as long as @ref array_t and @ref object_t satisfy
  17537. the Container concept; that is, their `max_size()` functions have constant
  17538. complexity.
  17539. @iterators No changes.
  17540. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  17541. @requirement This function helps `basic_json` satisfying the
  17542. [Container](https://en.cppreference.com/w/cpp/named_req/Container)
  17543. requirements:
  17544. - The complexity is constant.
  17545. - Has the semantics of returning `b.size()` where `b` is the largest
  17546. possible JSON value.
  17547. @sa @ref size() -- returns the number of elements
  17548. @since version 1.0.0
  17549. */
  17550. size_type max_size() const noexcept
  17551. {
  17552. switch (m_type)
  17553. {
  17554. case value_t::array:
  17555. {
  17556. // delegate call to array_t::max_size()
  17557. return m_value.array->max_size();
  17558. }
  17559. case value_t::object:
  17560. {
  17561. // delegate call to object_t::max_size()
  17562. return m_value.object->max_size();
  17563. }
  17564. default:
  17565. {
  17566. // all other types have max_size() == size()
  17567. return size();
  17568. }
  17569. }
  17570. }
  17571. /// @}
  17572. ///////////////
  17573. // modifiers //
  17574. ///////////////
  17575. /// @name modifiers
  17576. /// @{
  17577. /*!
  17578. @brief clears the contents
  17579. Clears the content of a JSON value and resets it to the default value as
  17580. if @ref basic_json(value_t) would have been called with the current value
  17581. type from @ref type():
  17582. Value type | initial value
  17583. ----------- | -------------
  17584. null | `null`
  17585. boolean | `false`
  17586. string | `""`
  17587. number | `0`
  17588. binary | An empty byte vector
  17589. object | `{}`
  17590. array | `[]`
  17591. @post Has the same effect as calling
  17592. @code {.cpp}
  17593. *this = basic_json(type());
  17594. @endcode
  17595. @liveexample{The example below shows the effect of `clear()` to different
  17596. JSON types.,clear}
  17597. @complexity Linear in the size of the JSON value.
  17598. @iterators All iterators, pointers and references related to this container
  17599. are invalidated.
  17600. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  17601. @sa @ref basic_json(value_t) -- constructor that creates an object with the
  17602. same value than calling `clear()`
  17603. @since version 1.0.0
  17604. */
  17605. void clear() noexcept
  17606. {
  17607. switch (m_type)
  17608. {
  17609. case value_t::number_integer:
  17610. {
  17611. m_value.number_integer = 0;
  17612. break;
  17613. }
  17614. case value_t::number_unsigned:
  17615. {
  17616. m_value.number_unsigned = 0;
  17617. break;
  17618. }
  17619. case value_t::number_float:
  17620. {
  17621. m_value.number_float = 0.0;
  17622. break;
  17623. }
  17624. case value_t::boolean:
  17625. {
  17626. m_value.boolean = false;
  17627. break;
  17628. }
  17629. case value_t::string:
  17630. {
  17631. m_value.string->clear();
  17632. break;
  17633. }
  17634. case value_t::binary:
  17635. {
  17636. m_value.binary->clear();
  17637. break;
  17638. }
  17639. case value_t::array:
  17640. {
  17641. m_value.array->clear();
  17642. break;
  17643. }
  17644. case value_t::object:
  17645. {
  17646. m_value.object->clear();
  17647. break;
  17648. }
  17649. default:
  17650. break;
  17651. }
  17652. }
  17653. /*!
  17654. @brief add an object to an array
  17655. Appends the given element @a val to the end of the JSON value. If the
  17656. function is called on a JSON null value, an empty array is created before
  17657. appending @a val.
  17658. @param[in] val the value to add to the JSON array
  17659. @throw type_error.308 when called on a type other than JSON array or
  17660. null; example: `"cannot use push_back() with number"`
  17661. @complexity Amortized constant.
  17662. @liveexample{The example shows how `push_back()` and `+=` can be used to
  17663. add elements to a JSON array. Note how the `null` value was silently
  17664. converted to a JSON array.,push_back}
  17665. @since version 1.0.0
  17666. */
  17667. void push_back(basic_json&& val)
  17668. {
  17669. // push_back only works for null objects or arrays
  17670. if (JSON_HEDLEY_UNLIKELY(not(is_null() or is_array())))
  17671. {
  17672. JSON_THROW(type_error::create(308, "cannot use push_back() with " + std::string(type_name())));
  17673. }
  17674. // transform null object into an array
  17675. if (is_null())
  17676. {
  17677. m_type = value_t::array;
  17678. m_value = value_t::array;
  17679. assert_invariant();
  17680. }
  17681. // add element to array (move semantics)
  17682. m_value.array->push_back(std::move(val));
  17683. // if val is moved from, basic_json move constructor marks it null so we do not call the destructor
  17684. }
  17685. /*!
  17686. @brief add an object to an array
  17687. @copydoc push_back(basic_json&&)
  17688. */
  17689. reference operator+=(basic_json&& val)
  17690. {
  17691. push_back(std::move(val));
  17692. return *this;
  17693. }
  17694. /*!
  17695. @brief add an object to an array
  17696. @copydoc push_back(basic_json&&)
  17697. */
  17698. void push_back(const basic_json& val)
  17699. {
  17700. // push_back only works for null objects or arrays
  17701. if (JSON_HEDLEY_UNLIKELY(not(is_null() or is_array())))
  17702. {
  17703. JSON_THROW(type_error::create(308, "cannot use push_back() with " + std::string(type_name())));
  17704. }
  17705. // transform null object into an array
  17706. if (is_null())
  17707. {
  17708. m_type = value_t::array;
  17709. m_value = value_t::array;
  17710. assert_invariant();
  17711. }
  17712. // add element to array
  17713. m_value.array->push_back(val);
  17714. }
  17715. /*!
  17716. @brief add an object to an array
  17717. @copydoc push_back(basic_json&&)
  17718. */
  17719. reference operator+=(const basic_json& val)
  17720. {
  17721. push_back(val);
  17722. return *this;
  17723. }
  17724. /*!
  17725. @brief add an object to an object
  17726. Inserts the given element @a val to the JSON object. If the function is
  17727. called on a JSON null value, an empty object is created before inserting
  17728. @a val.
  17729. @param[in] val the value to add to the JSON object
  17730. @throw type_error.308 when called on a type other than JSON object or
  17731. null; example: `"cannot use push_back() with number"`
  17732. @complexity Logarithmic in the size of the container, O(log(`size()`)).
  17733. @liveexample{The example shows how `push_back()` and `+=` can be used to
  17734. add elements to a JSON object. Note how the `null` value was silently
  17735. converted to a JSON object.,push_back__object_t__value}
  17736. @since version 1.0.0
  17737. */
  17738. void push_back(const typename object_t::value_type& val)
  17739. {
  17740. // push_back only works for null objects or objects
  17741. if (JSON_HEDLEY_UNLIKELY(not(is_null() or is_object())))
  17742. {
  17743. JSON_THROW(type_error::create(308, "cannot use push_back() with " + std::string(type_name())));
  17744. }
  17745. // transform null object into an object
  17746. if (is_null())
  17747. {
  17748. m_type = value_t::object;
  17749. m_value = value_t::object;
  17750. assert_invariant();
  17751. }
  17752. // add element to array
  17753. m_value.object->insert(val);
  17754. }
  17755. /*!
  17756. @brief add an object to an object
  17757. @copydoc push_back(const typename object_t::value_type&)
  17758. */
  17759. reference operator+=(const typename object_t::value_type& val)
  17760. {
  17761. push_back(val);
  17762. return *this;
  17763. }
  17764. /*!
  17765. @brief add an object to an object
  17766. This function allows to use `push_back` with an initializer list. In case
  17767. 1. the current value is an object,
  17768. 2. the initializer list @a init contains only two elements, and
  17769. 3. the first element of @a init is a string,
  17770. @a init is converted into an object element and added using
  17771. @ref push_back(const typename object_t::value_type&). Otherwise, @a init
  17772. is converted to a JSON value and added using @ref push_back(basic_json&&).
  17773. @param[in] init an initializer list
  17774. @complexity Linear in the size of the initializer list @a init.
  17775. @note This function is required to resolve an ambiguous overload error,
  17776. because pairs like `{"key", "value"}` can be both interpreted as
  17777. `object_t::value_type` or `std::initializer_list<basic_json>`, see
  17778. https://github.com/nlohmann/json/issues/235 for more information.
  17779. @liveexample{The example shows how initializer lists are treated as
  17780. objects when possible.,push_back__initializer_list}
  17781. */
  17782. void push_back(initializer_list_t init)
  17783. {
  17784. if (is_object() and init.size() == 2 and (*init.begin())->is_string())
  17785. {
  17786. basic_json&& key = init.begin()->moved_or_copied();
  17787. push_back(typename object_t::value_type(
  17788. std::move(key.get_ref<string_t&>()), (init.begin() + 1)->moved_or_copied()));
  17789. }
  17790. else
  17791. {
  17792. push_back(basic_json(init));
  17793. }
  17794. }
  17795. /*!
  17796. @brief add an object to an object
  17797. @copydoc push_back(initializer_list_t)
  17798. */
  17799. reference operator+=(initializer_list_t init)
  17800. {
  17801. push_back(init);
  17802. return *this;
  17803. }
  17804. /*!
  17805. @brief add an object to an array
  17806. Creates a JSON value from the passed parameters @a args to the end of the
  17807. JSON value. If the function is called on a JSON null value, an empty array
  17808. is created before appending the value created from @a args.
  17809. @param[in] args arguments to forward to a constructor of @ref basic_json
  17810. @tparam Args compatible types to create a @ref basic_json object
  17811. @return reference to the inserted element
  17812. @throw type_error.311 when called on a type other than JSON array or
  17813. null; example: `"cannot use emplace_back() with number"`
  17814. @complexity Amortized constant.
  17815. @liveexample{The example shows how `push_back()` can be used to add
  17816. elements to a JSON array. Note how the `null` value was silently converted
  17817. to a JSON array.,emplace_back}
  17818. @since version 2.0.8, returns reference since 3.7.0
  17819. */
  17820. template<class... Args>
  17821. reference emplace_back(Args&& ... args)
  17822. {
  17823. // emplace_back only works for null objects or arrays
  17824. if (JSON_HEDLEY_UNLIKELY(not(is_null() or is_array())))
  17825. {
  17826. JSON_THROW(type_error::create(311, "cannot use emplace_back() with " + std::string(type_name())));
  17827. }
  17828. // transform null object into an array
  17829. if (is_null())
  17830. {
  17831. m_type = value_t::array;
  17832. m_value = value_t::array;
  17833. assert_invariant();
  17834. }
  17835. // add element to array (perfect forwarding)
  17836. #ifdef JSON_HAS_CPP_17
  17837. return m_value.array->emplace_back(std::forward<Args>(args)...);
  17838. #else
  17839. m_value.array->emplace_back(std::forward<Args>(args)...);
  17840. return m_value.array->back();
  17841. #endif
  17842. }
  17843. /*!
  17844. @brief add an object to an object if key does not exist
  17845. Inserts a new element into a JSON object constructed in-place with the
  17846. given @a args if there is no element with the key in the container. If the
  17847. function is called on a JSON null value, an empty object is created before
  17848. appending the value created from @a args.
  17849. @param[in] args arguments to forward to a constructor of @ref basic_json
  17850. @tparam Args compatible types to create a @ref basic_json object
  17851. @return a pair consisting of an iterator to the inserted element, or the
  17852. already-existing element if no insertion happened, and a bool
  17853. denoting whether the insertion took place.
  17854. @throw type_error.311 when called on a type other than JSON object or
  17855. null; example: `"cannot use emplace() with number"`
  17856. @complexity Logarithmic in the size of the container, O(log(`size()`)).
  17857. @liveexample{The example shows how `emplace()` can be used to add elements
  17858. to a JSON object. Note how the `null` value was silently converted to a
  17859. JSON object. Further note how no value is added if there was already one
  17860. value stored with the same key.,emplace}
  17861. @since version 2.0.8
  17862. */
  17863. template<class... Args>
  17864. std::pair<iterator, bool> emplace(Args&& ... args)
  17865. {
  17866. // emplace only works for null objects or arrays
  17867. if (JSON_HEDLEY_UNLIKELY(not(is_null() or is_object())))
  17868. {
  17869. JSON_THROW(type_error::create(311, "cannot use emplace() with " + std::string(type_name())));
  17870. }
  17871. // transform null object into an object
  17872. if (is_null())
  17873. {
  17874. m_type = value_t::object;
  17875. m_value = value_t::object;
  17876. assert_invariant();
  17877. }
  17878. // add element to array (perfect forwarding)
  17879. auto res = m_value.object->emplace(std::forward<Args>(args)...);
  17880. // create result iterator and set iterator to the result of emplace
  17881. auto it = begin();
  17882. it.m_it.object_iterator = res.first;
  17883. // return pair of iterator and boolean
  17884. return {it, res.second};
  17885. }
  17886. /// Helper for insertion of an iterator
  17887. /// @note: This uses std::distance to support GCC 4.8,
  17888. /// see https://github.com/nlohmann/json/pull/1257
  17889. template<typename... Args>
  17890. iterator insert_iterator(const_iterator pos, Args&& ... args)
  17891. {
  17892. iterator result(this);
  17893. assert(m_value.array != nullptr);
  17894. auto insert_pos = std::distance(m_value.array->begin(), pos.m_it.array_iterator);
  17895. m_value.array->insert(pos.m_it.array_iterator, std::forward<Args>(args)...);
  17896. result.m_it.array_iterator = m_value.array->begin() + insert_pos;
  17897. // This could have been written as:
  17898. // result.m_it.array_iterator = m_value.array->insert(pos.m_it.array_iterator, cnt, val);
  17899. // but the return value of insert is missing in GCC 4.8, so it is written this way instead.
  17900. return result;
  17901. }
  17902. /*!
  17903. @brief inserts element
  17904. Inserts element @a val before iterator @a pos.
  17905. @param[in] pos iterator before which the content will be inserted; may be
  17906. the end() iterator
  17907. @param[in] val element to insert
  17908. @return iterator pointing to the inserted @a val.
  17909. @throw type_error.309 if called on JSON values other than arrays;
  17910. example: `"cannot use insert() with string"`
  17911. @throw invalid_iterator.202 if @a pos is not an iterator of *this;
  17912. example: `"iterator does not fit current value"`
  17913. @complexity Constant plus linear in the distance between @a pos and end of
  17914. the container.
  17915. @liveexample{The example shows how `insert()` is used.,insert}
  17916. @since version 1.0.0
  17917. */
  17918. iterator insert(const_iterator pos, const basic_json& val)
  17919. {
  17920. // insert only works for arrays
  17921. if (JSON_HEDLEY_LIKELY(is_array()))
  17922. {
  17923. // check if iterator pos fits to this JSON value
  17924. if (JSON_HEDLEY_UNLIKELY(pos.m_object != this))
  17925. {
  17926. JSON_THROW(invalid_iterator::create(202, "iterator does not fit current value"));
  17927. }
  17928. // insert to array and return iterator
  17929. return insert_iterator(pos, val);
  17930. }
  17931. JSON_THROW(type_error::create(309, "cannot use insert() with " + std::string(type_name())));
  17932. }
  17933. /*!
  17934. @brief inserts element
  17935. @copydoc insert(const_iterator, const basic_json&)
  17936. */
  17937. iterator insert(const_iterator pos, basic_json&& val)
  17938. {
  17939. return insert(pos, val);
  17940. }
  17941. /*!
  17942. @brief inserts elements
  17943. Inserts @a cnt copies of @a val before iterator @a pos.
  17944. @param[in] pos iterator before which the content will be inserted; may be
  17945. the end() iterator
  17946. @param[in] cnt number of copies of @a val to insert
  17947. @param[in] val element to insert
  17948. @return iterator pointing to the first element inserted, or @a pos if
  17949. `cnt==0`
  17950. @throw type_error.309 if called on JSON values other than arrays; example:
  17951. `"cannot use insert() with string"`
  17952. @throw invalid_iterator.202 if @a pos is not an iterator of *this;
  17953. example: `"iterator does not fit current value"`
  17954. @complexity Linear in @a cnt plus linear in the distance between @a pos
  17955. and end of the container.
  17956. @liveexample{The example shows how `insert()` is used.,insert__count}
  17957. @since version 1.0.0
  17958. */
  17959. iterator insert(const_iterator pos, size_type cnt, const basic_json& val)
  17960. {
  17961. // insert only works for arrays
  17962. if (JSON_HEDLEY_LIKELY(is_array()))
  17963. {
  17964. // check if iterator pos fits to this JSON value
  17965. if (JSON_HEDLEY_UNLIKELY(pos.m_object != this))
  17966. {
  17967. JSON_THROW(invalid_iterator::create(202, "iterator does not fit current value"));
  17968. }
  17969. // insert to array and return iterator
  17970. return insert_iterator(pos, cnt, val);
  17971. }
  17972. JSON_THROW(type_error::create(309, "cannot use insert() with " + std::string(type_name())));
  17973. }
  17974. /*!
  17975. @brief inserts elements
  17976. Inserts elements from range `[first, last)` before iterator @a pos.
  17977. @param[in] pos iterator before which the content will be inserted; may be
  17978. the end() iterator
  17979. @param[in] first begin of the range of elements to insert
  17980. @param[in] last end of the range of elements to insert
  17981. @throw type_error.309 if called on JSON values other than arrays; example:
  17982. `"cannot use insert() with string"`
  17983. @throw invalid_iterator.202 if @a pos is not an iterator of *this;
  17984. example: `"iterator does not fit current value"`
  17985. @throw invalid_iterator.210 if @a first and @a last do not belong to the
  17986. same JSON value; example: `"iterators do not fit"`
  17987. @throw invalid_iterator.211 if @a first or @a last are iterators into
  17988. container for which insert is called; example: `"passed iterators may not
  17989. belong to container"`
  17990. @return iterator pointing to the first element inserted, or @a pos if
  17991. `first==last`
  17992. @complexity Linear in `std::distance(first, last)` plus linear in the
  17993. distance between @a pos and end of the container.
  17994. @liveexample{The example shows how `insert()` is used.,insert__range}
  17995. @since version 1.0.0
  17996. */
  17997. iterator insert(const_iterator pos, const_iterator first, const_iterator last)
  17998. {
  17999. // insert only works for arrays
  18000. if (JSON_HEDLEY_UNLIKELY(not is_array()))
  18001. {
  18002. JSON_THROW(type_error::create(309, "cannot use insert() with " + std::string(type_name())));
  18003. }
  18004. // check if iterator pos fits to this JSON value
  18005. if (JSON_HEDLEY_UNLIKELY(pos.m_object != this))
  18006. {
  18007. JSON_THROW(invalid_iterator::create(202, "iterator does not fit current value"));
  18008. }
  18009. // check if range iterators belong to the same JSON object
  18010. if (JSON_HEDLEY_UNLIKELY(first.m_object != last.m_object))
  18011. {
  18012. JSON_THROW(invalid_iterator::create(210, "iterators do not fit"));
  18013. }
  18014. if (JSON_HEDLEY_UNLIKELY(first.m_object == this))
  18015. {
  18016. JSON_THROW(invalid_iterator::create(211, "passed iterators may not belong to container"));
  18017. }
  18018. // insert to array and return iterator
  18019. return insert_iterator(pos, first.m_it.array_iterator, last.m_it.array_iterator);
  18020. }
  18021. /*!
  18022. @brief inserts elements
  18023. Inserts elements from initializer list @a ilist before iterator @a pos.
  18024. @param[in] pos iterator before which the content will be inserted; may be
  18025. the end() iterator
  18026. @param[in] ilist initializer list to insert the values from
  18027. @throw type_error.309 if called on JSON values other than arrays; example:
  18028. `"cannot use insert() with string"`
  18029. @throw invalid_iterator.202 if @a pos is not an iterator of *this;
  18030. example: `"iterator does not fit current value"`
  18031. @return iterator pointing to the first element inserted, or @a pos if
  18032. `ilist` is empty
  18033. @complexity Linear in `ilist.size()` plus linear in the distance between
  18034. @a pos and end of the container.
  18035. @liveexample{The example shows how `insert()` is used.,insert__ilist}
  18036. @since version 1.0.0
  18037. */
  18038. iterator insert(const_iterator pos, initializer_list_t ilist)
  18039. {
  18040. // insert only works for arrays
  18041. if (JSON_HEDLEY_UNLIKELY(not is_array()))
  18042. {
  18043. JSON_THROW(type_error::create(309, "cannot use insert() with " + std::string(type_name())));
  18044. }
  18045. // check if iterator pos fits to this JSON value
  18046. if (JSON_HEDLEY_UNLIKELY(pos.m_object != this))
  18047. {
  18048. JSON_THROW(invalid_iterator::create(202, "iterator does not fit current value"));
  18049. }
  18050. // insert to array and return iterator
  18051. return insert_iterator(pos, ilist.begin(), ilist.end());
  18052. }
  18053. /*!
  18054. @brief inserts elements
  18055. Inserts elements from range `[first, last)`.
  18056. @param[in] first begin of the range of elements to insert
  18057. @param[in] last end of the range of elements to insert
  18058. @throw type_error.309 if called on JSON values other than objects; example:
  18059. `"cannot use insert() with string"`
  18060. @throw invalid_iterator.202 if iterator @a first or @a last does does not
  18061. point to an object; example: `"iterators first and last must point to
  18062. objects"`
  18063. @throw invalid_iterator.210 if @a first and @a last do not belong to the
  18064. same JSON value; example: `"iterators do not fit"`
  18065. @complexity Logarithmic: `O(N*log(size() + N))`, where `N` is the number
  18066. of elements to insert.
  18067. @liveexample{The example shows how `insert()` is used.,insert__range_object}
  18068. @since version 3.0.0
  18069. */
  18070. void insert(const_iterator first, const_iterator last)
  18071. {
  18072. // insert only works for objects
  18073. if (JSON_HEDLEY_UNLIKELY(not is_object()))
  18074. {
  18075. JSON_THROW(type_error::create(309, "cannot use insert() with " + std::string(type_name())));
  18076. }
  18077. // check if range iterators belong to the same JSON object
  18078. if (JSON_HEDLEY_UNLIKELY(first.m_object != last.m_object))
  18079. {
  18080. JSON_THROW(invalid_iterator::create(210, "iterators do not fit"));
  18081. }
  18082. // passed iterators must belong to objects
  18083. if (JSON_HEDLEY_UNLIKELY(not first.m_object->is_object()))
  18084. {
  18085. JSON_THROW(invalid_iterator::create(202, "iterators first and last must point to objects"));
  18086. }
  18087. m_value.object->insert(first.m_it.object_iterator, last.m_it.object_iterator);
  18088. }
  18089. /*!
  18090. @brief updates a JSON object from another object, overwriting existing keys
  18091. Inserts all values from JSON object @a j and overwrites existing keys.
  18092. @param[in] j JSON object to read values from
  18093. @throw type_error.312 if called on JSON values other than objects; example:
  18094. `"cannot use update() with string"`
  18095. @complexity O(N*log(size() + N)), where N is the number of elements to
  18096. insert.
  18097. @liveexample{The example shows how `update()` is used.,update}
  18098. @sa https://docs.python.org/3.6/library/stdtypes.html#dict.update
  18099. @since version 3.0.0
  18100. */
  18101. void update(const_reference j)
  18102. {
  18103. // implicitly convert null value to an empty object
  18104. if (is_null())
  18105. {
  18106. m_type = value_t::object;
  18107. m_value.object = create<object_t>();
  18108. assert_invariant();
  18109. }
  18110. if (JSON_HEDLEY_UNLIKELY(not is_object()))
  18111. {
  18112. JSON_THROW(type_error::create(312, "cannot use update() with " + std::string(type_name())));
  18113. }
  18114. if (JSON_HEDLEY_UNLIKELY(not j.is_object()))
  18115. {
  18116. JSON_THROW(type_error::create(312, "cannot use update() with " + std::string(j.type_name())));
  18117. }
  18118. for (auto it = j.cbegin(); it != j.cend(); ++it)
  18119. {
  18120. m_value.object->operator[](it.key()) = it.value();
  18121. }
  18122. }
  18123. /*!
  18124. @brief updates a JSON object from another object, overwriting existing keys
  18125. Inserts all values from from range `[first, last)` and overwrites existing
  18126. keys.
  18127. @param[in] first begin of the range of elements to insert
  18128. @param[in] last end of the range of elements to insert
  18129. @throw type_error.312 if called on JSON values other than objects; example:
  18130. `"cannot use update() with string"`
  18131. @throw invalid_iterator.202 if iterator @a first or @a last does does not
  18132. point to an object; example: `"iterators first and last must point to
  18133. objects"`
  18134. @throw invalid_iterator.210 if @a first and @a last do not belong to the
  18135. same JSON value; example: `"iterators do not fit"`
  18136. @complexity O(N*log(size() + N)), where N is the number of elements to
  18137. insert.
  18138. @liveexample{The example shows how `update()` is used__range.,update}
  18139. @sa https://docs.python.org/3.6/library/stdtypes.html#dict.update
  18140. @since version 3.0.0
  18141. */
  18142. void update(const_iterator first, const_iterator last)
  18143. {
  18144. // implicitly convert null value to an empty object
  18145. if (is_null())
  18146. {
  18147. m_type = value_t::object;
  18148. m_value.object = create<object_t>();
  18149. assert_invariant();
  18150. }
  18151. if (JSON_HEDLEY_UNLIKELY(not is_object()))
  18152. {
  18153. JSON_THROW(type_error::create(312, "cannot use update() with " + std::string(type_name())));
  18154. }
  18155. // check if range iterators belong to the same JSON object
  18156. if (JSON_HEDLEY_UNLIKELY(first.m_object != last.m_object))
  18157. {
  18158. JSON_THROW(invalid_iterator::create(210, "iterators do not fit"));
  18159. }
  18160. // passed iterators must belong to objects
  18161. if (JSON_HEDLEY_UNLIKELY(not first.m_object->is_object()
  18162. or not last.m_object->is_object()))
  18163. {
  18164. JSON_THROW(invalid_iterator::create(202, "iterators first and last must point to objects"));
  18165. }
  18166. for (auto it = first; it != last; ++it)
  18167. {
  18168. m_value.object->operator[](it.key()) = it.value();
  18169. }
  18170. }
  18171. /*!
  18172. @brief exchanges the values
  18173. Exchanges the contents of the JSON value with those of @a other. Does not
  18174. invoke any move, copy, or swap operations on individual elements. All
  18175. iterators and references remain valid. The past-the-end iterator is
  18176. invalidated.
  18177. @param[in,out] other JSON value to exchange the contents with
  18178. @complexity Constant.
  18179. @liveexample{The example below shows how JSON values can be swapped with
  18180. `swap()`.,swap__reference}
  18181. @since version 1.0.0
  18182. */
  18183. void swap(reference other) noexcept (
  18184. std::is_nothrow_move_constructible<value_t>::value and
  18185. std::is_nothrow_move_assignable<value_t>::value and
  18186. std::is_nothrow_move_constructible<json_value>::value and
  18187. std::is_nothrow_move_assignable<json_value>::value
  18188. )
  18189. {
  18190. std::swap(m_type, other.m_type);
  18191. std::swap(m_value, other.m_value);
  18192. assert_invariant();
  18193. }
  18194. /*!
  18195. @brief exchanges the values
  18196. Exchanges the contents of a JSON array with those of @a other. Does not
  18197. invoke any move, copy, or swap operations on individual elements. All
  18198. iterators and references remain valid. The past-the-end iterator is
  18199. invalidated.
  18200. @param[in,out] other array to exchange the contents with
  18201. @throw type_error.310 when JSON value is not an array; example: `"cannot
  18202. use swap() with string"`
  18203. @complexity Constant.
  18204. @liveexample{The example below shows how arrays can be swapped with
  18205. `swap()`.,swap__array_t}
  18206. @since version 1.0.0
  18207. */
  18208. void swap(array_t& other)
  18209. {
  18210. // swap only works for arrays
  18211. if (JSON_HEDLEY_LIKELY(is_array()))
  18212. {
  18213. std::swap(*(m_value.array), other);
  18214. }
  18215. else
  18216. {
  18217. JSON_THROW(type_error::create(310, "cannot use swap() with " + std::string(type_name())));
  18218. }
  18219. }
  18220. /*!
  18221. @brief exchanges the values
  18222. Exchanges the contents of a JSON object with those of @a other. Does not
  18223. invoke any move, copy, or swap operations on individual elements. All
  18224. iterators and references remain valid. The past-the-end iterator is
  18225. invalidated.
  18226. @param[in,out] other object to exchange the contents with
  18227. @throw type_error.310 when JSON value is not an object; example:
  18228. `"cannot use swap() with string"`
  18229. @complexity Constant.
  18230. @liveexample{The example below shows how objects can be swapped with
  18231. `swap()`.,swap__object_t}
  18232. @since version 1.0.0
  18233. */
  18234. void swap(object_t& other)
  18235. {
  18236. // swap only works for objects
  18237. if (JSON_HEDLEY_LIKELY(is_object()))
  18238. {
  18239. std::swap(*(m_value.object), other);
  18240. }
  18241. else
  18242. {
  18243. JSON_THROW(type_error::create(310, "cannot use swap() with " + std::string(type_name())));
  18244. }
  18245. }
  18246. /*!
  18247. @brief exchanges the values
  18248. Exchanges the contents of a JSON string with those of @a other. Does not
  18249. invoke any move, copy, or swap operations on individual elements. All
  18250. iterators and references remain valid. The past-the-end iterator is
  18251. invalidated.
  18252. @param[in,out] other string to exchange the contents with
  18253. @throw type_error.310 when JSON value is not a string; example: `"cannot
  18254. use swap() with boolean"`
  18255. @complexity Constant.
  18256. @liveexample{The example below shows how strings can be swapped with
  18257. `swap()`.,swap__string_t}
  18258. @since version 1.0.0
  18259. */
  18260. void swap(string_t& other)
  18261. {
  18262. // swap only works for strings
  18263. if (JSON_HEDLEY_LIKELY(is_string()))
  18264. {
  18265. std::swap(*(m_value.string), other);
  18266. }
  18267. else
  18268. {
  18269. JSON_THROW(type_error::create(310, "cannot use swap() with " + std::string(type_name())));
  18270. }
  18271. }
  18272. /*!
  18273. @brief exchanges the values
  18274. Exchanges the contents of a JSON string with those of @a other. Does not
  18275. invoke any move, copy, or swap operations on individual elements. All
  18276. iterators and references remain valid. The past-the-end iterator is
  18277. invalidated.
  18278. @param[in,out] other binary to exchange the contents with
  18279. @throw type_error.310 when JSON value is not a string; example: `"cannot
  18280. use swap() with boolean"`
  18281. @complexity Constant.
  18282. @liveexample{The example below shows how strings can be swapped with
  18283. `swap()`.,swap__binary_t}
  18284. @since version 3.8.0
  18285. */
  18286. void swap(binary_t& other)
  18287. {
  18288. // swap only works for strings
  18289. if (JSON_HEDLEY_LIKELY(is_binary()))
  18290. {
  18291. std::swap(*(m_value.binary), other);
  18292. }
  18293. else
  18294. {
  18295. JSON_THROW(type_error::create(310, "cannot use swap() with " + std::string(type_name())));
  18296. }
  18297. }
  18298. /// @}
  18299. public:
  18300. //////////////////////////////////////////
  18301. // lexicographical comparison operators //
  18302. //////////////////////////////////////////
  18303. /// @name lexicographical comparison operators
  18304. /// @{
  18305. /*!
  18306. @brief comparison: equal
  18307. Compares two JSON values for equality according to the following rules:
  18308. - Two JSON values are equal if (1) they are from the same type and (2)
  18309. their stored values are the same according to their respective
  18310. `operator==`.
  18311. - Integer and floating-point numbers are automatically converted before
  18312. comparison. Note that two NaN values are always treated as unequal.
  18313. - Two JSON null values are equal.
  18314. @note Floating-point inside JSON values numbers are compared with
  18315. `json::number_float_t::operator==` which is `double::operator==` by
  18316. default. To compare floating-point while respecting an epsilon, an alternative
  18317. [comparison function](https://github.com/mariokonrad/marnav/blob/master/include/marnav/math/floatingpoint.hpp#L34-#L39)
  18318. could be used, for instance
  18319. @code {.cpp}
  18320. template<typename T, typename = typename std::enable_if<std::is_floating_point<T>::value, T>::type>
  18321. inline bool is_same(T a, T b, T epsilon = std::numeric_limits<T>::epsilon()) noexcept
  18322. {
  18323. return std::abs(a - b) <= epsilon;
  18324. }
  18325. @endcode
  18326. Or you can self-defined operator equal function like this:
  18327. @code {.cpp}
  18328. bool my_equal(const_reference lhs, const_reference rhs) {
  18329. const auto lhs_type lhs.type();
  18330. const auto rhs_type rhs.type();
  18331. if (lhs_type == rhs_type) {
  18332. switch(lhs_type)
  18333. // self_defined case
  18334. case value_t::number_float:
  18335. return std::abs(lhs - rhs) <= std::numeric_limits<float>::epsilon();
  18336. // other cases remain the same with the original
  18337. ...
  18338. }
  18339. ...
  18340. }
  18341. @endcode
  18342. @note NaN values never compare equal to themselves or to other NaN values.
  18343. @param[in] lhs first JSON value to consider
  18344. @param[in] rhs second JSON value to consider
  18345. @return whether the values @a lhs and @a rhs are equal
  18346. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  18347. @complexity Linear.
  18348. @liveexample{The example demonstrates comparing several JSON
  18349. types.,operator__equal}
  18350. @since version 1.0.0
  18351. */
  18352. friend bool operator==(const_reference lhs, const_reference rhs) noexcept
  18353. {
  18354. const auto lhs_type = lhs.type();
  18355. const auto rhs_type = rhs.type();
  18356. if (lhs_type == rhs_type)
  18357. {
  18358. switch (lhs_type)
  18359. {
  18360. case value_t::array:
  18361. return *lhs.m_value.array == *rhs.m_value.array;
  18362. case value_t::object:
  18363. return *lhs.m_value.object == *rhs.m_value.object;
  18364. case value_t::null:
  18365. return true;
  18366. case value_t::string:
  18367. return *lhs.m_value.string == *rhs.m_value.string;
  18368. case value_t::boolean:
  18369. return lhs.m_value.boolean == rhs.m_value.boolean;
  18370. case value_t::number_integer:
  18371. return lhs.m_value.number_integer == rhs.m_value.number_integer;
  18372. case value_t::number_unsigned:
  18373. return lhs.m_value.number_unsigned == rhs.m_value.number_unsigned;
  18374. case value_t::number_float:
  18375. return lhs.m_value.number_float == rhs.m_value.number_float;
  18376. case value_t::binary:
  18377. return *lhs.m_value.binary == *rhs.m_value.binary;
  18378. default:
  18379. return false;
  18380. }
  18381. }
  18382. else if (lhs_type == value_t::number_integer and rhs_type == value_t::number_float)
  18383. {
  18384. return static_cast<number_float_t>(lhs.m_value.number_integer) == rhs.m_value.number_float;
  18385. }
  18386. else if (lhs_type == value_t::number_float and rhs_type == value_t::number_integer)
  18387. {
  18388. return lhs.m_value.number_float == static_cast<number_float_t>(rhs.m_value.number_integer);
  18389. }
  18390. else if (lhs_type == value_t::number_unsigned and rhs_type == value_t::number_float)
  18391. {
  18392. return static_cast<number_float_t>(lhs.m_value.number_unsigned) == rhs.m_value.number_float;
  18393. }
  18394. else if (lhs_type == value_t::number_float and rhs_type == value_t::number_unsigned)
  18395. {
  18396. return lhs.m_value.number_float == static_cast<number_float_t>(rhs.m_value.number_unsigned);
  18397. }
  18398. else if (lhs_type == value_t::number_unsigned and rhs_type == value_t::number_integer)
  18399. {
  18400. return static_cast<number_integer_t>(lhs.m_value.number_unsigned) == rhs.m_value.number_integer;
  18401. }
  18402. else if (lhs_type == value_t::number_integer and rhs_type == value_t::number_unsigned)
  18403. {
  18404. return lhs.m_value.number_integer == static_cast<number_integer_t>(rhs.m_value.number_unsigned);
  18405. }
  18406. return false;
  18407. }
  18408. /*!
  18409. @brief comparison: equal
  18410. @copydoc operator==(const_reference, const_reference)
  18411. */
  18412. template<typename ScalarType, typename std::enable_if<
  18413. std::is_scalar<ScalarType>::value, int>::type = 0>
  18414. friend bool operator==(const_reference lhs, const ScalarType rhs) noexcept
  18415. {
  18416. return lhs == basic_json(rhs);
  18417. }
  18418. /*!
  18419. @brief comparison: equal
  18420. @copydoc operator==(const_reference, const_reference)
  18421. */
  18422. template<typename ScalarType, typename std::enable_if<
  18423. std::is_scalar<ScalarType>::value, int>::type = 0>
  18424. friend bool operator==(const ScalarType lhs, const_reference rhs) noexcept
  18425. {
  18426. return basic_json(lhs) == rhs;
  18427. }
  18428. /*!
  18429. @brief comparison: not equal
  18430. Compares two JSON values for inequality by calculating `not (lhs == rhs)`.
  18431. @param[in] lhs first JSON value to consider
  18432. @param[in] rhs second JSON value to consider
  18433. @return whether the values @a lhs and @a rhs are not equal
  18434. @complexity Linear.
  18435. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  18436. @liveexample{The example demonstrates comparing several JSON
  18437. types.,operator__notequal}
  18438. @since version 1.0.0
  18439. */
  18440. friend bool operator!=(const_reference lhs, const_reference rhs) noexcept
  18441. {
  18442. return not (lhs == rhs);
  18443. }
  18444. /*!
  18445. @brief comparison: not equal
  18446. @copydoc operator!=(const_reference, const_reference)
  18447. */
  18448. template<typename ScalarType, typename std::enable_if<
  18449. std::is_scalar<ScalarType>::value, int>::type = 0>
  18450. friend bool operator!=(const_reference lhs, const ScalarType rhs) noexcept
  18451. {
  18452. return lhs != basic_json(rhs);
  18453. }
  18454. /*!
  18455. @brief comparison: not equal
  18456. @copydoc operator!=(const_reference, const_reference)
  18457. */
  18458. template<typename ScalarType, typename std::enable_if<
  18459. std::is_scalar<ScalarType>::value, int>::type = 0>
  18460. friend bool operator!=(const ScalarType lhs, const_reference rhs) noexcept
  18461. {
  18462. return basic_json(lhs) != rhs;
  18463. }
  18464. /*!
  18465. @brief comparison: less than
  18466. Compares whether one JSON value @a lhs is less than another JSON value @a
  18467. rhs according to the following rules:
  18468. - If @a lhs and @a rhs have the same type, the values are compared using
  18469. the default `<` operator.
  18470. - Integer and floating-point numbers are automatically converted before
  18471. comparison
  18472. - In case @a lhs and @a rhs have different types, the values are ignored
  18473. and the order of the types is considered, see
  18474. @ref operator<(const value_t, const value_t).
  18475. @param[in] lhs first JSON value to consider
  18476. @param[in] rhs second JSON value to consider
  18477. @return whether @a lhs is less than @a rhs
  18478. @complexity Linear.
  18479. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  18480. @liveexample{The example demonstrates comparing several JSON
  18481. types.,operator__less}
  18482. @since version 1.0.0
  18483. */
  18484. friend bool operator<(const_reference lhs, const_reference rhs) noexcept
  18485. {
  18486. const auto lhs_type = lhs.type();
  18487. const auto rhs_type = rhs.type();
  18488. if (lhs_type == rhs_type)
  18489. {
  18490. switch (lhs_type)
  18491. {
  18492. case value_t::array:
  18493. // note parentheses are necessary, see
  18494. // https://github.com/nlohmann/json/issues/1530
  18495. return (*lhs.m_value.array) < (*rhs.m_value.array);
  18496. case value_t::object:
  18497. return (*lhs.m_value.object) < (*rhs.m_value.object);
  18498. case value_t::null:
  18499. return false;
  18500. case value_t::string:
  18501. return (*lhs.m_value.string) < (*rhs.m_value.string);
  18502. case value_t::boolean:
  18503. return (lhs.m_value.boolean) < (rhs.m_value.boolean);
  18504. case value_t::number_integer:
  18505. return (lhs.m_value.number_integer) < (rhs.m_value.number_integer);
  18506. case value_t::number_unsigned:
  18507. return (lhs.m_value.number_unsigned) < (rhs.m_value.number_unsigned);
  18508. case value_t::number_float:
  18509. return (lhs.m_value.number_float) < (rhs.m_value.number_float);
  18510. case value_t::binary:
  18511. return (*lhs.m_value.binary) < (*rhs.m_value.binary);
  18512. default:
  18513. return false;
  18514. }
  18515. }
  18516. else if (lhs_type == value_t::number_integer and rhs_type == value_t::number_float)
  18517. {
  18518. return static_cast<number_float_t>(lhs.m_value.number_integer) < rhs.m_value.number_float;
  18519. }
  18520. else if (lhs_type == value_t::number_float and rhs_type == value_t::number_integer)
  18521. {
  18522. return lhs.m_value.number_float < static_cast<number_float_t>(rhs.m_value.number_integer);
  18523. }
  18524. else if (lhs_type == value_t::number_unsigned and rhs_type == value_t::number_float)
  18525. {
  18526. return static_cast<number_float_t>(lhs.m_value.number_unsigned) < rhs.m_value.number_float;
  18527. }
  18528. else if (lhs_type == value_t::number_float and rhs_type == value_t::number_unsigned)
  18529. {
  18530. return lhs.m_value.number_float < static_cast<number_float_t>(rhs.m_value.number_unsigned);
  18531. }
  18532. else if (lhs_type == value_t::number_integer and rhs_type == value_t::number_unsigned)
  18533. {
  18534. return lhs.m_value.number_integer < static_cast<number_integer_t>(rhs.m_value.number_unsigned);
  18535. }
  18536. else if (lhs_type == value_t::number_unsigned and rhs_type == value_t::number_integer)
  18537. {
  18538. return static_cast<number_integer_t>(lhs.m_value.number_unsigned) < rhs.m_value.number_integer;
  18539. }
  18540. // We only reach this line if we cannot compare values. In that case,
  18541. // we compare types. Note we have to call the operator explicitly,
  18542. // because MSVC has problems otherwise.
  18543. return operator<(lhs_type, rhs_type);
  18544. }
  18545. /*!
  18546. @brief comparison: less than
  18547. @copydoc operator<(const_reference, const_reference)
  18548. */
  18549. template<typename ScalarType, typename std::enable_if<
  18550. std::is_scalar<ScalarType>::value, int>::type = 0>
  18551. friend bool operator<(const_reference lhs, const ScalarType rhs) noexcept
  18552. {
  18553. return lhs < basic_json(rhs);
  18554. }
  18555. /*!
  18556. @brief comparison: less than
  18557. @copydoc operator<(const_reference, const_reference)
  18558. */
  18559. template<typename ScalarType, typename std::enable_if<
  18560. std::is_scalar<ScalarType>::value, int>::type = 0>
  18561. friend bool operator<(const ScalarType lhs, const_reference rhs) noexcept
  18562. {
  18563. return basic_json(lhs) < rhs;
  18564. }
  18565. /*!
  18566. @brief comparison: less than or equal
  18567. Compares whether one JSON value @a lhs is less than or equal to another
  18568. JSON value by calculating `not (rhs < lhs)`.
  18569. @param[in] lhs first JSON value to consider
  18570. @param[in] rhs second JSON value to consider
  18571. @return whether @a lhs is less than or equal to @a rhs
  18572. @complexity Linear.
  18573. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  18574. @liveexample{The example demonstrates comparing several JSON
  18575. types.,operator__greater}
  18576. @since version 1.0.0
  18577. */
  18578. friend bool operator<=(const_reference lhs, const_reference rhs) noexcept
  18579. {
  18580. return not (rhs < lhs);
  18581. }
  18582. /*!
  18583. @brief comparison: less than or equal
  18584. @copydoc operator<=(const_reference, const_reference)
  18585. */
  18586. template<typename ScalarType, typename std::enable_if<
  18587. std::is_scalar<ScalarType>::value, int>::type = 0>
  18588. friend bool operator<=(const_reference lhs, const ScalarType rhs) noexcept
  18589. {
  18590. return lhs <= basic_json(rhs);
  18591. }
  18592. /*!
  18593. @brief comparison: less than or equal
  18594. @copydoc operator<=(const_reference, const_reference)
  18595. */
  18596. template<typename ScalarType, typename std::enable_if<
  18597. std::is_scalar<ScalarType>::value, int>::type = 0>
  18598. friend bool operator<=(const ScalarType lhs, const_reference rhs) noexcept
  18599. {
  18600. return basic_json(lhs) <= rhs;
  18601. }
  18602. /*!
  18603. @brief comparison: greater than
  18604. Compares whether one JSON value @a lhs is greater than another
  18605. JSON value by calculating `not (lhs <= rhs)`.
  18606. @param[in] lhs first JSON value to consider
  18607. @param[in] rhs second JSON value to consider
  18608. @return whether @a lhs is greater than to @a rhs
  18609. @complexity Linear.
  18610. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  18611. @liveexample{The example demonstrates comparing several JSON
  18612. types.,operator__lessequal}
  18613. @since version 1.0.0
  18614. */
  18615. friend bool operator>(const_reference lhs, const_reference rhs) noexcept
  18616. {
  18617. return not (lhs <= rhs);
  18618. }
  18619. /*!
  18620. @brief comparison: greater than
  18621. @copydoc operator>(const_reference, const_reference)
  18622. */
  18623. template<typename ScalarType, typename std::enable_if<
  18624. std::is_scalar<ScalarType>::value, int>::type = 0>
  18625. friend bool operator>(const_reference lhs, const ScalarType rhs) noexcept
  18626. {
  18627. return lhs > basic_json(rhs);
  18628. }
  18629. /*!
  18630. @brief comparison: greater than
  18631. @copydoc operator>(const_reference, const_reference)
  18632. */
  18633. template<typename ScalarType, typename std::enable_if<
  18634. std::is_scalar<ScalarType>::value, int>::type = 0>
  18635. friend bool operator>(const ScalarType lhs, const_reference rhs) noexcept
  18636. {
  18637. return basic_json(lhs) > rhs;
  18638. }
  18639. /*!
  18640. @brief comparison: greater than or equal
  18641. Compares whether one JSON value @a lhs is greater than or equal to another
  18642. JSON value by calculating `not (lhs < rhs)`.
  18643. @param[in] lhs first JSON value to consider
  18644. @param[in] rhs second JSON value to consider
  18645. @return whether @a lhs is greater than or equal to @a rhs
  18646. @complexity Linear.
  18647. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  18648. @liveexample{The example demonstrates comparing several JSON
  18649. types.,operator__greaterequal}
  18650. @since version 1.0.0
  18651. */
  18652. friend bool operator>=(const_reference lhs, const_reference rhs) noexcept
  18653. {
  18654. return not (lhs < rhs);
  18655. }
  18656. /*!
  18657. @brief comparison: greater than or equal
  18658. @copydoc operator>=(const_reference, const_reference)
  18659. */
  18660. template<typename ScalarType, typename std::enable_if<
  18661. std::is_scalar<ScalarType>::value, int>::type = 0>
  18662. friend bool operator>=(const_reference lhs, const ScalarType rhs) noexcept
  18663. {
  18664. return lhs >= basic_json(rhs);
  18665. }
  18666. /*!
  18667. @brief comparison: greater than or equal
  18668. @copydoc operator>=(const_reference, const_reference)
  18669. */
  18670. template<typename ScalarType, typename std::enable_if<
  18671. std::is_scalar<ScalarType>::value, int>::type = 0>
  18672. friend bool operator>=(const ScalarType lhs, const_reference rhs) noexcept
  18673. {
  18674. return basic_json(lhs) >= rhs;
  18675. }
  18676. /// @}
  18677. ///////////////////
  18678. // serialization //
  18679. ///////////////////
  18680. /// @name serialization
  18681. /// @{
  18682. /*!
  18683. @brief serialize to stream
  18684. Serialize the given JSON value @a j to the output stream @a o. The JSON
  18685. value will be serialized using the @ref dump member function.
  18686. - The indentation of the output can be controlled with the member variable
  18687. `width` of the output stream @a o. For instance, using the manipulator
  18688. `std::setw(4)` on @a o sets the indentation level to `4` and the
  18689. serialization result is the same as calling `dump(4)`.
  18690. - The indentation character can be controlled with the member variable
  18691. `fill` of the output stream @a o. For instance, the manipulator
  18692. `std::setfill('\\t')` sets indentation to use a tab character rather than
  18693. the default space character.
  18694. @param[in,out] o stream to serialize to
  18695. @param[in] j JSON value to serialize
  18696. @return the stream @a o
  18697. @throw type_error.316 if a string stored inside the JSON value is not
  18698. UTF-8 encoded
  18699. @complexity Linear.
  18700. @liveexample{The example below shows the serialization with different
  18701. parameters to `width` to adjust the indentation level.,operator_serialize}
  18702. @since version 1.0.0; indentation character added in version 3.0.0
  18703. */
  18704. friend std::ostream& operator<<(std::ostream& o, const basic_json& j)
  18705. {
  18706. // read width member and use it as indentation parameter if nonzero
  18707. const bool pretty_print = o.width() > 0;
  18708. const auto indentation = pretty_print ? o.width() : 0;
  18709. // reset width to 0 for subsequent calls to this stream
  18710. o.width(0);
  18711. // do the actual serialization
  18712. serializer s(detail::output_adapter<char>(o), o.fill());
  18713. s.dump(j, pretty_print, false, static_cast<unsigned int>(indentation));
  18714. return o;
  18715. }
  18716. /*!
  18717. @brief serialize to stream
  18718. @deprecated This stream operator is deprecated and will be removed in
  18719. future 4.0.0 of the library. Please use
  18720. @ref operator<<(std::ostream&, const basic_json&)
  18721. instead; that is, replace calls like `j >> o;` with `o << j;`.
  18722. @since version 1.0.0; deprecated since version 3.0.0
  18723. */
  18724. JSON_HEDLEY_DEPRECATED(3.0.0)
  18725. friend std::ostream& operator>>(const basic_json& j, std::ostream& o)
  18726. {
  18727. return o << j;
  18728. }
  18729. /// @}
  18730. /////////////////////
  18731. // deserialization //
  18732. /////////////////////
  18733. /// @name deserialization
  18734. /// @{
  18735. /*!
  18736. @brief deserialize from a compatible input
  18737. This function reads from a compatible input. Examples are:
  18738. - an array of 1-byte values
  18739. - strings with character/literal type with size of 1 byte
  18740. - input streams
  18741. - container with contiguous storage of 1-byte values. Compatible container
  18742. types include `std::vector`, `std::string`, `std::array`,
  18743. `std::valarray`, and `std::initializer_list`. Furthermore, C-style
  18744. arrays can be used with `std::begin()`/`std::end()`. User-defined
  18745. containers can be used as long as they implement random-access iterators
  18746. and a contiguous storage.
  18747. @pre Each element of the container has a size of 1 byte. Violating this
  18748. precondition yields undefined behavior. **This precondition is enforced
  18749. with a static assertion.**
  18750. @pre The container storage is contiguous. Violating this precondition
  18751. yields undefined behavior. **This precondition is enforced with an
  18752. assertion.**
  18753. @warning There is no way to enforce all preconditions at compile-time. If
  18754. the function is called with a noncompliant container and with
  18755. assertions switched off, the behavior is undefined and will most
  18756. likely yield segmentation violation.
  18757. @param[in] i input to read from
  18758. @param[in] cb a parser callback function of type @ref parser_callback_t
  18759. which is used to control the deserialization by filtering unwanted values
  18760. (optional)
  18761. @param[in] allow_exceptions whether to throw exceptions in case of a
  18762. parse error (optional, true by default)
  18763. @return deserialized JSON value; in case of a parse error and
  18764. @a allow_exceptions set to `false`, the return value will be
  18765. value_t::discarded.
  18766. @throw parse_error.101 if a parse error occurs; example: `""unexpected end
  18767. of input; expected string literal""`
  18768. @throw parse_error.102 if to_unicode fails or surrogate error
  18769. @throw parse_error.103 if to_unicode fails
  18770. @complexity Linear in the length of the input. The parser is a predictive
  18771. LL(1) parser. The complexity can be higher if the parser callback function
  18772. @a cb has a super-linear complexity.
  18773. @note A UTF-8 byte order mark is silently ignored.
  18774. @liveexample{The example below demonstrates the `parse()` function reading
  18775. from an array.,parse__array__parser_callback_t}
  18776. @liveexample{The example below demonstrates the `parse()` function with
  18777. and without callback function.,parse__string__parser_callback_t}
  18778. @liveexample{The example below demonstrates the `parse()` function with
  18779. and without callback function.,parse__istream__parser_callback_t}
  18780. @liveexample{The example below demonstrates the `parse()` function reading
  18781. from a contiguous container.,parse__contiguouscontainer__parser_callback_t}
  18782. @since version 2.0.3 (contiguous containers)
  18783. */
  18784. template<typename InputType>
  18785. JSON_HEDLEY_WARN_UNUSED_RESULT
  18786. static basic_json parse(InputType&& i,
  18787. const parser_callback_t cb = nullptr,
  18788. const bool allow_exceptions = true)
  18789. {
  18790. basic_json result;
  18791. parser(detail::input_adapter(std::forward<InputType>(i)), cb, allow_exceptions).parse(true, result);
  18792. return result;
  18793. }
  18794. JSON_HEDLEY_WARN_UNUSED_RESULT
  18795. static basic_json parse(detail::span_input_adapter&& i,
  18796. const parser_callback_t cb = nullptr,
  18797. const bool allow_exceptions = true)
  18798. {
  18799. basic_json result;
  18800. parser(i.get(), cb, allow_exceptions).parse(true, result);
  18801. return result;
  18802. }
  18803. template<typename InputType>
  18804. static bool accept(InputType&& i)
  18805. {
  18806. return parser(detail::input_adapter(std::forward<InputType>(i))).accept(true);
  18807. }
  18808. static bool accept(detail::span_input_adapter&& i)
  18809. {
  18810. return parser(i.get()).accept(true);
  18811. }
  18812. /*!
  18813. @brief generate SAX events
  18814. The SAX event lister must follow the interface of @ref json_sax.
  18815. This function reads from a compatible input. Examples are:
  18816. - an array of 1-byte values
  18817. - strings with character/literal type with size of 1 byte
  18818. - input streams
  18819. - container with contiguous storage of 1-byte values. Compatible container
  18820. types include `std::vector`, `std::string`, `std::array`,
  18821. `std::valarray`, and `std::initializer_list`. Furthermore, C-style
  18822. arrays can be used with `std::begin()`/`std::end()`. User-defined
  18823. containers can be used as long as they implement random-access iterators
  18824. and a contiguous storage.
  18825. @pre Each element of the container has a size of 1 byte. Violating this
  18826. precondition yields undefined behavior. **This precondition is enforced
  18827. with a static assertion.**
  18828. @pre The container storage is contiguous. Violating this precondition
  18829. yields undefined behavior. **This precondition is enforced with an
  18830. assertion.**
  18831. @warning There is no way to enforce all preconditions at compile-time. If
  18832. the function is called with a noncompliant container and with
  18833. assertions switched off, the behavior is undefined and will most
  18834. likely yield segmentation violation.
  18835. @param[in] i input to read from
  18836. @param[in,out] sax SAX event listener
  18837. @param[in] format the format to parse (JSON, CBOR, MessagePack, or UBJSON)
  18838. @param[in] strict whether the input has to be consumed completely
  18839. @return return value of the last processed SAX event
  18840. @throw parse_error.101 if a parse error occurs; example: `""unexpected end
  18841. of input; expected string literal""`
  18842. @throw parse_error.102 if to_unicode fails or surrogate error
  18843. @throw parse_error.103 if to_unicode fails
  18844. @complexity Linear in the length of the input. The parser is a predictive
  18845. LL(1) parser. The complexity can be higher if the SAX consumer @a sax has
  18846. a super-linear complexity.
  18847. @note A UTF-8 byte order mark is silently ignored.
  18848. @liveexample{The example below demonstrates the `sax_parse()` function
  18849. reading from string and processing the events with a user-defined SAX
  18850. event consumer.,sax_parse}
  18851. @since version 3.2.0
  18852. */
  18853. template <typename SAX, typename InputType>
  18854. JSON_HEDLEY_NON_NULL(2)
  18855. static bool sax_parse(InputType&& i, SAX* sax,
  18856. input_format_t format = input_format_t::json,
  18857. const bool strict = true)
  18858. {
  18859. assert(sax);
  18860. auto ia = detail::input_adapter(std::forward<InputType>(i));
  18861. return format == input_format_t::json
  18862. ? parser(std::move(ia)).sax_parse(sax, strict)
  18863. : detail::binary_reader<basic_json, decltype(ia), SAX>(std::move(ia)).sax_parse(format, sax, strict);
  18864. }
  18865. template <typename SAX>
  18866. JSON_HEDLEY_NON_NULL(2)
  18867. static bool sax_parse(detail::span_input_adapter&& i, SAX* sax,
  18868. input_format_t format = input_format_t::json,
  18869. const bool strict = true)
  18870. {
  18871. assert(sax);
  18872. auto ia = i.get();
  18873. return format == input_format_t::json
  18874. ? parser(std::move(ia)).sax_parse(sax, strict)
  18875. : detail::binary_reader<basic_json, decltype(ia), SAX>(std::move(ia)).sax_parse(format, sax, strict);
  18876. }
  18877. /*!
  18878. @brief deserialize from an iterator range with contiguous storage
  18879. This function reads from an iterator range of a container with contiguous
  18880. storage of 1-byte values. Compatible container types include
  18881. `std::vector`, `std::string`, `std::array`, `std::valarray`, and
  18882. `std::initializer_list`. Furthermore, C-style arrays can be used with
  18883. `std::begin()`/`std::end()`. User-defined containers can be used as long
  18884. as they implement random-access iterators and a contiguous storage.
  18885. @pre The iterator range is contiguous. Violating this precondition yields
  18886. undefined behavior. **This precondition is enforced with an assertion.**
  18887. @pre Each element in the range has a size of 1 byte. Violating this
  18888. precondition yields undefined behavior. **This precondition is enforced
  18889. with a static assertion.**
  18890. @warning There is no way to enforce all preconditions at compile-time. If
  18891. the function is called with noncompliant iterators and with
  18892. assertions switched off, the behavior is undefined and will most
  18893. likely yield segmentation violation.
  18894. @tparam IteratorType iterator of container with contiguous storage
  18895. @param[in] first begin of the range to parse (included)
  18896. @param[in] last end of the range to parse (excluded)
  18897. @param[in] cb a parser callback function of type @ref parser_callback_t
  18898. which is used to control the deserialization by filtering unwanted values
  18899. (optional)
  18900. @param[in] allow_exceptions whether to throw exceptions in case of a
  18901. parse error (optional, true by default)
  18902. @return deserialized JSON value; in case of a parse error and
  18903. @a allow_exceptions set to `false`, the return value will be
  18904. value_t::discarded.
  18905. @throw parse_error.101 in case of an unexpected token
  18906. @throw parse_error.102 if to_unicode fails or surrogate error
  18907. @throw parse_error.103 if to_unicode fails
  18908. @complexity Linear in the length of the input. The parser is a predictive
  18909. LL(1) parser. The complexity can be higher if the parser callback function
  18910. @a cb has a super-linear complexity.
  18911. @note A UTF-8 byte order mark is silently ignored.
  18912. @liveexample{The example below demonstrates the `parse()` function reading
  18913. from an iterator range.,parse__iteratortype__parser_callback_t}
  18914. @since version 2.0.3
  18915. */
  18916. template<class IteratorType, typename std::enable_if<
  18917. std::is_base_of<
  18918. std::random_access_iterator_tag,
  18919. typename std::iterator_traits<IteratorType>::iterator_category>::value, int>::type = 0>
  18920. static basic_json parse(IteratorType first, IteratorType last,
  18921. const parser_callback_t cb = nullptr,
  18922. const bool allow_exceptions = true)
  18923. {
  18924. basic_json result;
  18925. parser(detail::input_adapter(first, last), cb, allow_exceptions).parse(true, result);
  18926. return result;
  18927. }
  18928. template<class IteratorType, typename std::enable_if<
  18929. std::is_base_of<
  18930. std::random_access_iterator_tag,
  18931. typename std::iterator_traits<IteratorType>::iterator_category>::value, int>::type = 0>
  18932. static bool accept(IteratorType first, IteratorType last)
  18933. {
  18934. return parser(detail::input_adapter(first, last)).accept(true);
  18935. }
  18936. template<class IteratorType, class SAX, typename std::enable_if<
  18937. std::is_base_of<
  18938. std::random_access_iterator_tag,
  18939. typename std::iterator_traits<IteratorType>::iterator_category>::value, int>::type = 0>
  18940. JSON_HEDLEY_NON_NULL(3)
  18941. static bool sax_parse(IteratorType first, IteratorType last, SAX* sax)
  18942. {
  18943. return parser(detail::input_adapter(first, last)).sax_parse(sax);
  18944. }
  18945. /*!
  18946. @brief deserialize from stream
  18947. @deprecated This stream operator is deprecated and will be removed in
  18948. version 4.0.0 of the library. Please use
  18949. @ref operator>>(std::istream&, basic_json&)
  18950. instead; that is, replace calls like `j << i;` with `i >> j;`.
  18951. @since version 1.0.0; deprecated since version 3.0.0
  18952. */
  18953. JSON_HEDLEY_DEPRECATED(3.0.0)
  18954. friend std::istream& operator<<(basic_json& j, std::istream& i)
  18955. {
  18956. return operator>>(i, j);
  18957. }
  18958. /*!
  18959. @brief deserialize from stream
  18960. Deserializes an input stream to a JSON value.
  18961. @param[in,out] i input stream to read a serialized JSON value from
  18962. @param[in,out] j JSON value to write the deserialized input to
  18963. @throw parse_error.101 in case of an unexpected token
  18964. @throw parse_error.102 if to_unicode fails or surrogate error
  18965. @throw parse_error.103 if to_unicode fails
  18966. @complexity Linear in the length of the input. The parser is a predictive
  18967. LL(1) parser.
  18968. @note A UTF-8 byte order mark is silently ignored.
  18969. @liveexample{The example below shows how a JSON value is constructed by
  18970. reading a serialization from a stream.,operator_deserialize}
  18971. @sa parse(std::istream&, const parser_callback_t) for a variant with a
  18972. parser callback function to filter values while parsing
  18973. @since version 1.0.0
  18974. */
  18975. friend std::istream& operator>>(std::istream& i, basic_json& j)
  18976. {
  18977. parser(detail::input_adapter(i)).parse(false, j);
  18978. return i;
  18979. }
  18980. /// @}
  18981. ///////////////////////////
  18982. // convenience functions //
  18983. ///////////////////////////
  18984. /*!
  18985. @brief return the type as string
  18986. Returns the type name as string to be used in error messages - usually to
  18987. indicate that a function was called on a wrong JSON type.
  18988. @return a string representation of a the @a m_type member:
  18989. Value type | return value
  18990. ----------- | -------------
  18991. null | `"null"`
  18992. boolean | `"boolean"`
  18993. string | `"string"`
  18994. number | `"number"` (for all number types)
  18995. object | `"object"`
  18996. array | `"array"`
  18997. binary | `"binary"`
  18998. discarded | `"discarded"`
  18999. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  19000. @complexity Constant.
  19001. @liveexample{The following code exemplifies `type_name()` for all JSON
  19002. types.,type_name}
  19003. @sa @ref type() -- return the type of the JSON value
  19004. @sa @ref operator value_t() -- return the type of the JSON value (implicit)
  19005. @since version 1.0.0, public since 2.1.0, `const char*` and `noexcept`
  19006. since 3.0.0
  19007. */
  19008. JSON_HEDLEY_RETURNS_NON_NULL
  19009. const char* type_name() const noexcept
  19010. {
  19011. {
  19012. switch (m_type)
  19013. {
  19014. case value_t::null:
  19015. return "null";
  19016. case value_t::object:
  19017. return "object";
  19018. case value_t::array:
  19019. return "array";
  19020. case value_t::string:
  19021. return "string";
  19022. case value_t::boolean:
  19023. return "boolean";
  19024. case value_t::binary:
  19025. return "binary";
  19026. case value_t::discarded:
  19027. return "discarded";
  19028. default:
  19029. return "number";
  19030. }
  19031. }
  19032. }
  19033. private:
  19034. //////////////////////
  19035. // member variables //
  19036. //////////////////////
  19037. /// the type of the current element
  19038. value_t m_type = value_t::null;
  19039. /// the value of the current element
  19040. json_value m_value = {};
  19041. //////////////////////////////////////////
  19042. // binary serialization/deserialization //
  19043. //////////////////////////////////////////
  19044. /// @name binary serialization/deserialization support
  19045. /// @{
  19046. public:
  19047. /*!
  19048. @brief create a CBOR serialization of a given JSON value
  19049. Serializes a given JSON value @a j to a byte vector using the CBOR (Concise
  19050. Binary Object Representation) serialization format. CBOR is a binary
  19051. serialization format which aims to be more compact than JSON itself, yet
  19052. more efficient to parse.
  19053. The library uses the following mapping from JSON values types to
  19054. CBOR types according to the CBOR specification (RFC 7049):
  19055. JSON value type | value/range | CBOR type | first byte
  19056. --------------- | ------------------------------------------ | ---------------------------------- | ---------------
  19057. null | `null` | Null | 0xF6
  19058. boolean | `true` | True | 0xF5
  19059. boolean | `false` | False | 0xF4
  19060. number_integer | -9223372036854775808..-2147483649 | Negative integer (8 bytes follow) | 0x3B
  19061. number_integer | -2147483648..-32769 | Negative integer (4 bytes follow) | 0x3A
  19062. number_integer | -32768..-129 | Negative integer (2 bytes follow) | 0x39
  19063. number_integer | -128..-25 | Negative integer (1 byte follow) | 0x38
  19064. number_integer | -24..-1 | Negative integer | 0x20..0x37
  19065. number_integer | 0..23 | Integer | 0x00..0x17
  19066. number_integer | 24..255 | Unsigned integer (1 byte follow) | 0x18
  19067. number_integer | 256..65535 | Unsigned integer (2 bytes follow) | 0x19
  19068. number_integer | 65536..4294967295 | Unsigned integer (4 bytes follow) | 0x1A
  19069. number_integer | 4294967296..18446744073709551615 | Unsigned integer (8 bytes follow) | 0x1B
  19070. number_unsigned | 0..23 | Integer | 0x00..0x17
  19071. number_unsigned | 24..255 | Unsigned integer (1 byte follow) | 0x18
  19072. number_unsigned | 256..65535 | Unsigned integer (2 bytes follow) | 0x19
  19073. number_unsigned | 65536..4294967295 | Unsigned integer (4 bytes follow) | 0x1A
  19074. number_unsigned | 4294967296..18446744073709551615 | Unsigned integer (8 bytes follow) | 0x1B
  19075. number_float | *any value* | Double-Precision Float | 0xFB
  19076. string | *length*: 0..23 | UTF-8 string | 0x60..0x77
  19077. string | *length*: 23..255 | UTF-8 string (1 byte follow) | 0x78
  19078. string | *length*: 256..65535 | UTF-8 string (2 bytes follow) | 0x79
  19079. string | *length*: 65536..4294967295 | UTF-8 string (4 bytes follow) | 0x7A
  19080. string | *length*: 4294967296..18446744073709551615 | UTF-8 string (8 bytes follow) | 0x7B
  19081. array | *size*: 0..23 | array | 0x80..0x97
  19082. array | *size*: 23..255 | array (1 byte follow) | 0x98
  19083. array | *size*: 256..65535 | array (2 bytes follow) | 0x99
  19084. array | *size*: 65536..4294967295 | array (4 bytes follow) | 0x9A
  19085. array | *size*: 4294967296..18446744073709551615 | array (8 bytes follow) | 0x9B
  19086. object | *size*: 0..23 | map | 0xA0..0xB7
  19087. object | *size*: 23..255 | map (1 byte follow) | 0xB8
  19088. object | *size*: 256..65535 | map (2 bytes follow) | 0xB9
  19089. object | *size*: 65536..4294967295 | map (4 bytes follow) | 0xBA
  19090. object | *size*: 4294967296..18446744073709551615 | map (8 bytes follow) | 0xBB
  19091. binary | *size*: 0..23 | byte string | 0x40..0x57
  19092. binary | *size*: 23..255 | byte string (1 byte follow) | 0x58
  19093. binary | *size*: 256..65535 | byte string (2 bytes follow) | 0x59
  19094. binary | *size*: 65536..4294967295 | byte string (4 bytes follow) | 0x5A
  19095. binary | *size*: 4294967296..18446744073709551615 | byte string (8 bytes follow) | 0x5B
  19096. @note The mapping is **complete** in the sense that any JSON value type
  19097. can be converted to a CBOR value.
  19098. @note If NaN or Infinity are stored inside a JSON number, they are
  19099. serialized properly. This behavior differs from the @ref dump()
  19100. function which serializes NaN or Infinity to `null`.
  19101. @note The following CBOR types are not used in the conversion:
  19102. - UTF-8 strings terminated by "break" (0x7F)
  19103. - arrays terminated by "break" (0x9F)
  19104. - maps terminated by "break" (0xBF)
  19105. - byte strings terminated by "break" (0x5F)
  19106. - date/time (0xC0..0xC1)
  19107. - bignum (0xC2..0xC3)
  19108. - decimal fraction (0xC4)
  19109. - bigfloat (0xC5)
  19110. - tagged items (0xC6..0xD4, 0xD8..0xDB)
  19111. - expected conversions (0xD5..0xD7)
  19112. - simple values (0xE0..0xF3, 0xF8)
  19113. - undefined (0xF7)
  19114. - half and single-precision floats (0xF9-0xFA)
  19115. - break (0xFF)
  19116. @param[in] j JSON value to serialize
  19117. @return MessagePack serialization as byte vector
  19118. @complexity Linear in the size of the JSON value @a j.
  19119. @liveexample{The example shows the serialization of a JSON value to a byte
  19120. vector in CBOR format.,to_cbor}
  19121. @sa http://cbor.io
  19122. @sa @ref from_cbor(detail::input_adapter&&, const bool, const bool) for the
  19123. analogous deserialization
  19124. @sa @ref to_msgpack(const basic_json&) for the related MessagePack format
  19125. @sa @ref to_ubjson(const basic_json&, const bool, const bool) for the
  19126. related UBJSON format
  19127. @since version 2.0.9
  19128. */
  19129. static std::vector<uint8_t> to_cbor(const basic_json& j)
  19130. {
  19131. std::vector<uint8_t> result;
  19132. to_cbor(j, result);
  19133. return result;
  19134. }
  19135. static void to_cbor(const basic_json& j, detail::output_adapter<uint8_t> o)
  19136. {
  19137. binary_writer<uint8_t>(o).write_cbor(j);
  19138. }
  19139. static void to_cbor(const basic_json& j, detail::output_adapter<char> o)
  19140. {
  19141. binary_writer<char>(o).write_cbor(j);
  19142. }
  19143. /*!
  19144. @brief create a MessagePack serialization of a given JSON value
  19145. Serializes a given JSON value @a j to a byte vector using the MessagePack
  19146. serialization format. MessagePack is a binary serialization format which
  19147. aims to be more compact than JSON itself, yet more efficient to parse.
  19148. The library uses the following mapping from JSON values types to
  19149. MessagePack types according to the MessagePack specification:
  19150. JSON value type | value/range | MessagePack type | first byte
  19151. --------------- | --------------------------------- | ---------------- | ----------
  19152. null | `null` | nil | 0xC0
  19153. boolean | `true` | true | 0xC3
  19154. boolean | `false` | false | 0xC2
  19155. number_integer | -9223372036854775808..-2147483649 | int64 | 0xD3
  19156. number_integer | -2147483648..-32769 | int32 | 0xD2
  19157. number_integer | -32768..-129 | int16 | 0xD1
  19158. number_integer | -128..-33 | int8 | 0xD0
  19159. number_integer | -32..-1 | negative fixint | 0xE0..0xFF
  19160. number_integer | 0..127 | positive fixint | 0x00..0x7F
  19161. number_integer | 128..255 | uint 8 | 0xCC
  19162. number_integer | 256..65535 | uint 16 | 0xCD
  19163. number_integer | 65536..4294967295 | uint 32 | 0xCE
  19164. number_integer | 4294967296..18446744073709551615 | uint 64 | 0xCF
  19165. number_unsigned | 0..127 | positive fixint | 0x00..0x7F
  19166. number_unsigned | 128..255 | uint 8 | 0xCC
  19167. number_unsigned | 256..65535 | uint 16 | 0xCD
  19168. number_unsigned | 65536..4294967295 | uint 32 | 0xCE
  19169. number_unsigned | 4294967296..18446744073709551615 | uint 64 | 0xCF
  19170. number_float | *any value* | float 64 | 0xCB
  19171. string | *length*: 0..31 | fixstr | 0xA0..0xBF
  19172. string | *length*: 32..255 | str 8 | 0xD9
  19173. string | *length*: 256..65535 | str 16 | 0xDA
  19174. string | *length*: 65536..4294967295 | str 32 | 0xDB
  19175. array | *size*: 0..15 | fixarray | 0x90..0x9F
  19176. array | *size*: 16..65535 | array 16 | 0xDC
  19177. array | *size*: 65536..4294967295 | array 32 | 0xDD
  19178. object | *size*: 0..15 | fix map | 0x80..0x8F
  19179. object | *size*: 16..65535 | map 16 | 0xDE
  19180. object | *size*: 65536..4294967295 | map 32 | 0xDF
  19181. binary | *size*: 0..255 | bin 8 | 0xC4
  19182. binary | *size*: 256..65535 | bin 16 | 0xC5
  19183. binary | *size*: 65536..4294967295 | bin 32 | 0xC6
  19184. @note The mapping is **complete** in the sense that any JSON value type
  19185. can be converted to a MessagePack value.
  19186. @note The following values can **not** be converted to a MessagePack value:
  19187. - strings with more than 4294967295 bytes
  19188. - byte strings with more than 4294967295 bytes
  19189. - arrays with more than 4294967295 elements
  19190. - objects with more than 4294967295 elements
  19191. @note The following MessagePack types are not used in the conversion:
  19192. - float 32 (0xCA)
  19193. @note Any MessagePack output created @ref to_msgpack can be successfully
  19194. parsed by @ref from_msgpack.
  19195. @note If NaN or Infinity are stored inside a JSON number, they are
  19196. serialized properly. This behavior differs from the @ref dump()
  19197. function which serializes NaN or Infinity to `null`.
  19198. @param[in] j JSON value to serialize
  19199. @return MessagePack serialization as byte vector
  19200. @complexity Linear in the size of the JSON value @a j.
  19201. @liveexample{The example shows the serialization of a JSON value to a byte
  19202. vector in MessagePack format.,to_msgpack}
  19203. @sa http://msgpack.org
  19204. @sa @ref from_msgpack for the analogous deserialization
  19205. @sa @ref to_cbor(const basic_json& for the related CBOR format
  19206. @sa @ref to_ubjson(const basic_json&, const bool, const bool) for the
  19207. related UBJSON format
  19208. @since version 2.0.9
  19209. */
  19210. static std::vector<uint8_t> to_msgpack(const basic_json& j)
  19211. {
  19212. std::vector<uint8_t> result;
  19213. to_msgpack(j, result);
  19214. return result;
  19215. }
  19216. static void to_msgpack(const basic_json& j, detail::output_adapter<uint8_t> o)
  19217. {
  19218. binary_writer<uint8_t>(o).write_msgpack(j);
  19219. }
  19220. static void to_msgpack(const basic_json& j, detail::output_adapter<char> o)
  19221. {
  19222. binary_writer<char>(o).write_msgpack(j);
  19223. }
  19224. /*!
  19225. @brief create a UBJSON serialization of a given JSON value
  19226. Serializes a given JSON value @a j to a byte vector using the UBJSON
  19227. (Universal Binary JSON) serialization format. UBJSON aims to be more compact
  19228. than JSON itself, yet more efficient to parse.
  19229. The library uses the following mapping from JSON values types to
  19230. UBJSON types according to the UBJSON specification:
  19231. JSON value type | value/range | UBJSON type | marker
  19232. --------------- | --------------------------------- | ----------- | ------
  19233. null | `null` | null | `Z`
  19234. boolean | `true` | true | `T`
  19235. boolean | `false` | false | `F`
  19236. number_integer | -9223372036854775808..-2147483649 | int64 | `L`
  19237. number_integer | -2147483648..-32769 | int32 | `l`
  19238. number_integer | -32768..-129 | int16 | `I`
  19239. number_integer | -128..127 | int8 | `i`
  19240. number_integer | 128..255 | uint8 | `U`
  19241. number_integer | 256..32767 | int16 | `I`
  19242. number_integer | 32768..2147483647 | int32 | `l`
  19243. number_integer | 2147483648..9223372036854775807 | int64 | `L`
  19244. number_unsigned | 0..127 | int8 | `i`
  19245. number_unsigned | 128..255 | uint8 | `U`
  19246. number_unsigned | 256..32767 | int16 | `I`
  19247. number_unsigned | 32768..2147483647 | int32 | `l`
  19248. number_unsigned | 2147483648..9223372036854775807 | int64 | `L`
  19249. number_float | *any value* | float64 | `D`
  19250. string | *with shortest length indicator* | string | `S`
  19251. array | *see notes on optimized format* | array | `[`
  19252. object | *see notes on optimized format* | map | `{`
  19253. @note The mapping is **complete** in the sense that any JSON value type
  19254. can be converted to a UBJSON value.
  19255. @note The following values can **not** be converted to a UBJSON value:
  19256. - strings with more than 9223372036854775807 bytes (theoretical)
  19257. - unsigned integer numbers above 9223372036854775807
  19258. @note The following markers are not used in the conversion:
  19259. - `Z`: no-op values are not created.
  19260. - `C`: single-byte strings are serialized with `S` markers.
  19261. @note Any UBJSON output created @ref to_ubjson can be successfully parsed
  19262. by @ref from_ubjson.
  19263. @note If NaN or Infinity are stored inside a JSON number, they are
  19264. serialized properly. This behavior differs from the @ref dump()
  19265. function which serializes NaN or Infinity to `null`.
  19266. @note The optimized formats for containers are supported: Parameter
  19267. @a use_size adds size information to the beginning of a container and
  19268. removes the closing marker. Parameter @a use_type further checks
  19269. whether all elements of a container have the same type and adds the
  19270. type marker to the beginning of the container. The @a use_type
  19271. parameter must only be used together with @a use_size = true. Note
  19272. that @a use_size = true alone may result in larger representations -
  19273. the benefit of this parameter is that the receiving side is
  19274. immediately informed on the number of elements of the container.
  19275. @note If the JSON data contains the binary type, the value stored is a list
  19276. of integers, as suggested by the UBJSON documentation. In particular,
  19277. this means that serialization and the deserialization of a JSON
  19278. containing binary values into UBJSON and back will result in a
  19279. different JSON object.
  19280. @param[in] j JSON value to serialize
  19281. @param[in] use_size whether to add size annotations to container types
  19282. @param[in] use_type whether to add type annotations to container types
  19283. (must be combined with @a use_size = true)
  19284. @return UBJSON serialization as byte vector
  19285. @complexity Linear in the size of the JSON value @a j.
  19286. @liveexample{The example shows the serialization of a JSON value to a byte
  19287. vector in UBJSON format.,to_ubjson}
  19288. @sa http://ubjson.org
  19289. @sa @ref from_ubjson(detail::input_adapter&&, const bool, const bool) for the
  19290. analogous deserialization
  19291. @sa @ref to_cbor(const basic_json& for the related CBOR format
  19292. @sa @ref to_msgpack(const basic_json&) for the related MessagePack format
  19293. @since version 3.1.0
  19294. */
  19295. static std::vector<uint8_t> to_ubjson(const basic_json& j,
  19296. const bool use_size = false,
  19297. const bool use_type = false)
  19298. {
  19299. std::vector<uint8_t> result;
  19300. to_ubjson(j, result, use_size, use_type);
  19301. return result;
  19302. }
  19303. static void to_ubjson(const basic_json& j, detail::output_adapter<uint8_t> o,
  19304. const bool use_size = false, const bool use_type = false)
  19305. {
  19306. binary_writer<uint8_t>(o).write_ubjson(j, use_size, use_type);
  19307. }
  19308. static void to_ubjson(const basic_json& j, detail::output_adapter<char> o,
  19309. const bool use_size = false, const bool use_type = false)
  19310. {
  19311. binary_writer<char>(o).write_ubjson(j, use_size, use_type);
  19312. }
  19313. /*!
  19314. @brief Serializes the given JSON object `j` to BSON and returns a vector
  19315. containing the corresponding BSON-representation.
  19316. BSON (Binary JSON) is a binary format in which zero or more ordered key/value pairs are
  19317. stored as a single entity (a so-called document).
  19318. The library uses the following mapping from JSON values types to BSON types:
  19319. JSON value type | value/range | BSON type | marker
  19320. --------------- | --------------------------------- | ----------- | ------
  19321. null | `null` | null | 0x0A
  19322. boolean | `true`, `false` | boolean | 0x08
  19323. number_integer | -9223372036854775808..-2147483649 | int64 | 0x12
  19324. number_integer | -2147483648..2147483647 | int32 | 0x10
  19325. number_integer | 2147483648..9223372036854775807 | int64 | 0x12
  19326. number_unsigned | 0..2147483647 | int32 | 0x10
  19327. number_unsigned | 2147483648..9223372036854775807 | int64 | 0x12
  19328. number_unsigned | 9223372036854775808..18446744073709551615| -- | --
  19329. number_float | *any value* | double | 0x01
  19330. string | *any value* | string | 0x02
  19331. array | *any value* | document | 0x04
  19332. object | *any value* | document | 0x03
  19333. binary | *any value* | binary | 0x05
  19334. @warning The mapping is **incomplete**, since only JSON-objects (and things
  19335. contained therein) can be serialized to BSON.
  19336. Also, integers larger than 9223372036854775807 cannot be serialized to BSON,
  19337. and the keys may not contain U+0000, since they are serialized a
  19338. zero-terminated c-strings.
  19339. @throw out_of_range.407 if `j.is_number_unsigned() && j.get<std::uint64_t>() > 9223372036854775807`
  19340. @throw out_of_range.409 if a key in `j` contains a NULL (U+0000)
  19341. @throw type_error.317 if `!j.is_object()`
  19342. @pre The input `j` is required to be an object: `j.is_object() == true`.
  19343. @note Any BSON output created via @ref to_bson can be successfully parsed
  19344. by @ref from_bson.
  19345. @param[in] j JSON value to serialize
  19346. @return BSON serialization as byte vector
  19347. @complexity Linear in the size of the JSON value @a j.
  19348. @liveexample{The example shows the serialization of a JSON value to a byte
  19349. vector in BSON format.,to_bson}
  19350. @sa http://bsonspec.org/spec.html
  19351. @sa @ref from_bson(detail::input_adapter&&, const bool strict) for the
  19352. analogous deserialization
  19353. @sa @ref to_ubjson(const basic_json&, const bool, const bool) for the
  19354. related UBJSON format
  19355. @sa @ref to_cbor(const basic_json&) for the related CBOR format
  19356. @sa @ref to_msgpack(const basic_json&) for the related MessagePack format
  19357. */
  19358. static std::vector<uint8_t> to_bson(const basic_json& j)
  19359. {
  19360. std::vector<uint8_t> result;
  19361. to_bson(j, result);
  19362. return result;
  19363. }
  19364. /*!
  19365. @brief Serializes the given JSON object `j` to BSON and forwards the
  19366. corresponding BSON-representation to the given output_adapter `o`.
  19367. @param j The JSON object to convert to BSON.
  19368. @param o The output adapter that receives the binary BSON representation.
  19369. @pre The input `j` shall be an object: `j.is_object() == true`
  19370. @sa @ref to_bson(const basic_json&)
  19371. */
  19372. static void to_bson(const basic_json& j, detail::output_adapter<uint8_t> o)
  19373. {
  19374. binary_writer<uint8_t>(o).write_bson(j);
  19375. }
  19376. /*!
  19377. @copydoc to_bson(const basic_json&, detail::output_adapter<uint8_t>)
  19378. */
  19379. static void to_bson(const basic_json& j, detail::output_adapter<char> o)
  19380. {
  19381. binary_writer<char>(o).write_bson(j);
  19382. }
  19383. /*!
  19384. @brief create a JSON value from an input in CBOR format
  19385. Deserializes a given input @a i to a JSON value using the CBOR (Concise
  19386. Binary Object Representation) serialization format.
  19387. The library maps CBOR types to JSON value types as follows:
  19388. CBOR type | JSON value type | first byte
  19389. ---------------------- | --------------- | ----------
  19390. Integer | number_unsigned | 0x00..0x17
  19391. Unsigned integer | number_unsigned | 0x18
  19392. Unsigned integer | number_unsigned | 0x19
  19393. Unsigned integer | number_unsigned | 0x1A
  19394. Unsigned integer | number_unsigned | 0x1B
  19395. Negative integer | number_integer | 0x20..0x37
  19396. Negative integer | number_integer | 0x38
  19397. Negative integer | number_integer | 0x39
  19398. Negative integer | number_integer | 0x3A
  19399. Negative integer | number_integer | 0x3B
  19400. Byte string | binary | 0x40..0x57
  19401. Byte string | binary | 0x58
  19402. Byte string | binary | 0x59
  19403. Byte string | binary | 0x5A
  19404. Byte string | binary | 0x5B
  19405. UTF-8 string | string | 0x60..0x77
  19406. UTF-8 string | string | 0x78
  19407. UTF-8 string | string | 0x79
  19408. UTF-8 string | string | 0x7A
  19409. UTF-8 string | string | 0x7B
  19410. UTF-8 string | string | 0x7F
  19411. array | array | 0x80..0x97
  19412. array | array | 0x98
  19413. array | array | 0x99
  19414. array | array | 0x9A
  19415. array | array | 0x9B
  19416. array | array | 0x9F
  19417. map | object | 0xA0..0xB7
  19418. map | object | 0xB8
  19419. map | object | 0xB9
  19420. map | object | 0xBA
  19421. map | object | 0xBB
  19422. map | object | 0xBF
  19423. False | `false` | 0xF4
  19424. True | `true` | 0xF5
  19425. Null | `null` | 0xF6
  19426. Half-Precision Float | number_float | 0xF9
  19427. Single-Precision Float | number_float | 0xFA
  19428. Double-Precision Float | number_float | 0xFB
  19429. @warning The mapping is **incomplete** in the sense that not all CBOR
  19430. types can be converted to a JSON value. The following CBOR types
  19431. are not supported and will yield parse errors (parse_error.112):
  19432. - date/time (0xC0..0xC1)
  19433. - bignum (0xC2..0xC3)
  19434. - decimal fraction (0xC4)
  19435. - bigfloat (0xC5)
  19436. - tagged items (0xC6..0xD4, 0xD8..0xDB)
  19437. - expected conversions (0xD5..0xD7)
  19438. - simple values (0xE0..0xF3, 0xF8)
  19439. - undefined (0xF7)
  19440. @warning CBOR allows map keys of any type, whereas JSON only allows
  19441. strings as keys in object values. Therefore, CBOR maps with keys
  19442. other than UTF-8 strings are rejected (parse_error.113).
  19443. @note Any CBOR output created @ref to_cbor can be successfully parsed by
  19444. @ref from_cbor.
  19445. @param[in] i an input in CBOR format convertible to an input adapter
  19446. @param[in] strict whether to expect the input to be consumed until EOF
  19447. (true by default)
  19448. @param[in] allow_exceptions whether to throw exceptions in case of a
  19449. parse error (optional, true by default)
  19450. @return deserialized JSON value; in case of a parse error and
  19451. @a allow_exceptions set to `false`, the return value will be
  19452. value_t::discarded.
  19453. @throw parse_error.110 if the given input ends prematurely or the end of
  19454. file was not reached when @a strict was set to true
  19455. @throw parse_error.112 if unsupported features from CBOR were
  19456. used in the given input @a v or if the input is not valid CBOR
  19457. @throw parse_error.113 if a string was expected as map key, but not found
  19458. @complexity Linear in the size of the input @a i.
  19459. @liveexample{The example shows the deserialization of a byte vector in CBOR
  19460. format to a JSON value.,from_cbor}
  19461. @sa http://cbor.io
  19462. @sa @ref to_cbor(const basic_json&) for the analogous serialization
  19463. @sa @ref from_msgpack(detail::input_adapter&&, const bool, const bool) for the
  19464. related MessagePack format
  19465. @sa @ref from_ubjson(detail::input_adapter&&, const bool, const bool) for the
  19466. related UBJSON format
  19467. @since version 2.0.9; parameter @a start_index since 2.1.1; changed to
  19468. consume input adapters, removed start_index parameter, and added
  19469. @a strict parameter since 3.0.0; added @a allow_exceptions parameter
  19470. since 3.2.0
  19471. */
  19472. template<typename InputType>
  19473. JSON_HEDLEY_WARN_UNUSED_RESULT
  19474. static basic_json from_cbor(InputType&& i,
  19475. const bool strict = true,
  19476. const bool allow_exceptions = true)
  19477. {
  19478. basic_json result;
  19479. detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
  19480. auto ia = detail::input_adapter(std::forward<InputType>(i));
  19481. const bool res = binary_reader<decltype(ia)>(std::move(ia)).sax_parse(input_format_t::cbor, &sdp, strict);
  19482. return res ? result : basic_json(value_t::discarded);
  19483. }
  19484. /*!
  19485. @copydoc from_cbor(detail::input_adapter&&, const bool, const bool)
  19486. */
  19487. template<typename A1, typename A2,
  19488. detail::enable_if_t<std::is_constructible<detail::span_input_adapter, A1, A2>::value, int> = 0>
  19489. JSON_HEDLEY_WARN_UNUSED_RESULT
  19490. static basic_json from_cbor(A1 && a1, A2 && a2,
  19491. const bool strict = true,
  19492. const bool allow_exceptions = true)
  19493. {
  19494. basic_json result;
  19495. detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
  19496. const bool res = binary_reader<detail::input_buffer_adapter>(detail::span_input_adapter(std::forward<A1>(a1), std::forward<A2>(a2)).get()).sax_parse(input_format_t::cbor, &sdp, strict);
  19497. return res ? result : basic_json(value_t::discarded);
  19498. }
  19499. JSON_HEDLEY_WARN_UNUSED_RESULT
  19500. static basic_json from_cbor(detail::span_input_adapter&& i,
  19501. const bool strict = true,
  19502. const bool allow_exceptions = true)
  19503. {
  19504. basic_json result;
  19505. detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
  19506. const bool res = binary_reader<detail::input_buffer_adapter>(i.get()).sax_parse(input_format_t::cbor, &sdp, strict);
  19507. return res ? result : basic_json(value_t::discarded);
  19508. }
  19509. /*!
  19510. @brief create a JSON value from an input in MessagePack format
  19511. Deserializes a given input @a i to a JSON value using the MessagePack
  19512. serialization format.
  19513. The library maps MessagePack types to JSON value types as follows:
  19514. MessagePack type | JSON value type | first byte
  19515. ---------------- | --------------- | ----------
  19516. positive fixint | number_unsigned | 0x00..0x7F
  19517. fixmap | object | 0x80..0x8F
  19518. fixarray | array | 0x90..0x9F
  19519. fixstr | string | 0xA0..0xBF
  19520. nil | `null` | 0xC0
  19521. false | `false` | 0xC2
  19522. true | `true` | 0xC3
  19523. float 32 | number_float | 0xCA
  19524. float 64 | number_float | 0xCB
  19525. uint 8 | number_unsigned | 0xCC
  19526. uint 16 | number_unsigned | 0xCD
  19527. uint 32 | number_unsigned | 0xCE
  19528. uint 64 | number_unsigned | 0xCF
  19529. int 8 | number_integer | 0xD0
  19530. int 16 | number_integer | 0xD1
  19531. int 32 | number_integer | 0xD2
  19532. int 64 | number_integer | 0xD3
  19533. str 8 | string | 0xD9
  19534. str 16 | string | 0xDA
  19535. str 32 | string | 0xDB
  19536. array 16 | array | 0xDC
  19537. array 32 | array | 0xDD
  19538. map 16 | object | 0xDE
  19539. map 32 | object | 0xDF
  19540. bin 8 | binary | 0xC4
  19541. bin 16 | binary | 0xC5
  19542. bin 32 | binary | 0xC6
  19543. ext 8 | binary | 0xC7
  19544. ext 16 | binary | 0xC8
  19545. ext 32 | binary | 0xC9
  19546. fixext 1 | binary | 0xD4
  19547. fixext 2 | binary | 0xD5
  19548. fixext 4 | binary | 0xD6
  19549. fixext 8 | binary | 0xD7
  19550. fixext 16 | binary | 0xD8
  19551. negative fixint | number_integer | 0xE0-0xFF
  19552. @note Any MessagePack output created @ref to_msgpack can be successfully
  19553. parsed by @ref from_msgpack.
  19554. @param[in] i an input in MessagePack format convertible to an input
  19555. adapter
  19556. @param[in] strict whether to expect the input to be consumed until EOF
  19557. (true by default)
  19558. @param[in] allow_exceptions whether to throw exceptions in case of a
  19559. parse error (optional, true by default)
  19560. @return deserialized JSON value; in case of a parse error and
  19561. @a allow_exceptions set to `false`, the return value will be
  19562. value_t::discarded.
  19563. @throw parse_error.110 if the given input ends prematurely or the end of
  19564. file was not reached when @a strict was set to true
  19565. @throw parse_error.112 if unsupported features from MessagePack were
  19566. used in the given input @a i or if the input is not valid MessagePack
  19567. @throw parse_error.113 if a string was expected as map key, but not found
  19568. @complexity Linear in the size of the input @a i.
  19569. @liveexample{The example shows the deserialization of a byte vector in
  19570. MessagePack format to a JSON value.,from_msgpack}
  19571. @sa http://msgpack.org
  19572. @sa @ref to_msgpack(const basic_json&) for the analogous serialization
  19573. @sa @ref from_cbor(detail::input_adapter&&, const bool, const bool) for the
  19574. related CBOR format
  19575. @sa @ref from_ubjson(detail::input_adapter&&, const bool, const bool) for
  19576. the related UBJSON format
  19577. @sa @ref from_bson(detail::input_adapter&&, const bool, const bool) for
  19578. the related BSON format
  19579. @since version 2.0.9; parameter @a start_index since 2.1.1; changed to
  19580. consume input adapters, removed start_index parameter, and added
  19581. @a strict parameter since 3.0.0; added @a allow_exceptions parameter
  19582. since 3.2.0
  19583. */
  19584. template<typename InputType>
  19585. JSON_HEDLEY_WARN_UNUSED_RESULT
  19586. static basic_json from_msgpack(InputType&& i,
  19587. const bool strict = true,
  19588. const bool allow_exceptions = true)
  19589. {
  19590. basic_json result;
  19591. detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
  19592. auto ia = detail::input_adapter(std::forward<InputType>(i));
  19593. const bool res = binary_reader<decltype(ia)>(std::move(ia)).sax_parse(input_format_t::msgpack, &sdp, strict);
  19594. return res ? result : basic_json(value_t::discarded);
  19595. }
  19596. /*!
  19597. @copydoc from_msgpack(detail::input_adapter&&, const bool, const bool)
  19598. */
  19599. template<typename A1, typename A2,
  19600. detail::enable_if_t<std::is_constructible<detail::span_input_adapter, A1, A2>::value, int> = 0>
  19601. JSON_HEDLEY_WARN_UNUSED_RESULT
  19602. static basic_json from_msgpack(A1 && a1, A2 && a2,
  19603. const bool strict = true,
  19604. const bool allow_exceptions = true)
  19605. {
  19606. basic_json result;
  19607. detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
  19608. const bool res = binary_reader<detail::input_buffer_adapter>(detail::span_input_adapter(std::forward<A1>(a1), std::forward<A2>(a2)).get()).sax_parse(input_format_t::msgpack, &sdp, strict);
  19609. return res ? result : basic_json(value_t::discarded);
  19610. }
  19611. JSON_HEDLEY_WARN_UNUSED_RESULT
  19612. static basic_json from_msgpack(detail::span_input_adapter&& i,
  19613. const bool strict = true,
  19614. const bool allow_exceptions = true)
  19615. {
  19616. basic_json result;
  19617. detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
  19618. const bool res = binary_reader<detail::input_buffer_adapter>(i.get()).sax_parse(input_format_t::msgpack, &sdp, strict);
  19619. return res ? result : basic_json(value_t::discarded);
  19620. }
  19621. /*!
  19622. @brief create a JSON value from an input in UBJSON format
  19623. Deserializes a given input @a i to a JSON value using the UBJSON (Universal
  19624. Binary JSON) serialization format.
  19625. The library maps UBJSON types to JSON value types as follows:
  19626. UBJSON type | JSON value type | marker
  19627. ----------- | --------------------------------------- | ------
  19628. no-op | *no value, next value is read* | `N`
  19629. null | `null` | `Z`
  19630. false | `false` | `F`
  19631. true | `true` | `T`
  19632. float32 | number_float | `d`
  19633. float64 | number_float | `D`
  19634. uint8 | number_unsigned | `U`
  19635. int8 | number_integer | `i`
  19636. int16 | number_integer | `I`
  19637. int32 | number_integer | `l`
  19638. int64 | number_integer | `L`
  19639. string | string | `S`
  19640. char | string | `C`
  19641. array | array (optimized values are supported) | `[`
  19642. object | object (optimized values are supported) | `{`
  19643. @note The mapping is **complete** in the sense that any UBJSON value can
  19644. be converted to a JSON value.
  19645. @param[in] i an input in UBJSON format convertible to an input adapter
  19646. @param[in] strict whether to expect the input to be consumed until EOF
  19647. (true by default)
  19648. @param[in] allow_exceptions whether to throw exceptions in case of a
  19649. parse error (optional, true by default)
  19650. @return deserialized JSON value; in case of a parse error and
  19651. @a allow_exceptions set to `false`, the return value will be
  19652. value_t::discarded.
  19653. @throw parse_error.110 if the given input ends prematurely or the end of
  19654. file was not reached when @a strict was set to true
  19655. @throw parse_error.112 if a parse error occurs
  19656. @throw parse_error.113 if a string could not be parsed successfully
  19657. @complexity Linear in the size of the input @a i.
  19658. @liveexample{The example shows the deserialization of a byte vector in
  19659. UBJSON format to a JSON value.,from_ubjson}
  19660. @sa http://ubjson.org
  19661. @sa @ref to_ubjson(const basic_json&, const bool, const bool) for the
  19662. analogous serialization
  19663. @sa @ref from_cbor(detail::input_adapter&&, const bool, const bool) for the
  19664. related CBOR format
  19665. @sa @ref from_msgpack(detail::input_adapter&&, const bool, const bool) for
  19666. the related MessagePack format
  19667. @sa @ref from_bson(detail::input_adapter&&, const bool, const bool) for
  19668. the related BSON format
  19669. @since version 3.1.0; added @a allow_exceptions parameter since 3.2.0
  19670. */
  19671. template<typename InputType>
  19672. JSON_HEDLEY_WARN_UNUSED_RESULT
  19673. static basic_json from_ubjson(InputType&& i,
  19674. const bool strict = true,
  19675. const bool allow_exceptions = true)
  19676. {
  19677. basic_json result;
  19678. detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
  19679. auto ia = detail::input_adapter(std::forward<InputType>(i));
  19680. const bool res = binary_reader<decltype(ia)>(std::move(ia)).sax_parse(input_format_t::ubjson, &sdp, strict);
  19681. return res ? result : basic_json(value_t::discarded);
  19682. }
  19683. /*!
  19684. @copydoc from_ubjson(detail::input_adapter&&, const bool, const bool)
  19685. */
  19686. template<typename A1, typename A2,
  19687. detail::enable_if_t<std::is_constructible<detail::span_input_adapter, A1, A2>::value, int> = 0>
  19688. JSON_HEDLEY_WARN_UNUSED_RESULT
  19689. static basic_json from_ubjson(A1 && a1, A2 && a2,
  19690. const bool strict = true,
  19691. const bool allow_exceptions = true)
  19692. {
  19693. basic_json result;
  19694. detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
  19695. const bool res = binary_reader<detail::input_buffer_adapter>(detail::span_input_adapter(std::forward<A1>(a1), std::forward<A2>(a2)).get()).sax_parse(input_format_t::ubjson, &sdp, strict);
  19696. return res ? result : basic_json(value_t::discarded);
  19697. }
  19698. static basic_json from_ubjson(detail::span_input_adapter&& i,
  19699. const bool strict = true,
  19700. const bool allow_exceptions = true)
  19701. {
  19702. basic_json result;
  19703. detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
  19704. const bool res = binary_reader<detail::input_buffer_adapter>(i.get()).sax_parse(input_format_t::ubjson, &sdp, strict);
  19705. return res ? result : basic_json(value_t::discarded);
  19706. }
  19707. /*!
  19708. @brief Create a JSON value from an input in BSON format
  19709. Deserializes a given input @a i to a JSON value using the BSON (Binary JSON)
  19710. serialization format.
  19711. The library maps BSON record types to JSON value types as follows:
  19712. BSON type | BSON marker byte | JSON value type
  19713. --------------- | ---------------- | ---------------------------
  19714. double | 0x01 | number_float
  19715. string | 0x02 | string
  19716. document | 0x03 | object
  19717. array | 0x04 | array
  19718. binary | 0x05 | still unsupported
  19719. undefined | 0x06 | still unsupported
  19720. ObjectId | 0x07 | still unsupported
  19721. boolean | 0x08 | boolean
  19722. UTC Date-Time | 0x09 | still unsupported
  19723. null | 0x0A | null
  19724. Regular Expr. | 0x0B | still unsupported
  19725. DB Pointer | 0x0C | still unsupported
  19726. JavaScript Code | 0x0D | still unsupported
  19727. Symbol | 0x0E | still unsupported
  19728. JavaScript Code | 0x0F | still unsupported
  19729. int32 | 0x10 | number_integer
  19730. Timestamp | 0x11 | still unsupported
  19731. 128-bit decimal float | 0x13 | still unsupported
  19732. Max Key | 0x7F | still unsupported
  19733. Min Key | 0xFF | still unsupported
  19734. @warning The mapping is **incomplete**. The unsupported mappings
  19735. are indicated in the table above.
  19736. @param[in] i an input in BSON format convertible to an input adapter
  19737. @param[in] strict whether to expect the input to be consumed until EOF
  19738. (true by default)
  19739. @param[in] allow_exceptions whether to throw exceptions in case of a
  19740. parse error (optional, true by default)
  19741. @return deserialized JSON value; in case of a parse error and
  19742. @a allow_exceptions set to `false`, the return value will be
  19743. value_t::discarded.
  19744. @throw parse_error.114 if an unsupported BSON record type is encountered
  19745. @complexity Linear in the size of the input @a i.
  19746. @liveexample{The example shows the deserialization of a byte vector in
  19747. BSON format to a JSON value.,from_bson}
  19748. @sa http://bsonspec.org/spec.html
  19749. @sa @ref to_bson(const basic_json&) for the analogous serialization
  19750. @sa @ref from_cbor(detail::input_adapter&&, const bool, const bool) for the
  19751. related CBOR format
  19752. @sa @ref from_msgpack(detail::input_adapter&&, const bool, const bool) for
  19753. the related MessagePack format
  19754. @sa @ref from_ubjson(detail::input_adapter&&, const bool, const bool) for the
  19755. related UBJSON format
  19756. */
  19757. template<typename InputType>
  19758. JSON_HEDLEY_WARN_UNUSED_RESULT
  19759. static basic_json from_bson(InputType&& i,
  19760. const bool strict = true,
  19761. const bool allow_exceptions = true)
  19762. {
  19763. basic_json result;
  19764. detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
  19765. auto ia = detail::input_adapter(std::forward<InputType>(i));
  19766. const bool res = binary_reader<decltype(ia)>(std::move(ia)).sax_parse(input_format_t::bson, &sdp, strict);
  19767. return res ? result : basic_json(value_t::discarded);
  19768. }
  19769. /*!
  19770. @copydoc from_bson(detail::input_adapter&&, const bool, const bool)
  19771. */
  19772. template<typename A1, typename A2,
  19773. detail::enable_if_t<std::is_constructible<detail::span_input_adapter, A1, A2>::value, int> = 0>
  19774. JSON_HEDLEY_WARN_UNUSED_RESULT
  19775. static basic_json from_bson(A1 && a1, A2 && a2,
  19776. const bool strict = true,
  19777. const bool allow_exceptions = true)
  19778. {
  19779. basic_json result;
  19780. detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
  19781. const bool res = binary_reader<detail::input_buffer_adapter>(detail::span_input_adapter(std::forward<A1>(a1), std::forward<A2>(a2)).get()).sax_parse(input_format_t::bson, &sdp, strict);
  19782. return res ? result : basic_json(value_t::discarded);
  19783. }
  19784. JSON_HEDLEY_WARN_UNUSED_RESULT
  19785. static basic_json from_bson(detail::span_input_adapter&& i,
  19786. const bool strict = true,
  19787. const bool allow_exceptions = true)
  19788. {
  19789. basic_json result;
  19790. detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
  19791. const bool res = binary_reader<detail::input_buffer_adapter>(i.get()).sax_parse(input_format_t::bson, &sdp, strict);
  19792. return res ? result : basic_json(value_t::discarded);
  19793. }
  19794. /// @}
  19795. //////////////////////////
  19796. // JSON Pointer support //
  19797. //////////////////////////
  19798. /// @name JSON Pointer functions
  19799. /// @{
  19800. /*!
  19801. @brief access specified element via JSON Pointer
  19802. Uses a JSON pointer to retrieve a reference to the respective JSON value.
  19803. No bound checking is performed. Similar to @ref operator[](const typename
  19804. object_t::key_type&), `null` values are created in arrays and objects if
  19805. necessary.
  19806. In particular:
  19807. - If the JSON pointer points to an object key that does not exist, it
  19808. is created an filled with a `null` value before a reference to it
  19809. is returned.
  19810. - If the JSON pointer points to an array index that does not exist, it
  19811. is created an filled with a `null` value before a reference to it
  19812. is returned. All indices between the current maximum and the given
  19813. index are also filled with `null`.
  19814. - The special value `-` is treated as a synonym for the index past the
  19815. end.
  19816. @param[in] ptr a JSON pointer
  19817. @return reference to the element pointed to by @a ptr
  19818. @complexity Constant.
  19819. @throw parse_error.106 if an array index begins with '0'
  19820. @throw parse_error.109 if an array index was not a number
  19821. @throw out_of_range.404 if the JSON pointer can not be resolved
  19822. @liveexample{The behavior is shown in the example.,operatorjson_pointer}
  19823. @since version 2.0.0
  19824. */
  19825. reference operator[](const json_pointer& ptr)
  19826. {
  19827. return ptr.get_unchecked(this);
  19828. }
  19829. /*!
  19830. @brief access specified element via JSON Pointer
  19831. Uses a JSON pointer to retrieve a reference to the respective JSON value.
  19832. No bound checking is performed. The function does not change the JSON
  19833. value; no `null` values are created. In particular, the special value
  19834. `-` yields an exception.
  19835. @param[in] ptr JSON pointer to the desired element
  19836. @return const reference to the element pointed to by @a ptr
  19837. @complexity Constant.
  19838. @throw parse_error.106 if an array index begins with '0'
  19839. @throw parse_error.109 if an array index was not a number
  19840. @throw out_of_range.402 if the array index '-' is used
  19841. @throw out_of_range.404 if the JSON pointer can not be resolved
  19842. @liveexample{The behavior is shown in the example.,operatorjson_pointer_const}
  19843. @since version 2.0.0
  19844. */
  19845. const_reference operator[](const json_pointer& ptr) const
  19846. {
  19847. return ptr.get_unchecked(this);
  19848. }
  19849. /*!
  19850. @brief access specified element via JSON Pointer
  19851. Returns a reference to the element at with specified JSON pointer @a ptr,
  19852. with bounds checking.
  19853. @param[in] ptr JSON pointer to the desired element
  19854. @return reference to the element pointed to by @a ptr
  19855. @throw parse_error.106 if an array index in the passed JSON pointer @a ptr
  19856. begins with '0'. See example below.
  19857. @throw parse_error.109 if an array index in the passed JSON pointer @a ptr
  19858. is not a number. See example below.
  19859. @throw out_of_range.401 if an array index in the passed JSON pointer @a ptr
  19860. is out of range. See example below.
  19861. @throw out_of_range.402 if the array index '-' is used in the passed JSON
  19862. pointer @a ptr. As `at` provides checked access (and no elements are
  19863. implicitly inserted), the index '-' is always invalid. See example below.
  19864. @throw out_of_range.403 if the JSON pointer describes a key of an object
  19865. which cannot be found. See example below.
  19866. @throw out_of_range.404 if the JSON pointer @a ptr can not be resolved.
  19867. See example below.
  19868. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  19869. changes in the JSON value.
  19870. @complexity Constant.
  19871. @since version 2.0.0
  19872. @liveexample{The behavior is shown in the example.,at_json_pointer}
  19873. */
  19874. reference at(const json_pointer& ptr)
  19875. {
  19876. return ptr.get_checked(this);
  19877. }
  19878. /*!
  19879. @brief access specified element via JSON Pointer
  19880. Returns a const reference to the element at with specified JSON pointer @a
  19881. ptr, with bounds checking.
  19882. @param[in] ptr JSON pointer to the desired element
  19883. @return reference to the element pointed to by @a ptr
  19884. @throw parse_error.106 if an array index in the passed JSON pointer @a ptr
  19885. begins with '0'. See example below.
  19886. @throw parse_error.109 if an array index in the passed JSON pointer @a ptr
  19887. is not a number. See example below.
  19888. @throw out_of_range.401 if an array index in the passed JSON pointer @a ptr
  19889. is out of range. See example below.
  19890. @throw out_of_range.402 if the array index '-' is used in the passed JSON
  19891. pointer @a ptr. As `at` provides checked access (and no elements are
  19892. implicitly inserted), the index '-' is always invalid. See example below.
  19893. @throw out_of_range.403 if the JSON pointer describes a key of an object
  19894. which cannot be found. See example below.
  19895. @throw out_of_range.404 if the JSON pointer @a ptr can not be resolved.
  19896. See example below.
  19897. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  19898. changes in the JSON value.
  19899. @complexity Constant.
  19900. @since version 2.0.0
  19901. @liveexample{The behavior is shown in the example.,at_json_pointer_const}
  19902. */
  19903. const_reference at(const json_pointer& ptr) const
  19904. {
  19905. return ptr.get_checked(this);
  19906. }
  19907. /*!
  19908. @brief return flattened JSON value
  19909. The function creates a JSON object whose keys are JSON pointers (see [RFC
  19910. 6901](https://tools.ietf.org/html/rfc6901)) and whose values are all
  19911. primitive. The original JSON value can be restored using the @ref
  19912. unflatten() function.
  19913. @return an object that maps JSON pointers to primitive values
  19914. @note Empty objects and arrays are flattened to `null` and will not be
  19915. reconstructed correctly by the @ref unflatten() function.
  19916. @complexity Linear in the size the JSON value.
  19917. @liveexample{The following code shows how a JSON object is flattened to an
  19918. object whose keys consist of JSON pointers.,flatten}
  19919. @sa @ref unflatten() for the reverse function
  19920. @since version 2.0.0
  19921. */
  19922. basic_json flatten() const
  19923. {
  19924. basic_json result(value_t::object);
  19925. json_pointer::flatten("", *this, result);
  19926. return result;
  19927. }
  19928. /*!
  19929. @brief unflatten a previously flattened JSON value
  19930. The function restores the arbitrary nesting of a JSON value that has been
  19931. flattened before using the @ref flatten() function. The JSON value must
  19932. meet certain constraints:
  19933. 1. The value must be an object.
  19934. 2. The keys must be JSON pointers (see
  19935. [RFC 6901](https://tools.ietf.org/html/rfc6901))
  19936. 3. The mapped values must be primitive JSON types.
  19937. @return the original JSON from a flattened version
  19938. @note Empty objects and arrays are flattened by @ref flatten() to `null`
  19939. values and can not unflattened to their original type. Apart from
  19940. this example, for a JSON value `j`, the following is always true:
  19941. `j == j.flatten().unflatten()`.
  19942. @complexity Linear in the size the JSON value.
  19943. @throw type_error.314 if value is not an object
  19944. @throw type_error.315 if object values are not primitive
  19945. @liveexample{The following code shows how a flattened JSON object is
  19946. unflattened into the original nested JSON object.,unflatten}
  19947. @sa @ref flatten() for the reverse function
  19948. @since version 2.0.0
  19949. */
  19950. basic_json unflatten() const
  19951. {
  19952. return json_pointer::unflatten(*this);
  19953. }
  19954. /// @}
  19955. //////////////////////////
  19956. // JSON Patch functions //
  19957. //////////////////////////
  19958. /// @name JSON Patch functions
  19959. /// @{
  19960. /*!
  19961. @brief applies a JSON patch
  19962. [JSON Patch](http://jsonpatch.com) defines a JSON document structure for
  19963. expressing a sequence of operations to apply to a JSON) document. With
  19964. this function, a JSON Patch is applied to the current JSON value by
  19965. executing all operations from the patch.
  19966. @param[in] json_patch JSON patch document
  19967. @return patched document
  19968. @note The application of a patch is atomic: Either all operations succeed
  19969. and the patched document is returned or an exception is thrown. In
  19970. any case, the original value is not changed: the patch is applied
  19971. to a copy of the value.
  19972. @throw parse_error.104 if the JSON patch does not consist of an array of
  19973. objects
  19974. @throw parse_error.105 if the JSON patch is malformed (e.g., mandatory
  19975. attributes are missing); example: `"operation add must have member path"`
  19976. @throw out_of_range.401 if an array index is out of range.
  19977. @throw out_of_range.403 if a JSON pointer inside the patch could not be
  19978. resolved successfully in the current JSON value; example: `"key baz not
  19979. found"`
  19980. @throw out_of_range.405 if JSON pointer has no parent ("add", "remove",
  19981. "move")
  19982. @throw other_error.501 if "test" operation was unsuccessful
  19983. @complexity Linear in the size of the JSON value and the length of the
  19984. JSON patch. As usually only a fraction of the JSON value is affected by
  19985. the patch, the complexity can usually be neglected.
  19986. @liveexample{The following code shows how a JSON patch is applied to a
  19987. value.,patch}
  19988. @sa @ref diff -- create a JSON patch by comparing two JSON values
  19989. @sa [RFC 6902 (JSON Patch)](https://tools.ietf.org/html/rfc6902)
  19990. @sa [RFC 6901 (JSON Pointer)](https://tools.ietf.org/html/rfc6901)
  19991. @since version 2.0.0
  19992. */
  19993. basic_json patch(const basic_json& json_patch) const
  19994. {
  19995. // make a working copy to apply the patch to
  19996. basic_json result = *this;
  19997. // the valid JSON Patch operations
  19998. enum class patch_operations {add, remove, replace, move, copy, test, invalid};
  19999. const auto get_op = [](const std::string & op)
  20000. {
  20001. if (op == "add")
  20002. {
  20003. return patch_operations::add;
  20004. }
  20005. if (op == "remove")
  20006. {
  20007. return patch_operations::remove;
  20008. }
  20009. if (op == "replace")
  20010. {
  20011. return patch_operations::replace;
  20012. }
  20013. if (op == "move")
  20014. {
  20015. return patch_operations::move;
  20016. }
  20017. if (op == "copy")
  20018. {
  20019. return patch_operations::copy;
  20020. }
  20021. if (op == "test")
  20022. {
  20023. return patch_operations::test;
  20024. }
  20025. return patch_operations::invalid;
  20026. };
  20027. // wrapper for "add" operation; add value at ptr
  20028. const auto operation_add = [&result](json_pointer & ptr, basic_json val)
  20029. {
  20030. // adding to the root of the target document means replacing it
  20031. if (ptr.empty())
  20032. {
  20033. result = val;
  20034. return;
  20035. }
  20036. // make sure the top element of the pointer exists
  20037. json_pointer top_pointer = ptr.top();
  20038. if (top_pointer != ptr)
  20039. {
  20040. result.at(top_pointer);
  20041. }
  20042. // get reference to parent of JSON pointer ptr
  20043. const auto last_path = ptr.back();
  20044. ptr.pop_back();
  20045. basic_json& parent = result[ptr];
  20046. switch (parent.m_type)
  20047. {
  20048. case value_t::null:
  20049. case value_t::object:
  20050. {
  20051. // use operator[] to add value
  20052. parent[last_path] = val;
  20053. break;
  20054. }
  20055. case value_t::array:
  20056. {
  20057. if (last_path == "-")
  20058. {
  20059. // special case: append to back
  20060. parent.push_back(val);
  20061. }
  20062. else
  20063. {
  20064. const auto idx = json_pointer::array_index(last_path);
  20065. if (JSON_HEDLEY_UNLIKELY(static_cast<size_type>(idx) > parent.size()))
  20066. {
  20067. // avoid undefined behavior
  20068. JSON_THROW(out_of_range::create(401, "array index " + std::to_string(idx) + " is out of range"));
  20069. }
  20070. // default case: insert add offset
  20071. parent.insert(parent.begin() + static_cast<difference_type>(idx), val);
  20072. }
  20073. break;
  20074. }
  20075. // if there exists a parent it cannot be primitive
  20076. default: // LCOV_EXCL_LINE
  20077. assert(false); // LCOV_EXCL_LINE
  20078. }
  20079. };
  20080. // wrapper for "remove" operation; remove value at ptr
  20081. const auto operation_remove = [&result](json_pointer & ptr)
  20082. {
  20083. // get reference to parent of JSON pointer ptr
  20084. const auto last_path = ptr.back();
  20085. ptr.pop_back();
  20086. basic_json& parent = result.at(ptr);
  20087. // remove child
  20088. if (parent.is_object())
  20089. {
  20090. // perform range check
  20091. auto it = parent.find(last_path);
  20092. if (JSON_HEDLEY_LIKELY(it != parent.end()))
  20093. {
  20094. parent.erase(it);
  20095. }
  20096. else
  20097. {
  20098. JSON_THROW(out_of_range::create(403, "key '" + last_path + "' not found"));
  20099. }
  20100. }
  20101. else if (parent.is_array())
  20102. {
  20103. // note erase performs range check
  20104. parent.erase(static_cast<size_type>(json_pointer::array_index(last_path)));
  20105. }
  20106. };
  20107. // type check: top level value must be an array
  20108. if (JSON_HEDLEY_UNLIKELY(not json_patch.is_array()))
  20109. {
  20110. JSON_THROW(parse_error::create(104, 0, "JSON patch must be an array of objects"));
  20111. }
  20112. // iterate and apply the operations
  20113. for (const auto& val : json_patch)
  20114. {
  20115. // wrapper to get a value for an operation
  20116. const auto get_value = [&val](const std::string & op,
  20117. const std::string & member,
  20118. bool string_type) -> basic_json &
  20119. {
  20120. // find value
  20121. auto it = val.m_value.object->find(member);
  20122. // context-sensitive error message
  20123. const auto error_msg = (op == "op") ? "operation" : "operation '" + op + "'";
  20124. // check if desired value is present
  20125. if (JSON_HEDLEY_UNLIKELY(it == val.m_value.object->end()))
  20126. {
  20127. JSON_THROW(parse_error::create(105, 0, error_msg + " must have member '" + member + "'"));
  20128. }
  20129. // check if result is of type string
  20130. if (JSON_HEDLEY_UNLIKELY(string_type and not it->second.is_string()))
  20131. {
  20132. JSON_THROW(parse_error::create(105, 0, error_msg + " must have string member '" + member + "'"));
  20133. }
  20134. // no error: return value
  20135. return it->second;
  20136. };
  20137. // type check: every element of the array must be an object
  20138. if (JSON_HEDLEY_UNLIKELY(not val.is_object()))
  20139. {
  20140. JSON_THROW(parse_error::create(104, 0, "JSON patch must be an array of objects"));
  20141. }
  20142. // collect mandatory members
  20143. const std::string op = get_value("op", "op", true);
  20144. const std::string path = get_value(op, "path", true);
  20145. json_pointer ptr(path);
  20146. switch (get_op(op))
  20147. {
  20148. case patch_operations::add:
  20149. {
  20150. operation_add(ptr, get_value("add", "value", false));
  20151. break;
  20152. }
  20153. case patch_operations::remove:
  20154. {
  20155. operation_remove(ptr);
  20156. break;
  20157. }
  20158. case patch_operations::replace:
  20159. {
  20160. // the "path" location must exist - use at()
  20161. result.at(ptr) = get_value("replace", "value", false);
  20162. break;
  20163. }
  20164. case patch_operations::move:
  20165. {
  20166. const std::string from_path = get_value("move", "from", true);
  20167. json_pointer from_ptr(from_path);
  20168. // the "from" location must exist - use at()
  20169. basic_json v = result.at(from_ptr);
  20170. // The move operation is functionally identical to a
  20171. // "remove" operation on the "from" location, followed
  20172. // immediately by an "add" operation at the target
  20173. // location with the value that was just removed.
  20174. operation_remove(from_ptr);
  20175. operation_add(ptr, v);
  20176. break;
  20177. }
  20178. case patch_operations::copy:
  20179. {
  20180. const std::string from_path = get_value("copy", "from", true);
  20181. const json_pointer from_ptr(from_path);
  20182. // the "from" location must exist - use at()
  20183. basic_json v = result.at(from_ptr);
  20184. // The copy is functionally identical to an "add"
  20185. // operation at the target location using the value
  20186. // specified in the "from" member.
  20187. operation_add(ptr, v);
  20188. break;
  20189. }
  20190. case patch_operations::test:
  20191. {
  20192. bool success = false;
  20193. JSON_TRY
  20194. {
  20195. // check if "value" matches the one at "path"
  20196. // the "path" location must exist - use at()
  20197. success = (result.at(ptr) == get_value("test", "value", false));
  20198. }
  20199. JSON_INTERNAL_CATCH (out_of_range&)
  20200. {
  20201. // ignore out of range errors: success remains false
  20202. }
  20203. // throw an exception if test fails
  20204. if (JSON_HEDLEY_UNLIKELY(not success))
  20205. {
  20206. JSON_THROW(other_error::create(501, "unsuccessful: " + val.dump()));
  20207. }
  20208. break;
  20209. }
  20210. default:
  20211. {
  20212. // op must be "add", "remove", "replace", "move", "copy", or
  20213. // "test"
  20214. JSON_THROW(parse_error::create(105, 0, "operation value '" + op + "' is invalid"));
  20215. }
  20216. }
  20217. }
  20218. return result;
  20219. }
  20220. /*!
  20221. @brief creates a diff as a JSON patch
  20222. Creates a [JSON Patch](http://jsonpatch.com) so that value @a source can
  20223. be changed into the value @a target by calling @ref patch function.
  20224. @invariant For two JSON values @a source and @a target, the following code
  20225. yields always `true`:
  20226. @code {.cpp}
  20227. source.patch(diff(source, target)) == target;
  20228. @endcode
  20229. @note Currently, only `remove`, `add`, and `replace` operations are
  20230. generated.
  20231. @param[in] source JSON value to compare from
  20232. @param[in] target JSON value to compare against
  20233. @param[in] path helper value to create JSON pointers
  20234. @return a JSON patch to convert the @a source to @a target
  20235. @complexity Linear in the lengths of @a source and @a target.
  20236. @liveexample{The following code shows how a JSON patch is created as a
  20237. diff for two JSON values.,diff}
  20238. @sa @ref patch -- apply a JSON patch
  20239. @sa @ref merge_patch -- apply a JSON Merge Patch
  20240. @sa [RFC 6902 (JSON Patch)](https://tools.ietf.org/html/rfc6902)
  20241. @since version 2.0.0
  20242. */
  20243. JSON_HEDLEY_WARN_UNUSED_RESULT
  20244. static basic_json diff(const basic_json& source, const basic_json& target,
  20245. const std::string& path = "")
  20246. {
  20247. // the patch
  20248. basic_json result(value_t::array);
  20249. // if the values are the same, return empty patch
  20250. if (source == target)
  20251. {
  20252. return result;
  20253. }
  20254. if (source.type() != target.type())
  20255. {
  20256. // different types: replace value
  20257. result.push_back(
  20258. {
  20259. {"op", "replace"}, {"path", path}, {"value", target}
  20260. });
  20261. return result;
  20262. }
  20263. switch (source.type())
  20264. {
  20265. case value_t::array:
  20266. {
  20267. // first pass: traverse common elements
  20268. std::size_t i = 0;
  20269. while (i < source.size() and i < target.size())
  20270. {
  20271. // recursive call to compare array values at index i
  20272. auto temp_diff = diff(source[i], target[i], path + "/" + std::to_string(i));
  20273. result.insert(result.end(), temp_diff.begin(), temp_diff.end());
  20274. ++i;
  20275. }
  20276. // i now reached the end of at least one array
  20277. // in a second pass, traverse the remaining elements
  20278. // remove my remaining elements
  20279. const auto end_index = static_cast<difference_type>(result.size());
  20280. while (i < source.size())
  20281. {
  20282. // add operations in reverse order to avoid invalid
  20283. // indices
  20284. result.insert(result.begin() + end_index, object(
  20285. {
  20286. {"op", "remove"},
  20287. {"path", path + "/" + std::to_string(i)}
  20288. }));
  20289. ++i;
  20290. }
  20291. // add other remaining elements
  20292. while (i < target.size())
  20293. {
  20294. result.push_back(
  20295. {
  20296. {"op", "add"},
  20297. {"path", path + "/-"},
  20298. {"value", target[i]}
  20299. });
  20300. ++i;
  20301. }
  20302. break;
  20303. }
  20304. case value_t::object:
  20305. {
  20306. // first pass: traverse this object's elements
  20307. for (auto it = source.cbegin(); it != source.cend(); ++it)
  20308. {
  20309. // escape the key name to be used in a JSON patch
  20310. const auto key = json_pointer::escape(it.key());
  20311. if (target.find(it.key()) != target.end())
  20312. {
  20313. // recursive call to compare object values at key it
  20314. auto temp_diff = diff(it.value(), target[it.key()], path + "/" + key);
  20315. result.insert(result.end(), temp_diff.begin(), temp_diff.end());
  20316. }
  20317. else
  20318. {
  20319. // found a key that is not in o -> remove it
  20320. result.push_back(object(
  20321. {
  20322. {"op", "remove"}, {"path", path + "/" + key}
  20323. }));
  20324. }
  20325. }
  20326. // second pass: traverse other object's elements
  20327. for (auto it = target.cbegin(); it != target.cend(); ++it)
  20328. {
  20329. if (source.find(it.key()) == source.end())
  20330. {
  20331. // found a key that is not in this -> add it
  20332. const auto key = json_pointer::escape(it.key());
  20333. result.push_back(
  20334. {
  20335. {"op", "add"}, {"path", path + "/" + key},
  20336. {"value", it.value()}
  20337. });
  20338. }
  20339. }
  20340. break;
  20341. }
  20342. default:
  20343. {
  20344. // both primitive type: replace value
  20345. result.push_back(
  20346. {
  20347. {"op", "replace"}, {"path", path}, {"value", target}
  20348. });
  20349. break;
  20350. }
  20351. }
  20352. return result;
  20353. }
  20354. /// @}
  20355. ////////////////////////////////
  20356. // JSON Merge Patch functions //
  20357. ////////////////////////////////
  20358. /// @name JSON Merge Patch functions
  20359. /// @{
  20360. /*!
  20361. @brief applies a JSON Merge Patch
  20362. The merge patch format is primarily intended for use with the HTTP PATCH
  20363. method as a means of describing a set of modifications to a target
  20364. resource's content. This function applies a merge patch to the current
  20365. JSON value.
  20366. The function implements the following algorithm from Section 2 of
  20367. [RFC 7396 (JSON Merge Patch)](https://tools.ietf.org/html/rfc7396):
  20368. ```
  20369. define MergePatch(Target, Patch):
  20370. if Patch is an Object:
  20371. if Target is not an Object:
  20372. Target = {} // Ignore the contents and set it to an empty Object
  20373. for each Name/Value pair in Patch:
  20374. if Value is null:
  20375. if Name exists in Target:
  20376. remove the Name/Value pair from Target
  20377. else:
  20378. Target[Name] = MergePatch(Target[Name], Value)
  20379. return Target
  20380. else:
  20381. return Patch
  20382. ```
  20383. Thereby, `Target` is the current object; that is, the patch is applied to
  20384. the current value.
  20385. @param[in] apply_patch the patch to apply
  20386. @complexity Linear in the lengths of @a patch.
  20387. @liveexample{The following code shows how a JSON Merge Patch is applied to
  20388. a JSON document.,merge_patch}
  20389. @sa @ref patch -- apply a JSON patch
  20390. @sa [RFC 7396 (JSON Merge Patch)](https://tools.ietf.org/html/rfc7396)
  20391. @since version 3.0.0
  20392. */
  20393. void merge_patch(const basic_json& apply_patch)
  20394. {
  20395. if (apply_patch.is_object())
  20396. {
  20397. if (not is_object())
  20398. {
  20399. *this = object();
  20400. }
  20401. for (auto it = apply_patch.begin(); it != apply_patch.end(); ++it)
  20402. {
  20403. if (it.value().is_null())
  20404. {
  20405. erase(it.key());
  20406. }
  20407. else
  20408. {
  20409. operator[](it.key()).merge_patch(it.value());
  20410. }
  20411. }
  20412. }
  20413. else
  20414. {
  20415. *this = apply_patch;
  20416. }
  20417. }
  20418. /// @}
  20419. };
  20420. /*!
  20421. @brief user-defined to_string function for JSON values
  20422. This function implements a user-defined to_string for JSON objects.
  20423. @param[in] j a JSON object
  20424. @return a std::string object
  20425. */
  20426. NLOHMANN_BASIC_JSON_TPL_DECLARATION
  20427. std::string to_string(const NLOHMANN_BASIC_JSON_TPL& j)
  20428. {
  20429. return j.dump();
  20430. }
  20431. } // namespace nlohmann
  20432. ///////////////////////
  20433. // nonmember support //
  20434. ///////////////////////
  20435. // specialization of std::swap, and std::hash
  20436. namespace std
  20437. {
  20438. /// hash value for JSON objects
  20439. template<>
  20440. struct hash<nlohmann::json>
  20441. {
  20442. /*!
  20443. @brief return a hash value for a JSON object
  20444. @since version 1.0.0
  20445. */
  20446. std::size_t operator()(const nlohmann::json& j) const
  20447. {
  20448. // a naive hashing via the string representation
  20449. const auto& h = hash<nlohmann::json::string_t>();
  20450. return h(j.dump());
  20451. }
  20452. };
  20453. /// specialization for std::less<value_t>
  20454. /// @note: do not remove the space after '<',
  20455. /// see https://github.com/nlohmann/json/pull/679
  20456. template<>
  20457. struct less<::nlohmann::detail::value_t>
  20458. {
  20459. /*!
  20460. @brief compare two value_t enum values
  20461. @since version 3.0.0
  20462. */
  20463. bool operator()(nlohmann::detail::value_t lhs,
  20464. nlohmann::detail::value_t rhs) const noexcept
  20465. {
  20466. return nlohmann::detail::operator<(lhs, rhs);
  20467. }
  20468. };
  20469. /*!
  20470. @brief exchanges the values of two JSON objects
  20471. @since version 1.0.0
  20472. */
  20473. template<>
  20474. inline void swap<nlohmann::json>(nlohmann::json& j1, nlohmann::json& j2) noexcept(
  20475. is_nothrow_move_constructible<nlohmann::json>::value and
  20476. is_nothrow_move_assignable<nlohmann::json>::value
  20477. )
  20478. {
  20479. j1.swap(j2);
  20480. }
  20481. } // namespace std
  20482. /*!
  20483. @brief user-defined string literal for JSON values
  20484. This operator implements a user-defined string literal for JSON objects. It
  20485. can be used by adding `"_json"` to a string literal and returns a JSON object
  20486. if no parse error occurred.
  20487. @param[in] s a string representation of a JSON object
  20488. @param[in] n the length of string @a s
  20489. @return a JSON object
  20490. @since version 1.0.0
  20491. */
  20492. JSON_HEDLEY_NON_NULL(1)
  20493. inline nlohmann::json operator "" _json(const char* s, std::size_t n)
  20494. {
  20495. return nlohmann::json::parse(s, s + n);
  20496. }
  20497. /*!
  20498. @brief user-defined string literal for JSON pointer
  20499. This operator implements a user-defined string literal for JSON Pointers. It
  20500. can be used by adding `"_json_pointer"` to a string literal and returns a JSON pointer
  20501. object if no parse error occurred.
  20502. @param[in] s a string representation of a JSON Pointer
  20503. @param[in] n the length of string @a s
  20504. @return a JSON pointer object
  20505. @since version 2.0.0
  20506. */
  20507. JSON_HEDLEY_NON_NULL(1)
  20508. inline nlohmann::json::json_pointer operator "" _json_pointer(const char* s, std::size_t n)
  20509. {
  20510. return nlohmann::json::json_pointer(std::string(s, n));
  20511. }
  20512. // #include <nlohmann/detail/macro_unscope.hpp>
  20513. // restore GCC/clang diagnostic settings
  20514. #if defined(__clang__) || defined(__GNUC__) || defined(__GNUG__)
  20515. #pragma GCC diagnostic pop
  20516. #endif
  20517. #if defined(__clang__)
  20518. #pragma GCC diagnostic pop
  20519. #endif
  20520. // clean up
  20521. #undef JSON_INTERNAL_CATCH
  20522. #undef JSON_CATCH
  20523. #undef JSON_THROW
  20524. #undef JSON_TRY
  20525. #undef JSON_HAS_CPP_14
  20526. #undef JSON_HAS_CPP_17
  20527. #undef NLOHMANN_BASIC_JSON_TPL_DECLARATION
  20528. #undef NLOHMANN_BASIC_JSON_TPL
  20529. // #include <nlohmann/thirdparty/hedley/hedley_undef.hpp>
  20530. #undef JSON_HEDLEY_ALWAYS_INLINE
  20531. #undef JSON_HEDLEY_ARM_VERSION
  20532. #undef JSON_HEDLEY_ARM_VERSION_CHECK
  20533. #undef JSON_HEDLEY_ARRAY_PARAM
  20534. #undef JSON_HEDLEY_ASSUME
  20535. #undef JSON_HEDLEY_BEGIN_C_DECLS
  20536. #undef JSON_HEDLEY_CLANG_HAS_ATTRIBUTE
  20537. #undef JSON_HEDLEY_CLANG_HAS_BUILTIN
  20538. #undef JSON_HEDLEY_CLANG_HAS_CPP_ATTRIBUTE
  20539. #undef JSON_HEDLEY_CLANG_HAS_DECLSPEC_DECLSPEC_ATTRIBUTE
  20540. #undef JSON_HEDLEY_CLANG_HAS_EXTENSION
  20541. #undef JSON_HEDLEY_CLANG_HAS_FEATURE
  20542. #undef JSON_HEDLEY_CLANG_HAS_WARNING
  20543. #undef JSON_HEDLEY_COMPCERT_VERSION
  20544. #undef JSON_HEDLEY_COMPCERT_VERSION_CHECK
  20545. #undef JSON_HEDLEY_CONCAT
  20546. #undef JSON_HEDLEY_CONCAT3
  20547. #undef JSON_HEDLEY_CONCAT3_EX
  20548. #undef JSON_HEDLEY_CONCAT_EX
  20549. #undef JSON_HEDLEY_CONST
  20550. #undef JSON_HEDLEY_CONSTEXPR
  20551. #undef JSON_HEDLEY_CONST_CAST
  20552. #undef JSON_HEDLEY_CPP_CAST
  20553. #undef JSON_HEDLEY_CRAY_VERSION
  20554. #undef JSON_HEDLEY_CRAY_VERSION_CHECK
  20555. #undef JSON_HEDLEY_C_DECL
  20556. #undef JSON_HEDLEY_DEPRECATED
  20557. #undef JSON_HEDLEY_DEPRECATED_FOR
  20558. #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL
  20559. #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_
  20560. #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED
  20561. #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES
  20562. #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS
  20563. #undef JSON_HEDLEY_DIAGNOSTIC_POP
  20564. #undef JSON_HEDLEY_DIAGNOSTIC_PUSH
  20565. #undef JSON_HEDLEY_DMC_VERSION
  20566. #undef JSON_HEDLEY_DMC_VERSION_CHECK
  20567. #undef JSON_HEDLEY_EMPTY_BASES
  20568. #undef JSON_HEDLEY_EMSCRIPTEN_VERSION
  20569. #undef JSON_HEDLEY_EMSCRIPTEN_VERSION_CHECK
  20570. #undef JSON_HEDLEY_END_C_DECLS
  20571. #undef JSON_HEDLEY_FLAGS
  20572. #undef JSON_HEDLEY_FLAGS_CAST
  20573. #undef JSON_HEDLEY_GCC_HAS_ATTRIBUTE
  20574. #undef JSON_HEDLEY_GCC_HAS_BUILTIN
  20575. #undef JSON_HEDLEY_GCC_HAS_CPP_ATTRIBUTE
  20576. #undef JSON_HEDLEY_GCC_HAS_DECLSPEC_ATTRIBUTE
  20577. #undef JSON_HEDLEY_GCC_HAS_EXTENSION
  20578. #undef JSON_HEDLEY_GCC_HAS_FEATURE
  20579. #undef JSON_HEDLEY_GCC_HAS_WARNING
  20580. #undef JSON_HEDLEY_GCC_NOT_CLANG_VERSION_CHECK
  20581. #undef JSON_HEDLEY_GCC_VERSION
  20582. #undef JSON_HEDLEY_GCC_VERSION_CHECK
  20583. #undef JSON_HEDLEY_GNUC_HAS_ATTRIBUTE
  20584. #undef JSON_HEDLEY_GNUC_HAS_BUILTIN
  20585. #undef JSON_HEDLEY_GNUC_HAS_CPP_ATTRIBUTE
  20586. #undef JSON_HEDLEY_GNUC_HAS_DECLSPEC_ATTRIBUTE
  20587. #undef JSON_HEDLEY_GNUC_HAS_EXTENSION
  20588. #undef JSON_HEDLEY_GNUC_HAS_FEATURE
  20589. #undef JSON_HEDLEY_GNUC_HAS_WARNING
  20590. #undef JSON_HEDLEY_GNUC_VERSION
  20591. #undef JSON_HEDLEY_GNUC_VERSION_CHECK
  20592. #undef JSON_HEDLEY_HAS_ATTRIBUTE
  20593. #undef JSON_HEDLEY_HAS_BUILTIN
  20594. #undef JSON_HEDLEY_HAS_CPP_ATTRIBUTE
  20595. #undef JSON_HEDLEY_HAS_CPP_ATTRIBUTE_NS
  20596. #undef JSON_HEDLEY_HAS_DECLSPEC_ATTRIBUTE
  20597. #undef JSON_HEDLEY_HAS_EXTENSION
  20598. #undef JSON_HEDLEY_HAS_FEATURE
  20599. #undef JSON_HEDLEY_HAS_WARNING
  20600. #undef JSON_HEDLEY_IAR_VERSION
  20601. #undef JSON_HEDLEY_IAR_VERSION_CHECK
  20602. #undef JSON_HEDLEY_IBM_VERSION
  20603. #undef JSON_HEDLEY_IBM_VERSION_CHECK
  20604. #undef JSON_HEDLEY_IMPORT
  20605. #undef JSON_HEDLEY_INLINE
  20606. #undef JSON_HEDLEY_INTEL_VERSION
  20607. #undef JSON_HEDLEY_INTEL_VERSION_CHECK
  20608. #undef JSON_HEDLEY_IS_CONSTANT
  20609. #undef JSON_HEDLEY_IS_CONSTEXPR_
  20610. #undef JSON_HEDLEY_LIKELY
  20611. #undef JSON_HEDLEY_MALLOC
  20612. #undef JSON_HEDLEY_MESSAGE
  20613. #undef JSON_HEDLEY_MSVC_VERSION
  20614. #undef JSON_HEDLEY_MSVC_VERSION_CHECK
  20615. #undef JSON_HEDLEY_NEVER_INLINE
  20616. #undef JSON_HEDLEY_NON_NULL
  20617. #undef JSON_HEDLEY_NO_ESCAPE
  20618. #undef JSON_HEDLEY_NO_RETURN
  20619. #undef JSON_HEDLEY_NO_THROW
  20620. #undef JSON_HEDLEY_NULL
  20621. #undef JSON_HEDLEY_PELLES_VERSION
  20622. #undef JSON_HEDLEY_PELLES_VERSION_CHECK
  20623. #undef JSON_HEDLEY_PGI_VERSION
  20624. #undef JSON_HEDLEY_PGI_VERSION_CHECK
  20625. #undef JSON_HEDLEY_PREDICT
  20626. #undef JSON_HEDLEY_PRINTF_FORMAT
  20627. #undef JSON_HEDLEY_PRIVATE
  20628. #undef JSON_HEDLEY_PUBLIC
  20629. #undef JSON_HEDLEY_PURE
  20630. #undef JSON_HEDLEY_REINTERPRET_CAST
  20631. #undef JSON_HEDLEY_REQUIRE
  20632. #undef JSON_HEDLEY_REQUIRE_CONSTEXPR
  20633. #undef JSON_HEDLEY_REQUIRE_MSG
  20634. #undef JSON_HEDLEY_RESTRICT
  20635. #undef JSON_HEDLEY_RETURNS_NON_NULL
  20636. #undef JSON_HEDLEY_SENTINEL
  20637. #undef JSON_HEDLEY_STATIC_ASSERT
  20638. #undef JSON_HEDLEY_STATIC_CAST
  20639. #undef JSON_HEDLEY_STRINGIFY
  20640. #undef JSON_HEDLEY_STRINGIFY_EX
  20641. #undef JSON_HEDLEY_SUNPRO_VERSION
  20642. #undef JSON_HEDLEY_SUNPRO_VERSION_CHECK
  20643. #undef JSON_HEDLEY_TINYC_VERSION
  20644. #undef JSON_HEDLEY_TINYC_VERSION_CHECK
  20645. #undef JSON_HEDLEY_TI_ARMCL_VERSION
  20646. #undef JSON_HEDLEY_TI_ARMCL_VERSION_CHECK
  20647. #undef JSON_HEDLEY_TI_CL2000_VERSION
  20648. #undef JSON_HEDLEY_TI_CL2000_VERSION_CHECK
  20649. #undef JSON_HEDLEY_TI_CL430_VERSION
  20650. #undef JSON_HEDLEY_TI_CL430_VERSION_CHECK
  20651. #undef JSON_HEDLEY_TI_CL6X_VERSION
  20652. #undef JSON_HEDLEY_TI_CL6X_VERSION_CHECK
  20653. #undef JSON_HEDLEY_TI_CL7X_VERSION
  20654. #undef JSON_HEDLEY_TI_CL7X_VERSION_CHECK
  20655. #undef JSON_HEDLEY_TI_CLPRU_VERSION
  20656. #undef JSON_HEDLEY_TI_CLPRU_VERSION_CHECK
  20657. #undef JSON_HEDLEY_TI_VERSION
  20658. #undef JSON_HEDLEY_TI_VERSION_CHECK
  20659. #undef JSON_HEDLEY_UNAVAILABLE
  20660. #undef JSON_HEDLEY_UNLIKELY
  20661. #undef JSON_HEDLEY_UNPREDICTABLE
  20662. #undef JSON_HEDLEY_UNREACHABLE
  20663. #undef JSON_HEDLEY_UNREACHABLE_RETURN
  20664. #undef JSON_HEDLEY_VERSION
  20665. #undef JSON_HEDLEY_VERSION_DECODE_MAJOR
  20666. #undef JSON_HEDLEY_VERSION_DECODE_MINOR
  20667. #undef JSON_HEDLEY_VERSION_DECODE_REVISION
  20668. #undef JSON_HEDLEY_VERSION_ENCODE
  20669. #undef JSON_HEDLEY_WARNING
  20670. #undef JSON_HEDLEY_WARN_UNUSED_RESULT
  20671. #undef JSON_HEDLEY_WARN_UNUSED_RESULT_MSG
  20672. #undef JSON_HEDLEY_FALL_THROUGH
  20673. #endif // INCLUDE_NLOHMANN_JSON_HPP_