json.hpp 844 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294
  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. @brief abstract input adapter interface
  3747. Produces a stream of std::char_traits<char>::int_type characters from a
  3748. std::istream, a buffer, or some other input type. Accepts the return of
  3749. exactly one non-EOF character for future input. The int_type characters
  3750. returned consist of all valid char values as positive values (typically
  3751. unsigned char), plus an EOF value outside that range, specified by the value
  3752. of the function std::char_traits<char>::eof(). This value is typically -1, but
  3753. could be any arbitrary value which is not a valid char value.
  3754. */
  3755. struct input_adapter_protocol
  3756. {
  3757. /// get a character [0,255] or std::char_traits<char>::eof().
  3758. virtual std::char_traits<char>::int_type get_character() = 0;
  3759. virtual ~input_adapter_protocol() = default;
  3760. };
  3761. /// a type to simplify interfaces
  3762. using input_adapter_t = std::shared_ptr<input_adapter_protocol>;
  3763. /*!
  3764. Input adapter for stdio file access. This adapter read only 1 byte and do not use any
  3765. buffer. This adapter is a very low level adapter.
  3766. */
  3767. class file_input_adapter : public input_adapter_protocol
  3768. {
  3769. public:
  3770. JSON_HEDLEY_NON_NULL(2)
  3771. explicit file_input_adapter(std::FILE* f) noexcept
  3772. : m_file(f)
  3773. {}
  3774. // make class move-only
  3775. file_input_adapter(const file_input_adapter&) = delete;
  3776. file_input_adapter(file_input_adapter&&) = default;
  3777. file_input_adapter& operator=(const file_input_adapter&) = delete;
  3778. file_input_adapter& operator=(file_input_adapter&&) = default;
  3779. ~file_input_adapter() override = default;
  3780. std::char_traits<char>::int_type get_character() noexcept override
  3781. {
  3782. return std::fgetc(m_file);
  3783. }
  3784. private:
  3785. /// the file pointer to read from
  3786. std::FILE* m_file;
  3787. };
  3788. /*!
  3789. Input adapter for a (caching) istream. Ignores a UFT Byte Order Mark at
  3790. beginning of input. Does not support changing the underlying std::streambuf
  3791. in mid-input. Maintains underlying std::istream and std::streambuf to support
  3792. subsequent use of standard std::istream operations to process any input
  3793. characters following those used in parsing the JSON input. Clears the
  3794. std::istream flags; any input errors (e.g., EOF) will be detected by the first
  3795. subsequent call for input from the std::istream.
  3796. */
  3797. class input_stream_adapter : public input_adapter_protocol
  3798. {
  3799. public:
  3800. ~input_stream_adapter() override
  3801. {
  3802. // clear stream flags; we use underlying streambuf I/O, do not
  3803. // maintain ifstream flags, except eof
  3804. is.clear(is.rdstate() & std::ios::eofbit);
  3805. }
  3806. explicit input_stream_adapter(std::istream& i)
  3807. : is(i), sb(*i.rdbuf())
  3808. {}
  3809. // delete because of pointer members
  3810. input_stream_adapter(const input_stream_adapter&) = delete;
  3811. input_stream_adapter& operator=(input_stream_adapter&) = delete;
  3812. input_stream_adapter(input_stream_adapter&&) = delete;
  3813. input_stream_adapter& operator=(input_stream_adapter&&) = delete;
  3814. // std::istream/std::streambuf use std::char_traits<char>::to_int_type, to
  3815. // ensure that std::char_traits<char>::eof() and the character 0xFF do not
  3816. // end up as the same value, eg. 0xFFFFFFFF.
  3817. std::char_traits<char>::int_type get_character() override
  3818. {
  3819. auto res = sb.sbumpc();
  3820. // set eof manually, as we don't use the istream interface.
  3821. if (res == EOF)
  3822. {
  3823. is.clear(is.rdstate() | std::ios::eofbit);
  3824. }
  3825. return res;
  3826. }
  3827. private:
  3828. /// the associated input stream
  3829. std::istream& is;
  3830. std::streambuf& sb;
  3831. };
  3832. /// input adapter for buffer input
  3833. class input_buffer_adapter : public input_adapter_protocol
  3834. {
  3835. public:
  3836. input_buffer_adapter(const char* b, const std::size_t l) noexcept
  3837. : cursor(b), limit(b == nullptr ? nullptr : (b + l))
  3838. {}
  3839. // delete because of pointer members
  3840. input_buffer_adapter(const input_buffer_adapter&) = delete;
  3841. input_buffer_adapter& operator=(input_buffer_adapter&) = delete;
  3842. input_buffer_adapter(input_buffer_adapter&&) = delete;
  3843. input_buffer_adapter& operator=(input_buffer_adapter&&) = delete;
  3844. ~input_buffer_adapter() override = default;
  3845. std::char_traits<char>::int_type get_character() noexcept override
  3846. {
  3847. if (JSON_HEDLEY_LIKELY(cursor < limit))
  3848. {
  3849. assert(cursor != nullptr and limit != nullptr);
  3850. return std::char_traits<char>::to_int_type(*(cursor++));
  3851. }
  3852. return std::char_traits<char>::eof();
  3853. }
  3854. private:
  3855. /// pointer to the current character
  3856. const char* cursor;
  3857. /// pointer past the last character
  3858. const char* const limit;
  3859. };
  3860. template<typename WideStringType, size_t T>
  3861. struct wide_string_input_helper
  3862. {
  3863. // UTF-32
  3864. static void fill_buffer(const WideStringType& str,
  3865. size_t& current_wchar,
  3866. std::array<std::char_traits<char>::int_type, 4>& utf8_bytes,
  3867. size_t& utf8_bytes_index,
  3868. size_t& utf8_bytes_filled)
  3869. {
  3870. utf8_bytes_index = 0;
  3871. if (current_wchar == str.size())
  3872. {
  3873. utf8_bytes[0] = std::char_traits<char>::eof();
  3874. utf8_bytes_filled = 1;
  3875. }
  3876. else
  3877. {
  3878. // get the current character
  3879. const auto wc = static_cast<unsigned int>(str[current_wchar++]);
  3880. // UTF-32 to UTF-8 encoding
  3881. if (wc < 0x80)
  3882. {
  3883. utf8_bytes[0] = static_cast<std::char_traits<char>::int_type>(wc);
  3884. utf8_bytes_filled = 1;
  3885. }
  3886. else if (wc <= 0x7FF)
  3887. {
  3888. utf8_bytes[0] = static_cast<std::char_traits<char>::int_type>(0xC0u | ((wc >> 6u) & 0x1Fu));
  3889. utf8_bytes[1] = static_cast<std::char_traits<char>::int_type>(0x80u | (wc & 0x3Fu));
  3890. utf8_bytes_filled = 2;
  3891. }
  3892. else if (wc <= 0xFFFF)
  3893. {
  3894. utf8_bytes[0] = static_cast<std::char_traits<char>::int_type>(0xE0u | ((wc >> 12u) & 0x0Fu));
  3895. utf8_bytes[1] = static_cast<std::char_traits<char>::int_type>(0x80u | ((wc >> 6u) & 0x3Fu));
  3896. utf8_bytes[2] = static_cast<std::char_traits<char>::int_type>(0x80u | (wc & 0x3Fu));
  3897. utf8_bytes_filled = 3;
  3898. }
  3899. else if (wc <= 0x10FFFF)
  3900. {
  3901. utf8_bytes[0] = static_cast<std::char_traits<char>::int_type>(0xF0u | ((wc >> 18u) & 0x07u));
  3902. utf8_bytes[1] = static_cast<std::char_traits<char>::int_type>(0x80u | ((wc >> 12u) & 0x3Fu));
  3903. utf8_bytes[2] = static_cast<std::char_traits<char>::int_type>(0x80u | ((wc >> 6u) & 0x3Fu));
  3904. utf8_bytes[3] = static_cast<std::char_traits<char>::int_type>(0x80u | (wc & 0x3Fu));
  3905. utf8_bytes_filled = 4;
  3906. }
  3907. else
  3908. {
  3909. // unknown character
  3910. utf8_bytes[0] = static_cast<std::char_traits<char>::int_type>(wc);
  3911. utf8_bytes_filled = 1;
  3912. }
  3913. }
  3914. }
  3915. };
  3916. template<typename WideStringType>
  3917. struct wide_string_input_helper<WideStringType, 2>
  3918. {
  3919. // UTF-16
  3920. static void fill_buffer(const WideStringType& str,
  3921. size_t& current_wchar,
  3922. std::array<std::char_traits<char>::int_type, 4>& utf8_bytes,
  3923. size_t& utf8_bytes_index,
  3924. size_t& utf8_bytes_filled)
  3925. {
  3926. utf8_bytes_index = 0;
  3927. if (current_wchar == str.size())
  3928. {
  3929. utf8_bytes[0] = std::char_traits<char>::eof();
  3930. utf8_bytes_filled = 1;
  3931. }
  3932. else
  3933. {
  3934. // get the current character
  3935. const auto wc = static_cast<unsigned int>(str[current_wchar++]);
  3936. // UTF-16 to UTF-8 encoding
  3937. if (wc < 0x80)
  3938. {
  3939. utf8_bytes[0] = static_cast<std::char_traits<char>::int_type>(wc);
  3940. utf8_bytes_filled = 1;
  3941. }
  3942. else if (wc <= 0x7FF)
  3943. {
  3944. utf8_bytes[0] = static_cast<std::char_traits<char>::int_type>(0xC0u | ((wc >> 6u)));
  3945. utf8_bytes[1] = static_cast<std::char_traits<char>::int_type>(0x80u | (wc & 0x3Fu));
  3946. utf8_bytes_filled = 2;
  3947. }
  3948. else if (0xD800 > wc or wc >= 0xE000)
  3949. {
  3950. utf8_bytes[0] = static_cast<std::char_traits<char>::int_type>(0xE0u | ((wc >> 12u)));
  3951. utf8_bytes[1] = static_cast<std::char_traits<char>::int_type>(0x80u | ((wc >> 6u) & 0x3Fu));
  3952. utf8_bytes[2] = static_cast<std::char_traits<char>::int_type>(0x80u | (wc & 0x3Fu));
  3953. utf8_bytes_filled = 3;
  3954. }
  3955. else
  3956. {
  3957. if (current_wchar < str.size())
  3958. {
  3959. const auto wc2 = static_cast<unsigned int>(str[current_wchar++]);
  3960. const auto charcode = 0x10000u + (((wc & 0x3FFu) << 10u) | (wc2 & 0x3FFu));
  3961. utf8_bytes[0] = static_cast<std::char_traits<char>::int_type>(0xF0u | (charcode >> 18u));
  3962. utf8_bytes[1] = static_cast<std::char_traits<char>::int_type>(0x80u | ((charcode >> 12u) & 0x3Fu));
  3963. utf8_bytes[2] = static_cast<std::char_traits<char>::int_type>(0x80u | ((charcode >> 6u) & 0x3Fu));
  3964. utf8_bytes[3] = static_cast<std::char_traits<char>::int_type>(0x80u | (charcode & 0x3Fu));
  3965. utf8_bytes_filled = 4;
  3966. }
  3967. else
  3968. {
  3969. // unknown character
  3970. ++current_wchar;
  3971. utf8_bytes[0] = static_cast<std::char_traits<char>::int_type>(wc);
  3972. utf8_bytes_filled = 1;
  3973. }
  3974. }
  3975. }
  3976. }
  3977. };
  3978. template<typename WideStringType>
  3979. class wide_string_input_adapter : public input_adapter_protocol
  3980. {
  3981. public:
  3982. explicit wide_string_input_adapter(const WideStringType& w) noexcept
  3983. : str(w)
  3984. {}
  3985. std::char_traits<char>::int_type get_character() noexcept override
  3986. {
  3987. // check if buffer needs to be filled
  3988. if (utf8_bytes_index == utf8_bytes_filled)
  3989. {
  3990. fill_buffer<sizeof(typename WideStringType::value_type)>();
  3991. assert(utf8_bytes_filled > 0);
  3992. assert(utf8_bytes_index == 0);
  3993. }
  3994. // use buffer
  3995. assert(utf8_bytes_filled > 0);
  3996. assert(utf8_bytes_index < utf8_bytes_filled);
  3997. return utf8_bytes[utf8_bytes_index++];
  3998. }
  3999. private:
  4000. template<size_t T>
  4001. void fill_buffer()
  4002. {
  4003. wide_string_input_helper<WideStringType, T>::fill_buffer(str, current_wchar, utf8_bytes, utf8_bytes_index, utf8_bytes_filled);
  4004. }
  4005. /// the wstring to process
  4006. const WideStringType& str;
  4007. /// index of the current wchar in str
  4008. std::size_t current_wchar = 0;
  4009. /// a buffer for UTF-8 bytes
  4010. std::array<std::char_traits<char>::int_type, 4> utf8_bytes = {{0, 0, 0, 0}};
  4011. /// index to the utf8_codes array for the next valid byte
  4012. std::size_t utf8_bytes_index = 0;
  4013. /// number of valid bytes in the utf8_codes array
  4014. std::size_t utf8_bytes_filled = 0;
  4015. };
  4016. class input_adapter
  4017. {
  4018. public:
  4019. // native support
  4020. JSON_HEDLEY_NON_NULL(2)
  4021. input_adapter(std::FILE* file)
  4022. : ia(std::make_shared<file_input_adapter>(file)) {}
  4023. /// input adapter for input stream
  4024. input_adapter(std::istream& i)
  4025. : ia(std::make_shared<input_stream_adapter>(i)) {}
  4026. /// input adapter for input stream
  4027. input_adapter(std::istream&& i)
  4028. : ia(std::make_shared<input_stream_adapter>(i)) {}
  4029. input_adapter(const std::wstring& ws)
  4030. : ia(std::make_shared<wide_string_input_adapter<std::wstring>>(ws)) {}
  4031. input_adapter(const std::u16string& ws)
  4032. : ia(std::make_shared<wide_string_input_adapter<std::u16string>>(ws)) {}
  4033. input_adapter(const std::u32string& ws)
  4034. : ia(std::make_shared<wide_string_input_adapter<std::u32string>>(ws)) {}
  4035. /// input adapter for buffer
  4036. template<typename CharT,
  4037. typename std::enable_if<
  4038. std::is_pointer<CharT>::value and
  4039. std::is_integral<typename std::remove_pointer<CharT>::type>::value and
  4040. sizeof(typename std::remove_pointer<CharT>::type) == 1,
  4041. int>::type = 0>
  4042. input_adapter(CharT b, std::size_t l)
  4043. : ia(std::make_shared<input_buffer_adapter>(reinterpret_cast<const char*>(b), l)) {}
  4044. // derived support
  4045. /// input adapter for string literal
  4046. template<typename CharT,
  4047. typename std::enable_if<
  4048. std::is_pointer<CharT>::value and
  4049. std::is_integral<typename std::remove_pointer<CharT>::type>::value and
  4050. sizeof(typename std::remove_pointer<CharT>::type) == 1,
  4051. int>::type = 0>
  4052. input_adapter(CharT b)
  4053. : input_adapter(reinterpret_cast<const char*>(b),
  4054. std::strlen(reinterpret_cast<const char*>(b))) {}
  4055. /// input adapter for iterator range with contiguous storage
  4056. template<class IteratorType,
  4057. typename std::enable_if<
  4058. std::is_same<typename iterator_traits<IteratorType>::iterator_category, std::random_access_iterator_tag>::value,
  4059. int>::type = 0>
  4060. input_adapter(IteratorType first, IteratorType last)
  4061. {
  4062. #ifndef NDEBUG
  4063. // assertion to check that the iterator range is indeed contiguous,
  4064. // see https://stackoverflow.com/a/35008842/266378 for more discussion
  4065. const auto is_contiguous = std::accumulate(
  4066. first, last, std::pair<bool, int>(true, 0),
  4067. [&first](std::pair<bool, int> res, decltype(*first) val)
  4068. {
  4069. res.first &= (val == *(std::next(std::addressof(*first), res.second++)));
  4070. return res;
  4071. }).first;
  4072. assert(is_contiguous);
  4073. #endif
  4074. // assertion to check that each element is 1 byte long
  4075. static_assert(
  4076. sizeof(typename iterator_traits<IteratorType>::value_type) == 1,
  4077. "each element in the iterator range must have the size of 1 byte");
  4078. const auto len = static_cast<size_t>(std::distance(first, last));
  4079. if (JSON_HEDLEY_LIKELY(len > 0))
  4080. {
  4081. // there is at least one element: use the address of first
  4082. ia = std::make_shared<input_buffer_adapter>(reinterpret_cast<const char*>(&(*first)), len);
  4083. }
  4084. else
  4085. {
  4086. // the address of first cannot be used: use nullptr
  4087. ia = std::make_shared<input_buffer_adapter>(nullptr, len);
  4088. }
  4089. }
  4090. /// input adapter for array
  4091. template<class T, std::size_t N>
  4092. input_adapter(T (&array)[N])
  4093. : input_adapter(std::begin(array), std::end(array)) {}
  4094. /// input adapter for contiguous container
  4095. template<class ContiguousContainer, typename
  4096. std::enable_if<not std::is_pointer<ContiguousContainer>::value and
  4097. std::is_base_of<std::random_access_iterator_tag, typename iterator_traits<decltype(std::begin(std::declval<ContiguousContainer const>()))>::iterator_category>::value,
  4098. int>::type = 0>
  4099. input_adapter(const ContiguousContainer& c)
  4100. : input_adapter(std::begin(c), std::end(c)) {}
  4101. operator input_adapter_t()
  4102. {
  4103. return ia;
  4104. }
  4105. private:
  4106. /// the actual adapter
  4107. input_adapter_t ia = nullptr;
  4108. };
  4109. } // namespace detail
  4110. } // namespace nlohmann
  4111. // #include <nlohmann/detail/input/json_sax.hpp>
  4112. #include <cassert> // assert
  4113. #include <cstddef>
  4114. #include <string> // string
  4115. #include <utility> // move
  4116. #include <vector> // vector
  4117. // #include <nlohmann/detail/exceptions.hpp>
  4118. // #include <nlohmann/detail/macro_scope.hpp>
  4119. namespace nlohmann
  4120. {
  4121. /*!
  4122. @brief SAX interface
  4123. This class describes the SAX interface used by @ref nlohmann::json::sax_parse.
  4124. Each function is called in different situations while the input is parsed. The
  4125. boolean return value informs the parser whether to continue processing the
  4126. input.
  4127. */
  4128. template<typename BasicJsonType>
  4129. struct json_sax
  4130. {
  4131. /// type for (signed) integers
  4132. using number_integer_t = typename BasicJsonType::number_integer_t;
  4133. /// type for unsigned integers
  4134. using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
  4135. /// type for floating-point numbers
  4136. using number_float_t = typename BasicJsonType::number_float_t;
  4137. /// type for strings
  4138. using string_t = typename BasicJsonType::string_t;
  4139. using binary_t = typename BasicJsonType::binary_t;
  4140. /*!
  4141. @brief a null value was read
  4142. @return whether parsing should proceed
  4143. */
  4144. virtual bool null() = 0;
  4145. /*!
  4146. @brief a boolean value was read
  4147. @param[in] val boolean value
  4148. @return whether parsing should proceed
  4149. */
  4150. virtual bool boolean(bool val) = 0;
  4151. /*!
  4152. @brief an integer number was read
  4153. @param[in] val integer value
  4154. @return whether parsing should proceed
  4155. */
  4156. virtual bool number_integer(number_integer_t val) = 0;
  4157. /*!
  4158. @brief an unsigned integer number was read
  4159. @param[in] val unsigned integer value
  4160. @return whether parsing should proceed
  4161. */
  4162. virtual bool number_unsigned(number_unsigned_t val) = 0;
  4163. /*!
  4164. @brief an floating-point number was read
  4165. @param[in] val floating-point value
  4166. @param[in] s raw token value
  4167. @return whether parsing should proceed
  4168. */
  4169. virtual bool number_float(number_float_t val, const string_t& s) = 0;
  4170. /*!
  4171. @brief a string was read
  4172. @param[in] val string value
  4173. @return whether parsing should proceed
  4174. @note It is safe to move the passed string.
  4175. */
  4176. virtual bool string(string_t& val) = 0;
  4177. /*!
  4178. @brief a binary string was read
  4179. @param[in] val binary value
  4180. @return whether parsing should proceed
  4181. @note It is safe to move the passed binary.
  4182. */
  4183. virtual bool binary(binary_t& val) = 0;
  4184. /*!
  4185. @brief the beginning of an object was read
  4186. @param[in] elements number of object elements or -1 if unknown
  4187. @return whether parsing should proceed
  4188. @note binary formats may report the number of elements
  4189. */
  4190. virtual bool start_object(std::size_t elements) = 0;
  4191. /*!
  4192. @brief an object key was read
  4193. @param[in] val object key
  4194. @return whether parsing should proceed
  4195. @note It is safe to move the passed string.
  4196. */
  4197. virtual bool key(string_t& val) = 0;
  4198. /*!
  4199. @brief the end of an object was read
  4200. @return whether parsing should proceed
  4201. */
  4202. virtual bool end_object() = 0;
  4203. /*!
  4204. @brief the beginning of an array was read
  4205. @param[in] elements number of array elements or -1 if unknown
  4206. @return whether parsing should proceed
  4207. @note binary formats may report the number of elements
  4208. */
  4209. virtual bool start_array(std::size_t elements) = 0;
  4210. /*!
  4211. @brief the end of an array was read
  4212. @return whether parsing should proceed
  4213. */
  4214. virtual bool end_array() = 0;
  4215. /*!
  4216. @brief a parse error occurred
  4217. @param[in] position the position in the input where the error occurs
  4218. @param[in] last_token the last read token
  4219. @param[in] ex an exception object describing the error
  4220. @return whether parsing should proceed (must return false)
  4221. */
  4222. virtual bool parse_error(std::size_t position,
  4223. const std::string& last_token,
  4224. const detail::exception& ex) = 0;
  4225. virtual ~json_sax() = default;
  4226. };
  4227. namespace detail
  4228. {
  4229. /*!
  4230. @brief SAX implementation to create a JSON value from SAX events
  4231. This class implements the @ref json_sax interface and processes the SAX events
  4232. to create a JSON value which makes it basically a DOM parser. The structure or
  4233. hierarchy of the JSON value is managed by the stack `ref_stack` which contains
  4234. a pointer to the respective array or object for each recursion depth.
  4235. After successful parsing, the value that is passed by reference to the
  4236. constructor contains the parsed value.
  4237. @tparam BasicJsonType the JSON type
  4238. */
  4239. template<typename BasicJsonType>
  4240. class json_sax_dom_parser
  4241. {
  4242. public:
  4243. using number_integer_t = typename BasicJsonType::number_integer_t;
  4244. using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
  4245. using number_float_t = typename BasicJsonType::number_float_t;
  4246. using string_t = typename BasicJsonType::string_t;
  4247. using binary_t = typename BasicJsonType::binary_t;
  4248. /*!
  4249. @param[in, out] r reference to a JSON value that is manipulated while
  4250. parsing
  4251. @param[in] allow_exceptions_ whether parse errors yield exceptions
  4252. */
  4253. explicit json_sax_dom_parser(BasicJsonType& r, const bool allow_exceptions_ = true)
  4254. : root(r), allow_exceptions(allow_exceptions_)
  4255. {}
  4256. // make class move-only
  4257. json_sax_dom_parser(const json_sax_dom_parser&) = delete;
  4258. json_sax_dom_parser(json_sax_dom_parser&&) = default;
  4259. json_sax_dom_parser& operator=(const json_sax_dom_parser&) = delete;
  4260. json_sax_dom_parser& operator=(json_sax_dom_parser&&) = default;
  4261. ~json_sax_dom_parser() = default;
  4262. bool null()
  4263. {
  4264. handle_value(nullptr);
  4265. return true;
  4266. }
  4267. bool boolean(bool val)
  4268. {
  4269. handle_value(val);
  4270. return true;
  4271. }
  4272. bool number_integer(number_integer_t val)
  4273. {
  4274. handle_value(val);
  4275. return true;
  4276. }
  4277. bool number_unsigned(number_unsigned_t val)
  4278. {
  4279. handle_value(val);
  4280. return true;
  4281. }
  4282. bool number_float(number_float_t val, const string_t& /*unused*/)
  4283. {
  4284. handle_value(val);
  4285. return true;
  4286. }
  4287. bool string(string_t& val)
  4288. {
  4289. handle_value(val);
  4290. return true;
  4291. }
  4292. bool binary(binary_t& val)
  4293. {
  4294. handle_binary(val);
  4295. return true;
  4296. }
  4297. bool start_object(std::size_t len)
  4298. {
  4299. ref_stack.push_back(handle_value(BasicJsonType::value_t::object));
  4300. if (JSON_HEDLEY_UNLIKELY(len != std::size_t(-1) and len > ref_stack.back()->max_size()))
  4301. {
  4302. JSON_THROW(out_of_range::create(408,
  4303. "excessive object size: " + std::to_string(len)));
  4304. }
  4305. return true;
  4306. }
  4307. bool key(string_t& val)
  4308. {
  4309. // add null at given key and store the reference for later
  4310. object_element = &(ref_stack.back()->m_value.object->operator[](val));
  4311. return true;
  4312. }
  4313. bool end_object()
  4314. {
  4315. ref_stack.pop_back();
  4316. return true;
  4317. }
  4318. bool start_array(std::size_t len)
  4319. {
  4320. ref_stack.push_back(handle_value(BasicJsonType::value_t::array));
  4321. if (JSON_HEDLEY_UNLIKELY(len != std::size_t(-1) and len > ref_stack.back()->max_size()))
  4322. {
  4323. JSON_THROW(out_of_range::create(408,
  4324. "excessive array size: " + std::to_string(len)));
  4325. }
  4326. return true;
  4327. }
  4328. bool end_array()
  4329. {
  4330. ref_stack.pop_back();
  4331. return true;
  4332. }
  4333. bool parse_error(std::size_t /*unused*/, const std::string& /*unused*/,
  4334. const detail::exception& ex)
  4335. {
  4336. errored = true;
  4337. if (allow_exceptions)
  4338. {
  4339. // determine the proper exception type from the id
  4340. switch ((ex.id / 100) % 100)
  4341. {
  4342. case 1:
  4343. JSON_THROW(*static_cast<const detail::parse_error*>(&ex));
  4344. case 4:
  4345. JSON_THROW(*static_cast<const detail::out_of_range*>(&ex));
  4346. // LCOV_EXCL_START
  4347. case 2:
  4348. JSON_THROW(*static_cast<const detail::invalid_iterator*>(&ex));
  4349. case 3:
  4350. JSON_THROW(*static_cast<const detail::type_error*>(&ex));
  4351. case 5:
  4352. JSON_THROW(*static_cast<const detail::other_error*>(&ex));
  4353. default:
  4354. assert(false);
  4355. // LCOV_EXCL_STOP
  4356. }
  4357. }
  4358. return false;
  4359. }
  4360. constexpr bool is_errored() const
  4361. {
  4362. return errored;
  4363. }
  4364. private:
  4365. /*!
  4366. @invariant If the ref stack is empty, then the passed value will be the new
  4367. root.
  4368. @invariant If the ref stack contains a value, then it is an array or an
  4369. object to which we can add elements
  4370. */
  4371. template<typename Value>
  4372. JSON_HEDLEY_RETURNS_NON_NULL
  4373. BasicJsonType* handle_value(Value&& v)
  4374. {
  4375. if (ref_stack.empty())
  4376. {
  4377. root = BasicJsonType(std::forward<Value>(v));
  4378. return &root;
  4379. }
  4380. assert(ref_stack.back()->is_array() or ref_stack.back()->is_object());
  4381. if (ref_stack.back()->is_array())
  4382. {
  4383. ref_stack.back()->m_value.array->emplace_back(std::forward<Value>(v));
  4384. return &(ref_stack.back()->m_value.array->back());
  4385. }
  4386. assert(ref_stack.back()->is_object());
  4387. assert(object_element);
  4388. *object_element = BasicJsonType(std::forward<Value>(v));
  4389. return object_element;
  4390. }
  4391. /*!
  4392. @invariant If the ref stack is empty, then the passed value will be the new
  4393. root.
  4394. @invariant If the ref stack contains a value, then it is an array or an
  4395. object to which we can add elements
  4396. */
  4397. template<typename BinaryValue>
  4398. JSON_HEDLEY_RETURNS_NON_NULL
  4399. BasicJsonType* handle_binary(BinaryValue&& v)
  4400. {
  4401. if (ref_stack.empty())
  4402. {
  4403. root = BasicJsonType::binary_array(std::forward<BinaryValue>(v));
  4404. return &root;
  4405. }
  4406. assert(ref_stack.back()->is_array() or ref_stack.back()->is_object());
  4407. if (ref_stack.back()->is_array())
  4408. {
  4409. ref_stack.back()->m_value.array->emplace_back(BasicJsonType::binary_array(std::forward<BinaryValue>(v)));
  4410. return &(ref_stack.back()->m_value.array->back());
  4411. }
  4412. assert(ref_stack.back()->is_object());
  4413. assert(object_element);
  4414. *object_element = BasicJsonType::binary_array(std::forward<BinaryValue>(v));
  4415. return object_element;
  4416. }
  4417. /// the parsed JSON value
  4418. BasicJsonType& root;
  4419. /// stack to model hierarchy of values
  4420. std::vector<BasicJsonType*> ref_stack {};
  4421. /// helper to hold the reference for the next object element
  4422. BasicJsonType* object_element = nullptr;
  4423. /// whether a syntax error occurred
  4424. bool errored = false;
  4425. /// whether to throw exceptions in case of errors
  4426. const bool allow_exceptions = true;
  4427. };
  4428. template<typename BasicJsonType>
  4429. class json_sax_dom_callback_parser
  4430. {
  4431. public:
  4432. using number_integer_t = typename BasicJsonType::number_integer_t;
  4433. using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
  4434. using number_float_t = typename BasicJsonType::number_float_t;
  4435. using string_t = typename BasicJsonType::string_t;
  4436. using binary_t = typename BasicJsonType::binary_t;
  4437. using parser_callback_t = typename BasicJsonType::parser_callback_t;
  4438. using parse_event_t = typename BasicJsonType::parse_event_t;
  4439. json_sax_dom_callback_parser(BasicJsonType& r,
  4440. const parser_callback_t cb,
  4441. const bool allow_exceptions_ = true)
  4442. : root(r), callback(cb), allow_exceptions(allow_exceptions_)
  4443. {
  4444. keep_stack.push_back(true);
  4445. }
  4446. // make class move-only
  4447. json_sax_dom_callback_parser(const json_sax_dom_callback_parser&) = delete;
  4448. json_sax_dom_callback_parser(json_sax_dom_callback_parser&&) = default;
  4449. json_sax_dom_callback_parser& operator=(const json_sax_dom_callback_parser&) = delete;
  4450. json_sax_dom_callback_parser& operator=(json_sax_dom_callback_parser&&) = default;
  4451. ~json_sax_dom_callback_parser() = default;
  4452. bool null()
  4453. {
  4454. handle_value(nullptr);
  4455. return true;
  4456. }
  4457. bool boolean(bool val)
  4458. {
  4459. handle_value(val);
  4460. return true;
  4461. }
  4462. bool number_integer(number_integer_t val)
  4463. {
  4464. handle_value(val);
  4465. return true;
  4466. }
  4467. bool number_unsigned(number_unsigned_t val)
  4468. {
  4469. handle_value(val);
  4470. return true;
  4471. }
  4472. bool number_float(number_float_t val, const string_t& /*unused*/)
  4473. {
  4474. handle_value(val);
  4475. return true;
  4476. }
  4477. bool string(string_t& val)
  4478. {
  4479. handle_value(val);
  4480. return true;
  4481. }
  4482. bool binary(binary_t& val)
  4483. {
  4484. handle_value(val);
  4485. return true;
  4486. }
  4487. bool start_object(std::size_t len)
  4488. {
  4489. // check callback for object start
  4490. const bool keep = callback(static_cast<int>(ref_stack.size()), parse_event_t::object_start, discarded);
  4491. keep_stack.push_back(keep);
  4492. auto val = handle_value(BasicJsonType::value_t::object, true);
  4493. ref_stack.push_back(val.second);
  4494. // check object limit
  4495. if (ref_stack.back() and JSON_HEDLEY_UNLIKELY(len != std::size_t(-1) and len > ref_stack.back()->max_size()))
  4496. {
  4497. JSON_THROW(out_of_range::create(408, "excessive object size: " + std::to_string(len)));
  4498. }
  4499. return true;
  4500. }
  4501. bool key(string_t& val)
  4502. {
  4503. BasicJsonType k = BasicJsonType(val);
  4504. // check callback for key
  4505. const bool keep = callback(static_cast<int>(ref_stack.size()), parse_event_t::key, k);
  4506. key_keep_stack.push_back(keep);
  4507. // add discarded value at given key and store the reference for later
  4508. if (keep and ref_stack.back())
  4509. {
  4510. object_element = &(ref_stack.back()->m_value.object->operator[](val) = discarded);
  4511. }
  4512. return true;
  4513. }
  4514. bool end_object()
  4515. {
  4516. if (ref_stack.back() and not callback(static_cast<int>(ref_stack.size()) - 1, parse_event_t::object_end, *ref_stack.back()))
  4517. {
  4518. // discard object
  4519. *ref_stack.back() = discarded;
  4520. }
  4521. assert(not ref_stack.empty());
  4522. assert(not keep_stack.empty());
  4523. ref_stack.pop_back();
  4524. keep_stack.pop_back();
  4525. if (not ref_stack.empty() and ref_stack.back() and ref_stack.back()->is_object())
  4526. {
  4527. // remove discarded value
  4528. for (auto it = ref_stack.back()->begin(); it != ref_stack.back()->end(); ++it)
  4529. {
  4530. if (it->is_discarded())
  4531. {
  4532. ref_stack.back()->erase(it);
  4533. break;
  4534. }
  4535. }
  4536. }
  4537. return true;
  4538. }
  4539. bool start_array(std::size_t len)
  4540. {
  4541. const bool keep = callback(static_cast<int>(ref_stack.size()), parse_event_t::array_start, discarded);
  4542. keep_stack.push_back(keep);
  4543. auto val = handle_value(BasicJsonType::value_t::array, true);
  4544. ref_stack.push_back(val.second);
  4545. // check array limit
  4546. if (ref_stack.back() and JSON_HEDLEY_UNLIKELY(len != std::size_t(-1) and len > ref_stack.back()->max_size()))
  4547. {
  4548. JSON_THROW(out_of_range::create(408, "excessive array size: " + std::to_string(len)));
  4549. }
  4550. return true;
  4551. }
  4552. bool end_array()
  4553. {
  4554. bool keep = true;
  4555. if (ref_stack.back())
  4556. {
  4557. keep = callback(static_cast<int>(ref_stack.size()) - 1, parse_event_t::array_end, *ref_stack.back());
  4558. if (not keep)
  4559. {
  4560. // discard array
  4561. *ref_stack.back() = discarded;
  4562. }
  4563. }
  4564. assert(not ref_stack.empty());
  4565. assert(not keep_stack.empty());
  4566. ref_stack.pop_back();
  4567. keep_stack.pop_back();
  4568. // remove discarded value
  4569. if (not keep and not ref_stack.empty() and ref_stack.back()->is_array())
  4570. {
  4571. ref_stack.back()->m_value.array->pop_back();
  4572. }
  4573. return true;
  4574. }
  4575. bool parse_error(std::size_t /*unused*/, const std::string& /*unused*/,
  4576. const detail::exception& ex)
  4577. {
  4578. errored = true;
  4579. if (allow_exceptions)
  4580. {
  4581. // determine the proper exception type from the id
  4582. switch ((ex.id / 100) % 100)
  4583. {
  4584. case 1:
  4585. JSON_THROW(*static_cast<const detail::parse_error*>(&ex));
  4586. case 4:
  4587. JSON_THROW(*static_cast<const detail::out_of_range*>(&ex));
  4588. // LCOV_EXCL_START
  4589. case 2:
  4590. JSON_THROW(*static_cast<const detail::invalid_iterator*>(&ex));
  4591. case 3:
  4592. JSON_THROW(*static_cast<const detail::type_error*>(&ex));
  4593. case 5:
  4594. JSON_THROW(*static_cast<const detail::other_error*>(&ex));
  4595. default:
  4596. assert(false);
  4597. // LCOV_EXCL_STOP
  4598. }
  4599. }
  4600. return false;
  4601. }
  4602. constexpr bool is_errored() const
  4603. {
  4604. return errored;
  4605. }
  4606. private:
  4607. /*!
  4608. @param[in] v value to add to the JSON value we build during parsing
  4609. @param[in] skip_callback whether we should skip calling the callback
  4610. function; this is required after start_array() and
  4611. start_object() SAX events, because otherwise we would call the
  4612. callback function with an empty array or object, respectively.
  4613. @invariant If the ref stack is empty, then the passed value will be the new
  4614. root.
  4615. @invariant If the ref stack contains a value, then it is an array or an
  4616. object to which we can add elements
  4617. @return pair of boolean (whether value should be kept) and pointer (to the
  4618. passed value in the ref_stack hierarchy; nullptr if not kept)
  4619. */
  4620. template<typename Value>
  4621. std::pair<bool, BasicJsonType*> handle_value(Value&& v, const bool skip_callback = false)
  4622. {
  4623. assert(not keep_stack.empty());
  4624. // do not handle this value if we know it would be added to a discarded
  4625. // container
  4626. if (not keep_stack.back())
  4627. {
  4628. return {false, nullptr};
  4629. }
  4630. // create value
  4631. auto value = BasicJsonType(std::forward<Value>(v));
  4632. // check callback
  4633. const bool keep = skip_callback or callback(static_cast<int>(ref_stack.size()), parse_event_t::value, value);
  4634. // do not handle this value if we just learnt it shall be discarded
  4635. if (not keep)
  4636. {
  4637. return {false, nullptr};
  4638. }
  4639. if (ref_stack.empty())
  4640. {
  4641. root = std::move(value);
  4642. return {true, &root};
  4643. }
  4644. // skip this value if we already decided to skip the parent
  4645. // (https://github.com/nlohmann/json/issues/971#issuecomment-413678360)
  4646. if (not ref_stack.back())
  4647. {
  4648. return {false, nullptr};
  4649. }
  4650. // we now only expect arrays and objects
  4651. assert(ref_stack.back()->is_array() or ref_stack.back()->is_object());
  4652. // array
  4653. if (ref_stack.back()->is_array())
  4654. {
  4655. ref_stack.back()->m_value.array->push_back(std::move(value));
  4656. return {true, &(ref_stack.back()->m_value.array->back())};
  4657. }
  4658. // object
  4659. assert(ref_stack.back()->is_object());
  4660. // check if we should store an element for the current key
  4661. assert(not key_keep_stack.empty());
  4662. const bool store_element = key_keep_stack.back();
  4663. key_keep_stack.pop_back();
  4664. if (not store_element)
  4665. {
  4666. return {false, nullptr};
  4667. }
  4668. assert(object_element);
  4669. *object_element = std::move(value);
  4670. return {true, object_element};
  4671. }
  4672. /// the parsed JSON value
  4673. BasicJsonType& root;
  4674. /// stack to model hierarchy of values
  4675. std::vector<BasicJsonType*> ref_stack {};
  4676. /// stack to manage which values to keep
  4677. std::vector<bool> keep_stack {};
  4678. /// stack to manage which object keys to keep
  4679. std::vector<bool> key_keep_stack {};
  4680. /// helper to hold the reference for the next object element
  4681. BasicJsonType* object_element = nullptr;
  4682. /// whether a syntax error occurred
  4683. bool errored = false;
  4684. /// callback function
  4685. const parser_callback_t callback = nullptr;
  4686. /// whether to throw exceptions in case of errors
  4687. const bool allow_exceptions = true;
  4688. /// a discarded value for the callback
  4689. BasicJsonType discarded = BasicJsonType::value_t::discarded;
  4690. };
  4691. template<typename BasicJsonType>
  4692. class json_sax_acceptor
  4693. {
  4694. public:
  4695. using number_integer_t = typename BasicJsonType::number_integer_t;
  4696. using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
  4697. using number_float_t = typename BasicJsonType::number_float_t;
  4698. using string_t = typename BasicJsonType::string_t;
  4699. using binary_t = typename BasicJsonType::binary_t;
  4700. bool null()
  4701. {
  4702. return true;
  4703. }
  4704. bool boolean(bool /*unused*/)
  4705. {
  4706. return true;
  4707. }
  4708. bool number_integer(number_integer_t /*unused*/)
  4709. {
  4710. return true;
  4711. }
  4712. bool number_unsigned(number_unsigned_t /*unused*/)
  4713. {
  4714. return true;
  4715. }
  4716. bool number_float(number_float_t /*unused*/, const string_t& /*unused*/)
  4717. {
  4718. return true;
  4719. }
  4720. bool string(string_t& /*unused*/)
  4721. {
  4722. return true;
  4723. }
  4724. bool binary(binary_t& /*unused*/)
  4725. {
  4726. return true;
  4727. }
  4728. bool start_object(std::size_t /*unused*/ = std::size_t(-1))
  4729. {
  4730. return true;
  4731. }
  4732. bool key(string_t& /*unused*/)
  4733. {
  4734. return true;
  4735. }
  4736. bool end_object()
  4737. {
  4738. return true;
  4739. }
  4740. bool start_array(std::size_t /*unused*/ = std::size_t(-1))
  4741. {
  4742. return true;
  4743. }
  4744. bool end_array()
  4745. {
  4746. return true;
  4747. }
  4748. bool parse_error(std::size_t /*unused*/, const std::string& /*unused*/, const detail::exception& /*unused*/)
  4749. {
  4750. return false;
  4751. }
  4752. };
  4753. } // namespace detail
  4754. } // namespace nlohmann
  4755. // #include <nlohmann/detail/macro_scope.hpp>
  4756. // #include <nlohmann/detail/meta/is_sax.hpp>
  4757. #include <cstdint> // size_t
  4758. #include <utility> // declval
  4759. #include <string> // string
  4760. // #include <nlohmann/detail/meta/detected.hpp>
  4761. // #include <nlohmann/detail/meta/type_traits.hpp>
  4762. namespace nlohmann
  4763. {
  4764. namespace detail
  4765. {
  4766. template <typename T>
  4767. using null_function_t = decltype(std::declval<T&>().null());
  4768. template <typename T>
  4769. using boolean_function_t =
  4770. decltype(std::declval<T&>().boolean(std::declval<bool>()));
  4771. template <typename T, typename Integer>
  4772. using number_integer_function_t =
  4773. decltype(std::declval<T&>().number_integer(std::declval<Integer>()));
  4774. template <typename T, typename Unsigned>
  4775. using number_unsigned_function_t =
  4776. decltype(std::declval<T&>().number_unsigned(std::declval<Unsigned>()));
  4777. template <typename T, typename Float, typename String>
  4778. using number_float_function_t = decltype(std::declval<T&>().number_float(
  4779. std::declval<Float>(), std::declval<const String&>()));
  4780. template <typename T, typename String>
  4781. using string_function_t =
  4782. decltype(std::declval<T&>().string(std::declval<String&>()));
  4783. template <typename T>
  4784. using start_object_function_t =
  4785. decltype(std::declval<T&>().start_object(std::declval<std::size_t>()));
  4786. template <typename T, typename String>
  4787. using key_function_t =
  4788. decltype(std::declval<T&>().key(std::declval<String&>()));
  4789. template <typename T>
  4790. using end_object_function_t = decltype(std::declval<T&>().end_object());
  4791. template <typename T>
  4792. using start_array_function_t =
  4793. decltype(std::declval<T&>().start_array(std::declval<std::size_t>()));
  4794. template <typename T>
  4795. using end_array_function_t = decltype(std::declval<T&>().end_array());
  4796. template <typename T, typename Exception>
  4797. using parse_error_function_t = decltype(std::declval<T&>().parse_error(
  4798. std::declval<std::size_t>(), std::declval<const std::string&>(),
  4799. std::declval<const Exception&>()));
  4800. template <typename SAX, typename BasicJsonType>
  4801. struct is_sax
  4802. {
  4803. private:
  4804. static_assert(is_basic_json<BasicJsonType>::value,
  4805. "BasicJsonType must be of type basic_json<...>");
  4806. using number_integer_t = typename BasicJsonType::number_integer_t;
  4807. using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
  4808. using number_float_t = typename BasicJsonType::number_float_t;
  4809. using string_t = typename BasicJsonType::string_t;
  4810. using exception_t = typename BasicJsonType::exception;
  4811. public:
  4812. static constexpr bool value =
  4813. is_detected_exact<bool, null_function_t, SAX>::value &&
  4814. is_detected_exact<bool, boolean_function_t, SAX>::value &&
  4815. is_detected_exact<bool, number_integer_function_t, SAX,
  4816. number_integer_t>::value &&
  4817. is_detected_exact<bool, number_unsigned_function_t, SAX,
  4818. number_unsigned_t>::value &&
  4819. is_detected_exact<bool, number_float_function_t, SAX, number_float_t,
  4820. string_t>::value &&
  4821. is_detected_exact<bool, string_function_t, SAX, string_t>::value &&
  4822. is_detected_exact<bool, start_object_function_t, SAX>::value &&
  4823. is_detected_exact<bool, key_function_t, SAX, string_t>::value &&
  4824. is_detected_exact<bool, end_object_function_t, SAX>::value &&
  4825. is_detected_exact<bool, start_array_function_t, SAX>::value &&
  4826. is_detected_exact<bool, end_array_function_t, SAX>::value &&
  4827. is_detected_exact<bool, parse_error_function_t, SAX, exception_t>::value;
  4828. };
  4829. template <typename SAX, typename BasicJsonType>
  4830. struct is_sax_static_asserts
  4831. {
  4832. private:
  4833. static_assert(is_basic_json<BasicJsonType>::value,
  4834. "BasicJsonType must be of type basic_json<...>");
  4835. using number_integer_t = typename BasicJsonType::number_integer_t;
  4836. using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
  4837. using number_float_t = typename BasicJsonType::number_float_t;
  4838. using string_t = typename BasicJsonType::string_t;
  4839. using exception_t = typename BasicJsonType::exception;
  4840. public:
  4841. static_assert(is_detected_exact<bool, null_function_t, SAX>::value,
  4842. "Missing/invalid function: bool null()");
  4843. static_assert(is_detected_exact<bool, boolean_function_t, SAX>::value,
  4844. "Missing/invalid function: bool boolean(bool)");
  4845. static_assert(is_detected_exact<bool, boolean_function_t, SAX>::value,
  4846. "Missing/invalid function: bool boolean(bool)");
  4847. static_assert(
  4848. is_detected_exact<bool, number_integer_function_t, SAX,
  4849. number_integer_t>::value,
  4850. "Missing/invalid function: bool number_integer(number_integer_t)");
  4851. static_assert(
  4852. is_detected_exact<bool, number_unsigned_function_t, SAX,
  4853. number_unsigned_t>::value,
  4854. "Missing/invalid function: bool number_unsigned(number_unsigned_t)");
  4855. static_assert(is_detected_exact<bool, number_float_function_t, SAX,
  4856. number_float_t, string_t>::value,
  4857. "Missing/invalid function: bool number_float(number_float_t, const string_t&)");
  4858. static_assert(
  4859. is_detected_exact<bool, string_function_t, SAX, string_t>::value,
  4860. "Missing/invalid function: bool string(string_t&)");
  4861. static_assert(is_detected_exact<bool, start_object_function_t, SAX>::value,
  4862. "Missing/invalid function: bool start_object(std::size_t)");
  4863. static_assert(is_detected_exact<bool, key_function_t, SAX, string_t>::value,
  4864. "Missing/invalid function: bool key(string_t&)");
  4865. static_assert(is_detected_exact<bool, end_object_function_t, SAX>::value,
  4866. "Missing/invalid function: bool end_object()");
  4867. static_assert(is_detected_exact<bool, start_array_function_t, SAX>::value,
  4868. "Missing/invalid function: bool start_array(std::size_t)");
  4869. static_assert(is_detected_exact<bool, end_array_function_t, SAX>::value,
  4870. "Missing/invalid function: bool end_array()");
  4871. static_assert(
  4872. is_detected_exact<bool, parse_error_function_t, SAX, exception_t>::value,
  4873. "Missing/invalid function: bool parse_error(std::size_t, const "
  4874. "std::string&, const exception&)");
  4875. };
  4876. } // namespace detail
  4877. } // namespace nlohmann
  4878. // #include <nlohmann/detail/value_t.hpp>
  4879. namespace nlohmann
  4880. {
  4881. namespace detail
  4882. {
  4883. ///////////////////
  4884. // binary reader //
  4885. ///////////////////
  4886. /*!
  4887. @brief deserialization of CBOR, MessagePack, and UBJSON values
  4888. */
  4889. template<typename BasicJsonType, typename SAX = json_sax_dom_parser<BasicJsonType>>
  4890. class binary_reader
  4891. {
  4892. using number_integer_t = typename BasicJsonType::number_integer_t;
  4893. using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
  4894. using number_float_t = typename BasicJsonType::number_float_t;
  4895. using string_t = typename BasicJsonType::string_t;
  4896. using internal_binary_t = typename BasicJsonType::internal_binary_t;
  4897. using json_sax_t = SAX;
  4898. public:
  4899. /*!
  4900. @brief create a binary reader
  4901. @param[in] adapter input adapter to read from
  4902. */
  4903. explicit binary_reader(input_adapter_t adapter) : ia(std::move(adapter))
  4904. {
  4905. (void)detail::is_sax_static_asserts<SAX, BasicJsonType> {};
  4906. assert(ia);
  4907. }
  4908. // make class move-only
  4909. binary_reader(const binary_reader&) = delete;
  4910. binary_reader(binary_reader&&) = default;
  4911. binary_reader& operator=(const binary_reader&) = delete;
  4912. binary_reader& operator=(binary_reader&&) = default;
  4913. ~binary_reader() = default;
  4914. /*!
  4915. @param[in] format the binary format to parse
  4916. @param[in] sax_ a SAX event processor
  4917. @param[in] strict whether to expect the input to be consumed completed
  4918. @return
  4919. */
  4920. JSON_HEDLEY_NON_NULL(3)
  4921. bool sax_parse(const input_format_t format,
  4922. json_sax_t* sax_,
  4923. const bool strict = true)
  4924. {
  4925. sax = sax_;
  4926. bool result = false;
  4927. switch (format)
  4928. {
  4929. case input_format_t::bson:
  4930. result = parse_bson_internal();
  4931. break;
  4932. case input_format_t::cbor:
  4933. result = parse_cbor_internal();
  4934. break;
  4935. case input_format_t::msgpack:
  4936. result = parse_msgpack_internal();
  4937. break;
  4938. case input_format_t::ubjson:
  4939. result = parse_ubjson_internal();
  4940. break;
  4941. default: // LCOV_EXCL_LINE
  4942. assert(false); // LCOV_EXCL_LINE
  4943. }
  4944. // strict mode: next byte must be EOF
  4945. if (result and strict)
  4946. {
  4947. if (format == input_format_t::ubjson)
  4948. {
  4949. get_ignore_noop();
  4950. }
  4951. else
  4952. {
  4953. get();
  4954. }
  4955. if (JSON_HEDLEY_UNLIKELY(current != std::char_traits<char>::eof()))
  4956. {
  4957. return sax->parse_error(chars_read, get_token_string(),
  4958. parse_error::create(110, chars_read, exception_message(format, "expected end of input; last byte: 0x" + get_token_string(), "value")));
  4959. }
  4960. }
  4961. return result;
  4962. }
  4963. /*!
  4964. @brief determine system byte order
  4965. @return true if and only if system's byte order is little endian
  4966. @note from https://stackoverflow.com/a/1001328/266378
  4967. */
  4968. static constexpr bool little_endianess(int num = 1) noexcept
  4969. {
  4970. return *reinterpret_cast<char*>(&num) == 1;
  4971. }
  4972. private:
  4973. //////////
  4974. // BSON //
  4975. //////////
  4976. /*!
  4977. @brief Reads in a BSON-object and passes it to the SAX-parser.
  4978. @return whether a valid BSON-value was passed to the SAX parser
  4979. */
  4980. bool parse_bson_internal()
  4981. {
  4982. std::int32_t document_size;
  4983. get_number<std::int32_t, true>(input_format_t::bson, document_size);
  4984. if (JSON_HEDLEY_UNLIKELY(not sax->start_object(std::size_t(-1))))
  4985. {
  4986. return false;
  4987. }
  4988. if (JSON_HEDLEY_UNLIKELY(not parse_bson_element_list(/*is_array*/false)))
  4989. {
  4990. return false;
  4991. }
  4992. return sax->end_object();
  4993. }
  4994. /*!
  4995. @brief Parses a C-style string from the BSON input.
  4996. @param[in, out] result A reference to the string variable where the read
  4997. string is to be stored.
  4998. @return `true` if the \x00-byte indicating the end of the string was
  4999. encountered before the EOF; false` indicates an unexpected EOF.
  5000. */
  5001. bool get_bson_cstr(string_t& result)
  5002. {
  5003. auto out = std::back_inserter(result);
  5004. while (true)
  5005. {
  5006. get();
  5007. if (JSON_HEDLEY_UNLIKELY(not unexpect_eof(input_format_t::bson, "cstring")))
  5008. {
  5009. return false;
  5010. }
  5011. if (current == 0x00)
  5012. {
  5013. return true;
  5014. }
  5015. *out++ = static_cast<char>(current);
  5016. }
  5017. return true;
  5018. }
  5019. /*!
  5020. @brief Parses a zero-terminated string of length @a len from the BSON
  5021. input.
  5022. @param[in] len The length (including the zero-byte at the end) of the
  5023. string to be read.
  5024. @param[in, out] result A reference to the string variable where the read
  5025. string is to be stored.
  5026. @tparam NumberType The type of the length @a len
  5027. @pre len >= 1
  5028. @return `true` if the string was successfully parsed
  5029. */
  5030. template<typename NumberType>
  5031. bool get_bson_string(const NumberType len, string_t& result)
  5032. {
  5033. if (JSON_HEDLEY_UNLIKELY(len < 1))
  5034. {
  5035. auto last_token = get_token_string();
  5036. 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")));
  5037. }
  5038. return get_string(input_format_t::bson, len - static_cast<NumberType>(1), result) and get() != std::char_traits<char>::eof();
  5039. }
  5040. /*!
  5041. @brief Parses a byte array input of length @a len from the BSON input.
  5042. @param[in] len The length of the byte array to be read.
  5043. @param[in, out] result A reference to the binary variable where the read
  5044. array is to be stored.
  5045. @tparam NumberType The type of the length @a len
  5046. @pre len >= 0
  5047. @return `true` if the byte array was successfully parsed
  5048. */
  5049. template<typename NumberType>
  5050. bool get_bson_binary(const NumberType len, internal_binary_t& result)
  5051. {
  5052. if (JSON_HEDLEY_UNLIKELY(len < 0))
  5053. {
  5054. auto last_token = get_token_string();
  5055. 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")));
  5056. }
  5057. result.has_subtype = true; // All BSON binary values have a subtype
  5058. get_number<std::uint8_t>(input_format_t::bson, result.subtype);
  5059. return get_binary(input_format_t::bson, len, result);
  5060. }
  5061. /*!
  5062. @brief Read a BSON document element of the given @a element_type.
  5063. @param[in] element_type The BSON element type, c.f. http://bsonspec.org/spec.html
  5064. @param[in] element_type_parse_position The position in the input stream,
  5065. where the `element_type` was read.
  5066. @warning Not all BSON element types are supported yet. An unsupported
  5067. @a element_type will give rise to a parse_error.114:
  5068. Unsupported BSON record type 0x...
  5069. @return whether a valid BSON-object/array was passed to the SAX parser
  5070. */
  5071. bool parse_bson_element_internal(const int element_type,
  5072. const std::size_t element_type_parse_position)
  5073. {
  5074. switch (element_type)
  5075. {
  5076. case 0x01: // double
  5077. {
  5078. double number;
  5079. return get_number<double, true>(input_format_t::bson, number) and sax->number_float(static_cast<number_float_t>(number), "");
  5080. }
  5081. case 0x02: // string
  5082. {
  5083. std::int32_t len;
  5084. string_t value;
  5085. return get_number<std::int32_t, true>(input_format_t::bson, len) and get_bson_string(len, value) and sax->string(value);
  5086. }
  5087. case 0x03: // object
  5088. {
  5089. return parse_bson_internal();
  5090. }
  5091. case 0x04: // array
  5092. {
  5093. return parse_bson_array();
  5094. }
  5095. case 0x05: // binary
  5096. {
  5097. std::int32_t len;
  5098. internal_binary_t value;
  5099. return get_number<std::int32_t, true>(input_format_t::bson, len) and get_bson_binary(len, value) and sax->binary(value);
  5100. }
  5101. case 0x08: // boolean
  5102. {
  5103. return sax->boolean(get() != 0);
  5104. }
  5105. case 0x0A: // null
  5106. {
  5107. return sax->null();
  5108. }
  5109. case 0x10: // int32
  5110. {
  5111. std::int32_t value;
  5112. return get_number<std::int32_t, true>(input_format_t::bson, value) and sax->number_integer(value);
  5113. }
  5114. case 0x12: // int64
  5115. {
  5116. std::int64_t value;
  5117. return get_number<std::int64_t, true>(input_format_t::bson, value) and sax->number_integer(value);
  5118. }
  5119. default: // anything else not supported (yet)
  5120. {
  5121. std::array<char, 3> cr{{}};
  5122. (std::snprintf)(cr.data(), cr.size(), "%.2hhX", static_cast<unsigned char>(element_type));
  5123. 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())));
  5124. }
  5125. }
  5126. }
  5127. /*!
  5128. @brief Read a BSON element list (as specified in the BSON-spec)
  5129. The same binary layout is used for objects and arrays, hence it must be
  5130. indicated with the argument @a is_array which one is expected
  5131. (true --> array, false --> object).
  5132. @param[in] is_array Determines if the element list being read is to be
  5133. treated as an object (@a is_array == false), or as an
  5134. array (@a is_array == true).
  5135. @return whether a valid BSON-object/array was passed to the SAX parser
  5136. */
  5137. bool parse_bson_element_list(const bool is_array)
  5138. {
  5139. string_t key;
  5140. while (int element_type = get())
  5141. {
  5142. if (JSON_HEDLEY_UNLIKELY(not unexpect_eof(input_format_t::bson, "element list")))
  5143. {
  5144. return false;
  5145. }
  5146. const std::size_t element_type_parse_position = chars_read;
  5147. if (JSON_HEDLEY_UNLIKELY(not get_bson_cstr(key)))
  5148. {
  5149. return false;
  5150. }
  5151. if (not is_array and not sax->key(key))
  5152. {
  5153. return false;
  5154. }
  5155. if (JSON_HEDLEY_UNLIKELY(not parse_bson_element_internal(element_type, element_type_parse_position)))
  5156. {
  5157. return false;
  5158. }
  5159. // get_bson_cstr only appends
  5160. key.clear();
  5161. }
  5162. return true;
  5163. }
  5164. /*!
  5165. @brief Reads an array from the BSON input and passes it to the SAX-parser.
  5166. @return whether a valid BSON-array was passed to the SAX parser
  5167. */
  5168. bool parse_bson_array()
  5169. {
  5170. std::int32_t document_size;
  5171. get_number<std::int32_t, true>(input_format_t::bson, document_size);
  5172. if (JSON_HEDLEY_UNLIKELY(not sax->start_array(std::size_t(-1))))
  5173. {
  5174. return false;
  5175. }
  5176. if (JSON_HEDLEY_UNLIKELY(not parse_bson_element_list(/*is_array*/true)))
  5177. {
  5178. return false;
  5179. }
  5180. return sax->end_array();
  5181. }
  5182. //////////
  5183. // CBOR //
  5184. //////////
  5185. /*!
  5186. @param[in] get_char whether a new character should be retrieved from the
  5187. input (true, default) or whether the last read
  5188. character should be considered instead
  5189. @return whether a valid CBOR value was passed to the SAX parser
  5190. */
  5191. bool parse_cbor_internal(const bool get_char = true)
  5192. {
  5193. switch (get_char ? get() : current)
  5194. {
  5195. // EOF
  5196. case std::char_traits<char>::eof():
  5197. return unexpect_eof(input_format_t::cbor, "value");
  5198. // Integer 0x00..0x17 (0..23)
  5199. case 0x00:
  5200. case 0x01:
  5201. case 0x02:
  5202. case 0x03:
  5203. case 0x04:
  5204. case 0x05:
  5205. case 0x06:
  5206. case 0x07:
  5207. case 0x08:
  5208. case 0x09:
  5209. case 0x0A:
  5210. case 0x0B:
  5211. case 0x0C:
  5212. case 0x0D:
  5213. case 0x0E:
  5214. case 0x0F:
  5215. case 0x10:
  5216. case 0x11:
  5217. case 0x12:
  5218. case 0x13:
  5219. case 0x14:
  5220. case 0x15:
  5221. case 0x16:
  5222. case 0x17:
  5223. return sax->number_unsigned(static_cast<number_unsigned_t>(current));
  5224. case 0x18: // Unsigned integer (one-byte uint8_t follows)
  5225. {
  5226. std::uint8_t number;
  5227. return get_number(input_format_t::cbor, number) and sax->number_unsigned(number);
  5228. }
  5229. case 0x19: // Unsigned integer (two-byte uint16_t follows)
  5230. {
  5231. std::uint16_t number;
  5232. return get_number(input_format_t::cbor, number) and sax->number_unsigned(number);
  5233. }
  5234. case 0x1A: // Unsigned integer (four-byte uint32_t follows)
  5235. {
  5236. std::uint32_t number;
  5237. return get_number(input_format_t::cbor, number) and sax->number_unsigned(number);
  5238. }
  5239. case 0x1B: // Unsigned integer (eight-byte uint64_t follows)
  5240. {
  5241. std::uint64_t number;
  5242. return get_number(input_format_t::cbor, number) and sax->number_unsigned(number);
  5243. }
  5244. // Negative integer -1-0x00..-1-0x17 (-1..-24)
  5245. case 0x20:
  5246. case 0x21:
  5247. case 0x22:
  5248. case 0x23:
  5249. case 0x24:
  5250. case 0x25:
  5251. case 0x26:
  5252. case 0x27:
  5253. case 0x28:
  5254. case 0x29:
  5255. case 0x2A:
  5256. case 0x2B:
  5257. case 0x2C:
  5258. case 0x2D:
  5259. case 0x2E:
  5260. case 0x2F:
  5261. case 0x30:
  5262. case 0x31:
  5263. case 0x32:
  5264. case 0x33:
  5265. case 0x34:
  5266. case 0x35:
  5267. case 0x36:
  5268. case 0x37:
  5269. return sax->number_integer(static_cast<std::int8_t>(0x20 - 1 - current));
  5270. case 0x38: // Negative integer (one-byte uint8_t follows)
  5271. {
  5272. std::uint8_t number;
  5273. return get_number(input_format_t::cbor, number) and sax->number_integer(static_cast<number_integer_t>(-1) - number);
  5274. }
  5275. case 0x39: // Negative integer -1-n (two-byte uint16_t follows)
  5276. {
  5277. std::uint16_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 0x3A: // Negative integer -1-n (four-byte uint32_t follows)
  5281. {
  5282. std::uint32_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 0x3B: // Negative integer -1-n (eight-byte uint64_t follows)
  5286. {
  5287. std::uint64_t number;
  5288. return get_number(input_format_t::cbor, number) and sax->number_integer(static_cast<number_integer_t>(-1)
  5289. - static_cast<number_integer_t>(number));
  5290. }
  5291. // Binary data (0x00..0x17 bytes follow)
  5292. case 0x40:
  5293. case 0x41:
  5294. case 0x42:
  5295. case 0x43:
  5296. case 0x44:
  5297. case 0x45:
  5298. case 0x46:
  5299. case 0x47:
  5300. case 0x48:
  5301. case 0x49:
  5302. case 0x4A:
  5303. case 0x4B:
  5304. case 0x4C:
  5305. case 0x4D:
  5306. case 0x4E:
  5307. case 0x4F:
  5308. case 0x50:
  5309. case 0x51:
  5310. case 0x52:
  5311. case 0x53:
  5312. case 0x54:
  5313. case 0x55:
  5314. case 0x56:
  5315. case 0x57:
  5316. case 0x58: // Binary data (one-byte uint8_t for n follows)
  5317. case 0x59: // Binary data (two-byte uint16_t for n follow)
  5318. case 0x5A: // Binary data (four-byte uint32_t for n follow)
  5319. case 0x5B: // Binary data (eight-byte uint64_t for n follow)
  5320. case 0x5F: // Binary data (indefinite length)
  5321. {
  5322. internal_binary_t b;
  5323. return get_cbor_binary(b) and sax->binary(b);
  5324. }
  5325. // UTF-8 string (0x00..0x17 bytes follow)
  5326. case 0x60:
  5327. case 0x61:
  5328. case 0x62:
  5329. case 0x63:
  5330. case 0x64:
  5331. case 0x65:
  5332. case 0x66:
  5333. case 0x67:
  5334. case 0x68:
  5335. case 0x69:
  5336. case 0x6A:
  5337. case 0x6B:
  5338. case 0x6C:
  5339. case 0x6D:
  5340. case 0x6E:
  5341. case 0x6F:
  5342. case 0x70:
  5343. case 0x71:
  5344. case 0x72:
  5345. case 0x73:
  5346. case 0x74:
  5347. case 0x75:
  5348. case 0x76:
  5349. case 0x77:
  5350. case 0x78: // UTF-8 string (one-byte uint8_t for n follows)
  5351. case 0x79: // UTF-8 string (two-byte uint16_t for n follow)
  5352. case 0x7A: // UTF-8 string (four-byte uint32_t for n follow)
  5353. case 0x7B: // UTF-8 string (eight-byte uint64_t for n follow)
  5354. case 0x7F: // UTF-8 string (indefinite length)
  5355. {
  5356. string_t s;
  5357. return get_cbor_string(s) and sax->string(s);
  5358. }
  5359. // array (0x00..0x17 data items follow)
  5360. case 0x80:
  5361. case 0x81:
  5362. case 0x82:
  5363. case 0x83:
  5364. case 0x84:
  5365. case 0x85:
  5366. case 0x86:
  5367. case 0x87:
  5368. case 0x88:
  5369. case 0x89:
  5370. case 0x8A:
  5371. case 0x8B:
  5372. case 0x8C:
  5373. case 0x8D:
  5374. case 0x8E:
  5375. case 0x8F:
  5376. case 0x90:
  5377. case 0x91:
  5378. case 0x92:
  5379. case 0x93:
  5380. case 0x94:
  5381. case 0x95:
  5382. case 0x96:
  5383. case 0x97:
  5384. return get_cbor_array(static_cast<std::size_t>(static_cast<unsigned int>(current) & 0x1Fu));
  5385. case 0x98: // array (one-byte uint8_t for n follows)
  5386. {
  5387. std::uint8_t len;
  5388. return get_number(input_format_t::cbor, len) and get_cbor_array(static_cast<std::size_t>(len));
  5389. }
  5390. case 0x99: // array (two-byte uint16_t for n follow)
  5391. {
  5392. std::uint16_t len;
  5393. return get_number(input_format_t::cbor, len) and get_cbor_array(static_cast<std::size_t>(len));
  5394. }
  5395. case 0x9A: // array (four-byte uint32_t for n follow)
  5396. {
  5397. std::uint32_t len;
  5398. return get_number(input_format_t::cbor, len) and get_cbor_array(static_cast<std::size_t>(len));
  5399. }
  5400. case 0x9B: // array (eight-byte uint64_t for n follow)
  5401. {
  5402. std::uint64_t len;
  5403. return get_number(input_format_t::cbor, len) and get_cbor_array(static_cast<std::size_t>(len));
  5404. }
  5405. case 0x9F: // array (indefinite length)
  5406. return get_cbor_array(std::size_t(-1));
  5407. // map (0x00..0x17 pairs of data items follow)
  5408. case 0xA0:
  5409. case 0xA1:
  5410. case 0xA2:
  5411. case 0xA3:
  5412. case 0xA4:
  5413. case 0xA5:
  5414. case 0xA6:
  5415. case 0xA7:
  5416. case 0xA8:
  5417. case 0xA9:
  5418. case 0xAA:
  5419. case 0xAB:
  5420. case 0xAC:
  5421. case 0xAD:
  5422. case 0xAE:
  5423. case 0xAF:
  5424. case 0xB0:
  5425. case 0xB1:
  5426. case 0xB2:
  5427. case 0xB3:
  5428. case 0xB4:
  5429. case 0xB5:
  5430. case 0xB6:
  5431. case 0xB7:
  5432. return get_cbor_object(static_cast<std::size_t>(static_cast<unsigned int>(current) & 0x1Fu));
  5433. case 0xB8: // map (one-byte uint8_t for n follows)
  5434. {
  5435. std::uint8_t len;
  5436. return get_number(input_format_t::cbor, len) and get_cbor_object(static_cast<std::size_t>(len));
  5437. }
  5438. case 0xB9: // map (two-byte uint16_t for n follow)
  5439. {
  5440. std::uint16_t len;
  5441. return get_number(input_format_t::cbor, len) and get_cbor_object(static_cast<std::size_t>(len));
  5442. }
  5443. case 0xBA: // map (four-byte uint32_t for n follow)
  5444. {
  5445. std::uint32_t len;
  5446. return get_number(input_format_t::cbor, len) and get_cbor_object(static_cast<std::size_t>(len));
  5447. }
  5448. case 0xBB: // map (eight-byte uint64_t for n follow)
  5449. {
  5450. std::uint64_t len;
  5451. return get_number(input_format_t::cbor, len) and get_cbor_object(static_cast<std::size_t>(len));
  5452. }
  5453. case 0xBF: // map (indefinite length)
  5454. return get_cbor_object(std::size_t(-1));
  5455. case 0xF4: // false
  5456. return sax->boolean(false);
  5457. case 0xF5: // true
  5458. return sax->boolean(true);
  5459. case 0xF6: // null
  5460. return sax->null();
  5461. case 0xF9: // Half-Precision Float (two-byte IEEE 754)
  5462. {
  5463. const int byte1_raw = get();
  5464. if (JSON_HEDLEY_UNLIKELY(not unexpect_eof(input_format_t::cbor, "number")))
  5465. {
  5466. return false;
  5467. }
  5468. const int byte2_raw = get();
  5469. if (JSON_HEDLEY_UNLIKELY(not unexpect_eof(input_format_t::cbor, "number")))
  5470. {
  5471. return false;
  5472. }
  5473. const auto byte1 = static_cast<unsigned char>(byte1_raw);
  5474. const auto byte2 = static_cast<unsigned char>(byte2_raw);
  5475. // code from RFC 7049, Appendix D, Figure 3:
  5476. // As half-precision floating-point numbers were only added
  5477. // to IEEE 754 in 2008, today's programming platforms often
  5478. // still only have limited support for them. It is very
  5479. // easy to include at least decoding support for them even
  5480. // without such support. An example of a small decoder for
  5481. // half-precision floating-point numbers in the C language
  5482. // is shown in Fig. 3.
  5483. const auto half = static_cast<unsigned int>((byte1 << 8u) + byte2);
  5484. const double val = [&half]
  5485. {
  5486. const int exp = (half >> 10u) & 0x1Fu;
  5487. const unsigned int mant = half & 0x3FFu;
  5488. assert(0 <= exp and exp <= 32);
  5489. assert(mant <= 1024);
  5490. switch (exp)
  5491. {
  5492. case 0:
  5493. return std::ldexp(mant, -24);
  5494. case 31:
  5495. return (mant == 0)
  5496. ? std::numeric_limits<double>::infinity()
  5497. : std::numeric_limits<double>::quiet_NaN();
  5498. default:
  5499. return std::ldexp(mant + 1024, exp - 25);
  5500. }
  5501. }();
  5502. return sax->number_float((half & 0x8000u) != 0
  5503. ? static_cast<number_float_t>(-val)
  5504. : static_cast<number_float_t>(val), "");
  5505. }
  5506. case 0xFA: // Single-Precision Float (four-byte IEEE 754)
  5507. {
  5508. float number;
  5509. return get_number(input_format_t::cbor, number) and sax->number_float(static_cast<number_float_t>(number), "");
  5510. }
  5511. case 0xFB: // Double-Precision Float (eight-byte IEEE 754)
  5512. {
  5513. double number;
  5514. return get_number(input_format_t::cbor, number) and sax->number_float(static_cast<number_float_t>(number), "");
  5515. }
  5516. default: // anything else (0xFF is handled inside the other types)
  5517. {
  5518. auto last_token = get_token_string();
  5519. 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")));
  5520. }
  5521. }
  5522. }
  5523. /*!
  5524. @brief reads a CBOR string
  5525. This function first reads starting bytes to determine the expected
  5526. string length and then copies this number of bytes into a string.
  5527. Additionally, CBOR's strings with indefinite lengths are supported.
  5528. @param[out] result created string
  5529. @return whether string creation completed
  5530. */
  5531. bool get_cbor_string(string_t& result)
  5532. {
  5533. if (JSON_HEDLEY_UNLIKELY(not unexpect_eof(input_format_t::cbor, "string")))
  5534. {
  5535. return false;
  5536. }
  5537. switch (current)
  5538. {
  5539. // UTF-8 string (0x00..0x17 bytes follow)
  5540. case 0x60:
  5541. case 0x61:
  5542. case 0x62:
  5543. case 0x63:
  5544. case 0x64:
  5545. case 0x65:
  5546. case 0x66:
  5547. case 0x67:
  5548. case 0x68:
  5549. case 0x69:
  5550. case 0x6A:
  5551. case 0x6B:
  5552. case 0x6C:
  5553. case 0x6D:
  5554. case 0x6E:
  5555. case 0x6F:
  5556. case 0x70:
  5557. case 0x71:
  5558. case 0x72:
  5559. case 0x73:
  5560. case 0x74:
  5561. case 0x75:
  5562. case 0x76:
  5563. case 0x77:
  5564. {
  5565. return get_string(input_format_t::cbor, static_cast<unsigned int>(current) & 0x1Fu, result);
  5566. }
  5567. case 0x78: // UTF-8 string (one-byte uint8_t for n follows)
  5568. {
  5569. std::uint8_t len;
  5570. return get_number(input_format_t::cbor, len) and get_string(input_format_t::cbor, len, result);
  5571. }
  5572. case 0x79: // UTF-8 string (two-byte uint16_t for n follow)
  5573. {
  5574. std::uint16_t len;
  5575. return get_number(input_format_t::cbor, len) and get_string(input_format_t::cbor, len, result);
  5576. }
  5577. case 0x7A: // UTF-8 string (four-byte uint32_t for n follow)
  5578. {
  5579. std::uint32_t len;
  5580. return get_number(input_format_t::cbor, len) and get_string(input_format_t::cbor, len, result);
  5581. }
  5582. case 0x7B: // UTF-8 string (eight-byte uint64_t for n follow)
  5583. {
  5584. std::uint64_t len;
  5585. return get_number(input_format_t::cbor, len) and get_string(input_format_t::cbor, len, result);
  5586. }
  5587. case 0x7F: // UTF-8 string (indefinite length)
  5588. {
  5589. while (get() != 0xFF)
  5590. {
  5591. string_t chunk;
  5592. if (not get_cbor_string(chunk))
  5593. {
  5594. return false;
  5595. }
  5596. result.append(chunk);
  5597. }
  5598. return true;
  5599. }
  5600. default:
  5601. {
  5602. auto last_token = get_token_string();
  5603. 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")));
  5604. }
  5605. }
  5606. }
  5607. /*!
  5608. @brief reads a CBOR byte array
  5609. This function first reads starting bytes to determine the expected
  5610. byte array length and then copies this number of bytes into the byte array.
  5611. Additionally, CBOR's byte arrays with indefinite lengths are supported.
  5612. @param[out] result created byte array
  5613. @return whether byte array creation completed
  5614. */
  5615. bool get_cbor_binary(internal_binary_t& result)
  5616. {
  5617. if (JSON_HEDLEY_UNLIKELY(not unexpect_eof(input_format_t::cbor, "binary")))
  5618. {
  5619. return false;
  5620. }
  5621. switch (current)
  5622. {
  5623. // Binary data (0x00..0x17 bytes follow)
  5624. case 0x40:
  5625. case 0x41:
  5626. case 0x42:
  5627. case 0x43:
  5628. case 0x44:
  5629. case 0x45:
  5630. case 0x46:
  5631. case 0x47:
  5632. case 0x48:
  5633. case 0x49:
  5634. case 0x4A:
  5635. case 0x4B:
  5636. case 0x4C:
  5637. case 0x4D:
  5638. case 0x4E:
  5639. case 0x4F:
  5640. case 0x50:
  5641. case 0x51:
  5642. case 0x52:
  5643. case 0x53:
  5644. case 0x54:
  5645. case 0x55:
  5646. case 0x56:
  5647. case 0x57:
  5648. {
  5649. return get_binary(input_format_t::cbor, static_cast<unsigned int>(current) & 0x1Fu, result);
  5650. }
  5651. case 0x58: // Binary data (one-byte uint8_t for n follows)
  5652. {
  5653. std::uint8_t len;
  5654. return get_number(input_format_t::cbor, len) and get_binary(input_format_t::cbor, len, result);
  5655. }
  5656. case 0x59: // Binary data (two-byte uint16_t for n follow)
  5657. {
  5658. std::uint16_t len;
  5659. return get_number(input_format_t::cbor, len) and get_binary(input_format_t::cbor, len, result);
  5660. }
  5661. case 0x5A: // Binary data (four-byte uint32_t for n follow)
  5662. {
  5663. std::uint32_t len;
  5664. return get_number(input_format_t::cbor, len) and get_binary(input_format_t::cbor, len, result);
  5665. }
  5666. case 0x5B: // Binary data (eight-byte uint64_t for n follow)
  5667. {
  5668. std::uint64_t len;
  5669. return get_number(input_format_t::cbor, len) and get_binary(input_format_t::cbor, len, result);
  5670. }
  5671. case 0x5F: // Binary data (indefinite length)
  5672. {
  5673. while (get() != 0xFF)
  5674. {
  5675. internal_binary_t chunk;
  5676. if (not get_cbor_binary(chunk))
  5677. {
  5678. return false;
  5679. }
  5680. result.insert(result.end(), chunk.begin(), chunk.end());
  5681. }
  5682. return true;
  5683. }
  5684. default:
  5685. {
  5686. auto last_token = get_token_string();
  5687. 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")));
  5688. }
  5689. }
  5690. }
  5691. /*!
  5692. @param[in] len the length of the array or std::size_t(-1) for an
  5693. array of indefinite size
  5694. @return whether array creation completed
  5695. */
  5696. bool get_cbor_array(const std::size_t len)
  5697. {
  5698. if (JSON_HEDLEY_UNLIKELY(not sax->start_array(len)))
  5699. {
  5700. return false;
  5701. }
  5702. if (len != std::size_t(-1))
  5703. {
  5704. for (std::size_t i = 0; i < len; ++i)
  5705. {
  5706. if (JSON_HEDLEY_UNLIKELY(not parse_cbor_internal()))
  5707. {
  5708. return false;
  5709. }
  5710. }
  5711. }
  5712. else
  5713. {
  5714. while (get() != 0xFF)
  5715. {
  5716. if (JSON_HEDLEY_UNLIKELY(not parse_cbor_internal(false)))
  5717. {
  5718. return false;
  5719. }
  5720. }
  5721. }
  5722. return sax->end_array();
  5723. }
  5724. /*!
  5725. @param[in] len the length of the object or std::size_t(-1) for an
  5726. object of indefinite size
  5727. @return whether object creation completed
  5728. */
  5729. bool get_cbor_object(const std::size_t len)
  5730. {
  5731. if (JSON_HEDLEY_UNLIKELY(not sax->start_object(len)))
  5732. {
  5733. return false;
  5734. }
  5735. string_t key;
  5736. if (len != std::size_t(-1))
  5737. {
  5738. for (std::size_t i = 0; i < len; ++i)
  5739. {
  5740. get();
  5741. if (JSON_HEDLEY_UNLIKELY(not get_cbor_string(key) or not sax->key(key)))
  5742. {
  5743. return false;
  5744. }
  5745. if (JSON_HEDLEY_UNLIKELY(not parse_cbor_internal()))
  5746. {
  5747. return false;
  5748. }
  5749. key.clear();
  5750. }
  5751. }
  5752. else
  5753. {
  5754. while (get() != 0xFF)
  5755. {
  5756. if (JSON_HEDLEY_UNLIKELY(not get_cbor_string(key) or not sax->key(key)))
  5757. {
  5758. return false;
  5759. }
  5760. if (JSON_HEDLEY_UNLIKELY(not parse_cbor_internal()))
  5761. {
  5762. return false;
  5763. }
  5764. key.clear();
  5765. }
  5766. }
  5767. return sax->end_object();
  5768. }
  5769. /////////////
  5770. // MsgPack //
  5771. /////////////
  5772. /*!
  5773. @return whether a valid MessagePack value was passed to the SAX parser
  5774. */
  5775. bool parse_msgpack_internal()
  5776. {
  5777. switch (get())
  5778. {
  5779. // EOF
  5780. case std::char_traits<char>::eof():
  5781. return unexpect_eof(input_format_t::msgpack, "value");
  5782. // positive fixint
  5783. case 0x00:
  5784. case 0x01:
  5785. case 0x02:
  5786. case 0x03:
  5787. case 0x04:
  5788. case 0x05:
  5789. case 0x06:
  5790. case 0x07:
  5791. case 0x08:
  5792. case 0x09:
  5793. case 0x0A:
  5794. case 0x0B:
  5795. case 0x0C:
  5796. case 0x0D:
  5797. case 0x0E:
  5798. case 0x0F:
  5799. case 0x10:
  5800. case 0x11:
  5801. case 0x12:
  5802. case 0x13:
  5803. case 0x14:
  5804. case 0x15:
  5805. case 0x16:
  5806. case 0x17:
  5807. case 0x18:
  5808. case 0x19:
  5809. case 0x1A:
  5810. case 0x1B:
  5811. case 0x1C:
  5812. case 0x1D:
  5813. case 0x1E:
  5814. case 0x1F:
  5815. case 0x20:
  5816. case 0x21:
  5817. case 0x22:
  5818. case 0x23:
  5819. case 0x24:
  5820. case 0x25:
  5821. case 0x26:
  5822. case 0x27:
  5823. case 0x28:
  5824. case 0x29:
  5825. case 0x2A:
  5826. case 0x2B:
  5827. case 0x2C:
  5828. case 0x2D:
  5829. case 0x2E:
  5830. case 0x2F:
  5831. case 0x30:
  5832. case 0x31:
  5833. case 0x32:
  5834. case 0x33:
  5835. case 0x34:
  5836. case 0x35:
  5837. case 0x36:
  5838. case 0x37:
  5839. case 0x38:
  5840. case 0x39:
  5841. case 0x3A:
  5842. case 0x3B:
  5843. case 0x3C:
  5844. case 0x3D:
  5845. case 0x3E:
  5846. case 0x3F:
  5847. case 0x40:
  5848. case 0x41:
  5849. case 0x42:
  5850. case 0x43:
  5851. case 0x44:
  5852. case 0x45:
  5853. case 0x46:
  5854. case 0x47:
  5855. case 0x48:
  5856. case 0x49:
  5857. case 0x4A:
  5858. case 0x4B:
  5859. case 0x4C:
  5860. case 0x4D:
  5861. case 0x4E:
  5862. case 0x4F:
  5863. case 0x50:
  5864. case 0x51:
  5865. case 0x52:
  5866. case 0x53:
  5867. case 0x54:
  5868. case 0x55:
  5869. case 0x56:
  5870. case 0x57:
  5871. case 0x58:
  5872. case 0x59:
  5873. case 0x5A:
  5874. case 0x5B:
  5875. case 0x5C:
  5876. case 0x5D:
  5877. case 0x5E:
  5878. case 0x5F:
  5879. case 0x60:
  5880. case 0x61:
  5881. case 0x62:
  5882. case 0x63:
  5883. case 0x64:
  5884. case 0x65:
  5885. case 0x66:
  5886. case 0x67:
  5887. case 0x68:
  5888. case 0x69:
  5889. case 0x6A:
  5890. case 0x6B:
  5891. case 0x6C:
  5892. case 0x6D:
  5893. case 0x6E:
  5894. case 0x6F:
  5895. case 0x70:
  5896. case 0x71:
  5897. case 0x72:
  5898. case 0x73:
  5899. case 0x74:
  5900. case 0x75:
  5901. case 0x76:
  5902. case 0x77:
  5903. case 0x78:
  5904. case 0x79:
  5905. case 0x7A:
  5906. case 0x7B:
  5907. case 0x7C:
  5908. case 0x7D:
  5909. case 0x7E:
  5910. case 0x7F:
  5911. return sax->number_unsigned(static_cast<number_unsigned_t>(current));
  5912. // fixmap
  5913. case 0x80:
  5914. case 0x81:
  5915. case 0x82:
  5916. case 0x83:
  5917. case 0x84:
  5918. case 0x85:
  5919. case 0x86:
  5920. case 0x87:
  5921. case 0x88:
  5922. case 0x89:
  5923. case 0x8A:
  5924. case 0x8B:
  5925. case 0x8C:
  5926. case 0x8D:
  5927. case 0x8E:
  5928. case 0x8F:
  5929. return get_msgpack_object(static_cast<std::size_t>(static_cast<unsigned int>(current) & 0x0Fu));
  5930. // fixarray
  5931. case 0x90:
  5932. case 0x91:
  5933. case 0x92:
  5934. case 0x93:
  5935. case 0x94:
  5936. case 0x95:
  5937. case 0x96:
  5938. case 0x97:
  5939. case 0x98:
  5940. case 0x99:
  5941. case 0x9A:
  5942. case 0x9B:
  5943. case 0x9C:
  5944. case 0x9D:
  5945. case 0x9E:
  5946. case 0x9F:
  5947. return get_msgpack_array(static_cast<std::size_t>(static_cast<unsigned int>(current) & 0x0Fu));
  5948. // fixstr
  5949. case 0xA0:
  5950. case 0xA1:
  5951. case 0xA2:
  5952. case 0xA3:
  5953. case 0xA4:
  5954. case 0xA5:
  5955. case 0xA6:
  5956. case 0xA7:
  5957. case 0xA8:
  5958. case 0xA9:
  5959. case 0xAA:
  5960. case 0xAB:
  5961. case 0xAC:
  5962. case 0xAD:
  5963. case 0xAE:
  5964. case 0xAF:
  5965. case 0xB0:
  5966. case 0xB1:
  5967. case 0xB2:
  5968. case 0xB3:
  5969. case 0xB4:
  5970. case 0xB5:
  5971. case 0xB6:
  5972. case 0xB7:
  5973. case 0xB8:
  5974. case 0xB9:
  5975. case 0xBA:
  5976. case 0xBB:
  5977. case 0xBC:
  5978. case 0xBD:
  5979. case 0xBE:
  5980. case 0xBF:
  5981. case 0xD9: // str 8
  5982. case 0xDA: // str 16
  5983. case 0xDB: // str 32
  5984. {
  5985. string_t s;
  5986. return get_msgpack_string(s) and sax->string(s);
  5987. }
  5988. case 0xC0: // nil
  5989. return sax->null();
  5990. case 0xC2: // false
  5991. return sax->boolean(false);
  5992. case 0xC3: // true
  5993. return sax->boolean(true);
  5994. case 0xC4: // bin 8
  5995. case 0xC5: // bin 16
  5996. case 0xC6: // bin 32
  5997. case 0xC7: // ext 8
  5998. case 0xC8: // ext 16
  5999. case 0xC9: // ext 32
  6000. case 0xD4: // fixext 1
  6001. case 0xD5: // fixext 2
  6002. case 0xD6: // fixext 4
  6003. case 0xD7: // fixext 8
  6004. case 0xD8: // fixext 16
  6005. {
  6006. internal_binary_t b;
  6007. return get_msgpack_binary(b) and sax->binary(b);
  6008. }
  6009. case 0xCA: // float 32
  6010. {
  6011. float number;
  6012. return get_number(input_format_t::msgpack, number) and sax->number_float(static_cast<number_float_t>(number), "");
  6013. }
  6014. case 0xCB: // float 64
  6015. {
  6016. double number;
  6017. return get_number(input_format_t::msgpack, number) and sax->number_float(static_cast<number_float_t>(number), "");
  6018. }
  6019. case 0xCC: // uint 8
  6020. {
  6021. std::uint8_t number;
  6022. return get_number(input_format_t::msgpack, number) and sax->number_unsigned(number);
  6023. }
  6024. case 0xCD: // uint 16
  6025. {
  6026. std::uint16_t number;
  6027. return get_number(input_format_t::msgpack, number) and sax->number_unsigned(number);
  6028. }
  6029. case 0xCE: // uint 32
  6030. {
  6031. std::uint32_t number;
  6032. return get_number(input_format_t::msgpack, number) and sax->number_unsigned(number);
  6033. }
  6034. case 0xCF: // uint 64
  6035. {
  6036. std::uint64_t number;
  6037. return get_number(input_format_t::msgpack, number) and sax->number_unsigned(number);
  6038. }
  6039. case 0xD0: // int 8
  6040. {
  6041. std::int8_t number;
  6042. return get_number(input_format_t::msgpack, number) and sax->number_integer(number);
  6043. }
  6044. case 0xD1: // int 16
  6045. {
  6046. std::int16_t number;
  6047. return get_number(input_format_t::msgpack, number) and sax->number_integer(number);
  6048. }
  6049. case 0xD2: // int 32
  6050. {
  6051. std::int32_t number;
  6052. return get_number(input_format_t::msgpack, number) and sax->number_integer(number);
  6053. }
  6054. case 0xD3: // int 64
  6055. {
  6056. std::int64_t number;
  6057. return get_number(input_format_t::msgpack, number) and sax->number_integer(number);
  6058. }
  6059. case 0xDC: // array 16
  6060. {
  6061. std::uint16_t len;
  6062. return get_number(input_format_t::msgpack, len) and get_msgpack_array(static_cast<std::size_t>(len));
  6063. }
  6064. case 0xDD: // array 32
  6065. {
  6066. std::uint32_t len;
  6067. return get_number(input_format_t::msgpack, len) and get_msgpack_array(static_cast<std::size_t>(len));
  6068. }
  6069. case 0xDE: // map 16
  6070. {
  6071. std::uint16_t len;
  6072. return get_number(input_format_t::msgpack, len) and get_msgpack_object(static_cast<std::size_t>(len));
  6073. }
  6074. case 0xDF: // map 32
  6075. {
  6076. std::uint32_t len;
  6077. return get_number(input_format_t::msgpack, len) and get_msgpack_object(static_cast<std::size_t>(len));
  6078. }
  6079. // negative fixint
  6080. case 0xE0:
  6081. case 0xE1:
  6082. case 0xE2:
  6083. case 0xE3:
  6084. case 0xE4:
  6085. case 0xE5:
  6086. case 0xE6:
  6087. case 0xE7:
  6088. case 0xE8:
  6089. case 0xE9:
  6090. case 0xEA:
  6091. case 0xEB:
  6092. case 0xEC:
  6093. case 0xED:
  6094. case 0xEE:
  6095. case 0xEF:
  6096. case 0xF0:
  6097. case 0xF1:
  6098. case 0xF2:
  6099. case 0xF3:
  6100. case 0xF4:
  6101. case 0xF5:
  6102. case 0xF6:
  6103. case 0xF7:
  6104. case 0xF8:
  6105. case 0xF9:
  6106. case 0xFA:
  6107. case 0xFB:
  6108. case 0xFC:
  6109. case 0xFD:
  6110. case 0xFE:
  6111. case 0xFF:
  6112. return sax->number_integer(static_cast<std::int8_t>(current));
  6113. default: // anything else
  6114. {
  6115. auto last_token = get_token_string();
  6116. 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")));
  6117. }
  6118. }
  6119. }
  6120. /*!
  6121. @brief reads a MessagePack string
  6122. This function first reads starting bytes to determine the expected
  6123. string length and then copies this number of bytes into a string.
  6124. @param[out] result created string
  6125. @return whether string creation completed
  6126. */
  6127. bool get_msgpack_string(string_t& result)
  6128. {
  6129. if (JSON_HEDLEY_UNLIKELY(not unexpect_eof(input_format_t::msgpack, "string")))
  6130. {
  6131. return false;
  6132. }
  6133. switch (current)
  6134. {
  6135. // fixstr
  6136. case 0xA0:
  6137. case 0xA1:
  6138. case 0xA2:
  6139. case 0xA3:
  6140. case 0xA4:
  6141. case 0xA5:
  6142. case 0xA6:
  6143. case 0xA7:
  6144. case 0xA8:
  6145. case 0xA9:
  6146. case 0xAA:
  6147. case 0xAB:
  6148. case 0xAC:
  6149. case 0xAD:
  6150. case 0xAE:
  6151. case 0xAF:
  6152. case 0xB0:
  6153. case 0xB1:
  6154. case 0xB2:
  6155. case 0xB3:
  6156. case 0xB4:
  6157. case 0xB5:
  6158. case 0xB6:
  6159. case 0xB7:
  6160. case 0xB8:
  6161. case 0xB9:
  6162. case 0xBA:
  6163. case 0xBB:
  6164. case 0xBC:
  6165. case 0xBD:
  6166. case 0xBE:
  6167. case 0xBF:
  6168. {
  6169. return get_string(input_format_t::msgpack, static_cast<unsigned int>(current) & 0x1Fu, result);
  6170. }
  6171. case 0xD9: // str 8
  6172. {
  6173. std::uint8_t len;
  6174. return get_number(input_format_t::msgpack, len) and get_string(input_format_t::msgpack, len, result);
  6175. }
  6176. case 0xDA: // str 16
  6177. {
  6178. std::uint16_t len;
  6179. return get_number(input_format_t::msgpack, len) and get_string(input_format_t::msgpack, len, result);
  6180. }
  6181. case 0xDB: // str 32
  6182. {
  6183. std::uint32_t len;
  6184. return get_number(input_format_t::msgpack, len) and get_string(input_format_t::msgpack, len, result);
  6185. }
  6186. default:
  6187. {
  6188. auto last_token = get_token_string();
  6189. 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")));
  6190. }
  6191. }
  6192. }
  6193. /*!
  6194. @brief reads a MessagePack byte array
  6195. This function first reads starting bytes to determine the expected
  6196. byte array length and then copies this number of bytes into a byte array.
  6197. @param[out] result created byte array
  6198. @return whether byte array creation completed
  6199. */
  6200. bool get_msgpack_binary(internal_binary_t& result)
  6201. {
  6202. if (JSON_HEDLEY_UNLIKELY(not unexpect_eof(input_format_t::msgpack, "binary")))
  6203. {
  6204. return false;
  6205. }
  6206. switch (current)
  6207. {
  6208. case 0xC4: // bin 8
  6209. {
  6210. std::uint8_t len;
  6211. return get_number(input_format_t::msgpack, len) and get_binary(input_format_t::msgpack, len, result);
  6212. }
  6213. case 0xC5: // bin 16
  6214. {
  6215. std::uint16_t len;
  6216. return get_number(input_format_t::msgpack, len) and get_binary(input_format_t::msgpack, len, result);
  6217. }
  6218. case 0xC6: // bin 32
  6219. {
  6220. std::uint32_t len;
  6221. return get_number(input_format_t::msgpack, len) and get_binary(input_format_t::msgpack, len, result);
  6222. }
  6223. case 0xC7: // ext 8
  6224. {
  6225. std::uint8_t len;
  6226. result.has_subtype = true;
  6227. return get_number(input_format_t::msgpack, len) and
  6228. get_number(input_format_t::msgpack, result.subtype) and
  6229. get_binary(input_format_t::msgpack, len, result);
  6230. }
  6231. case 0xC8: // ext 16
  6232. {
  6233. std::uint16_t len;
  6234. result.has_subtype = true;
  6235. return get_number(input_format_t::msgpack, len) and
  6236. get_number(input_format_t::msgpack, result.subtype) and
  6237. get_binary(input_format_t::msgpack, len, result);
  6238. }
  6239. case 0xC9: // ext 32
  6240. {
  6241. std::uint32_t len;
  6242. result.has_subtype = true;
  6243. return get_number(input_format_t::msgpack, len) and
  6244. get_number(input_format_t::msgpack, result.subtype) and
  6245. get_binary(input_format_t::msgpack, len, result);
  6246. }
  6247. case 0xD4: // fixext 1
  6248. {
  6249. result.has_subtype = true;
  6250. return get_number(input_format_t::msgpack, result.subtype) and get_binary(input_format_t::msgpack, 1, result);
  6251. }
  6252. case 0xD5: // fixext 2
  6253. {
  6254. result.has_subtype = true;
  6255. return get_number(input_format_t::msgpack, result.subtype) and get_binary(input_format_t::msgpack, 2, result);
  6256. }
  6257. case 0xD6: // fixext 4
  6258. {
  6259. result.has_subtype = true;
  6260. return get_number(input_format_t::msgpack, result.subtype) and get_binary(input_format_t::msgpack, 4, result);
  6261. }
  6262. case 0xD7: // fixext 8
  6263. {
  6264. result.has_subtype = true;
  6265. return get_number(input_format_t::msgpack, result.subtype) and get_binary(input_format_t::msgpack, 8, result);
  6266. }
  6267. case 0xD8: // fixext 16
  6268. {
  6269. result.has_subtype = true;
  6270. return get_number(input_format_t::msgpack, result.subtype) and get_binary(input_format_t::msgpack, 16, result);
  6271. }
  6272. default:
  6273. {
  6274. auto last_token = get_token_string();
  6275. return sax->parse_error(chars_read, last_token, parse_error::create(113, chars_read, exception_message(input_format_t::msgpack, "expected binary type specification (0xC4-0xC9, 0xD4-0xD8); last byte: 0x" + last_token, "binary")));
  6276. }
  6277. }
  6278. }
  6279. /*!
  6280. @param[in] len the length of the array
  6281. @return whether array creation completed
  6282. */
  6283. bool get_msgpack_array(const std::size_t len)
  6284. {
  6285. if (JSON_HEDLEY_UNLIKELY(not sax->start_array(len)))
  6286. {
  6287. return false;
  6288. }
  6289. for (std::size_t i = 0; i < len; ++i)
  6290. {
  6291. if (JSON_HEDLEY_UNLIKELY(not parse_msgpack_internal()))
  6292. {
  6293. return false;
  6294. }
  6295. }
  6296. return sax->end_array();
  6297. }
  6298. /*!
  6299. @param[in] len the length of the object
  6300. @return whether object creation completed
  6301. */
  6302. bool get_msgpack_object(const std::size_t len)
  6303. {
  6304. if (JSON_HEDLEY_UNLIKELY(not sax->start_object(len)))
  6305. {
  6306. return false;
  6307. }
  6308. string_t key;
  6309. for (std::size_t i = 0; i < len; ++i)
  6310. {
  6311. get();
  6312. if (JSON_HEDLEY_UNLIKELY(not get_msgpack_string(key) or not sax->key(key)))
  6313. {
  6314. return false;
  6315. }
  6316. if (JSON_HEDLEY_UNLIKELY(not parse_msgpack_internal()))
  6317. {
  6318. return false;
  6319. }
  6320. key.clear();
  6321. }
  6322. return sax->end_object();
  6323. }
  6324. ////////////
  6325. // UBJSON //
  6326. ////////////
  6327. /*!
  6328. @param[in] get_char whether a new character should be retrieved from the
  6329. input (true, default) or whether the last read
  6330. character should be considered instead
  6331. @return whether a valid UBJSON value was passed to the SAX parser
  6332. */
  6333. bool parse_ubjson_internal(const bool get_char = true)
  6334. {
  6335. return get_ubjson_value(get_char ? get_ignore_noop() : current);
  6336. }
  6337. /*!
  6338. @brief reads a UBJSON string
  6339. This function is either called after reading the 'S' byte explicitly
  6340. indicating a string, or in case of an object key where the 'S' byte can be
  6341. left out.
  6342. @param[out] result created string
  6343. @param[in] get_char whether a new character should be retrieved from the
  6344. input (true, default) or whether the last read
  6345. character should be considered instead
  6346. @return whether string creation completed
  6347. */
  6348. bool get_ubjson_string(string_t& result, const bool get_char = true)
  6349. {
  6350. if (get_char)
  6351. {
  6352. get(); // TODO(niels): may we ignore N here?
  6353. }
  6354. if (JSON_HEDLEY_UNLIKELY(not unexpect_eof(input_format_t::ubjson, "value")))
  6355. {
  6356. return false;
  6357. }
  6358. switch (current)
  6359. {
  6360. case 'U':
  6361. {
  6362. std::uint8_t len;
  6363. return get_number(input_format_t::ubjson, len) and get_string(input_format_t::ubjson, len, result);
  6364. }
  6365. case 'i':
  6366. {
  6367. std::int8_t len;
  6368. return get_number(input_format_t::ubjson, len) and get_string(input_format_t::ubjson, len, result);
  6369. }
  6370. case 'I':
  6371. {
  6372. std::int16_t len;
  6373. return get_number(input_format_t::ubjson, len) and get_string(input_format_t::ubjson, len, result);
  6374. }
  6375. case 'l':
  6376. {
  6377. std::int32_t len;
  6378. return get_number(input_format_t::ubjson, len) and get_string(input_format_t::ubjson, len, result);
  6379. }
  6380. case 'L':
  6381. {
  6382. std::int64_t len;
  6383. return get_number(input_format_t::ubjson, len) and get_string(input_format_t::ubjson, len, result);
  6384. }
  6385. default:
  6386. auto last_token = get_token_string();
  6387. 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")));
  6388. }
  6389. }
  6390. /*!
  6391. @param[out] result determined size
  6392. @return whether size determination completed
  6393. */
  6394. bool get_ubjson_size_value(std::size_t& result)
  6395. {
  6396. switch (get_ignore_noop())
  6397. {
  6398. case 'U':
  6399. {
  6400. std::uint8_t number;
  6401. if (JSON_HEDLEY_UNLIKELY(not get_number(input_format_t::ubjson, number)))
  6402. {
  6403. return false;
  6404. }
  6405. result = static_cast<std::size_t>(number);
  6406. return true;
  6407. }
  6408. case 'i':
  6409. {
  6410. std::int8_t number;
  6411. if (JSON_HEDLEY_UNLIKELY(not get_number(input_format_t::ubjson, number)))
  6412. {
  6413. return false;
  6414. }
  6415. result = static_cast<std::size_t>(number);
  6416. return true;
  6417. }
  6418. case 'I':
  6419. {
  6420. std::int16_t number;
  6421. if (JSON_HEDLEY_UNLIKELY(not get_number(input_format_t::ubjson, number)))
  6422. {
  6423. return false;
  6424. }
  6425. result = static_cast<std::size_t>(number);
  6426. return true;
  6427. }
  6428. case 'l':
  6429. {
  6430. std::int32_t number;
  6431. if (JSON_HEDLEY_UNLIKELY(not get_number(input_format_t::ubjson, number)))
  6432. {
  6433. return false;
  6434. }
  6435. result = static_cast<std::size_t>(number);
  6436. return true;
  6437. }
  6438. case 'L':
  6439. {
  6440. std::int64_t number;
  6441. if (JSON_HEDLEY_UNLIKELY(not get_number(input_format_t::ubjson, number)))
  6442. {
  6443. return false;
  6444. }
  6445. result = static_cast<std::size_t>(number);
  6446. return true;
  6447. }
  6448. default:
  6449. {
  6450. auto last_token = get_token_string();
  6451. 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")));
  6452. }
  6453. }
  6454. }
  6455. /*!
  6456. @brief determine the type and size for a container
  6457. In the optimized UBJSON format, a type and a size can be provided to allow
  6458. for a more compact representation.
  6459. @param[out] result pair of the size and the type
  6460. @return whether pair creation completed
  6461. */
  6462. bool get_ubjson_size_type(std::pair<std::size_t, int>& result)
  6463. {
  6464. result.first = string_t::npos; // size
  6465. result.second = 0; // type
  6466. get_ignore_noop();
  6467. if (current == '$')
  6468. {
  6469. result.second = get(); // must not ignore 'N', because 'N' maybe the type
  6470. if (JSON_HEDLEY_UNLIKELY(not unexpect_eof(input_format_t::ubjson, "type")))
  6471. {
  6472. return false;
  6473. }
  6474. get_ignore_noop();
  6475. if (JSON_HEDLEY_UNLIKELY(current != '#'))
  6476. {
  6477. if (JSON_HEDLEY_UNLIKELY(not unexpect_eof(input_format_t::ubjson, "value")))
  6478. {
  6479. return false;
  6480. }
  6481. auto last_token = get_token_string();
  6482. 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")));
  6483. }
  6484. return get_ubjson_size_value(result.first);
  6485. }
  6486. if (current == '#')
  6487. {
  6488. return get_ubjson_size_value(result.first);
  6489. }
  6490. return true;
  6491. }
  6492. /*!
  6493. @param prefix the previously read or set type prefix
  6494. @return whether value creation completed
  6495. */
  6496. bool get_ubjson_value(const int prefix)
  6497. {
  6498. switch (prefix)
  6499. {
  6500. case std::char_traits<char>::eof(): // EOF
  6501. return unexpect_eof(input_format_t::ubjson, "value");
  6502. case 'T': // true
  6503. return sax->boolean(true);
  6504. case 'F': // false
  6505. return sax->boolean(false);
  6506. case 'Z': // null
  6507. return sax->null();
  6508. case 'U':
  6509. {
  6510. std::uint8_t number;
  6511. return get_number(input_format_t::ubjson, number) and sax->number_unsigned(number);
  6512. }
  6513. case 'i':
  6514. {
  6515. std::int8_t number;
  6516. return get_number(input_format_t::ubjson, number) and sax->number_integer(number);
  6517. }
  6518. case 'I':
  6519. {
  6520. std::int16_t number;
  6521. return get_number(input_format_t::ubjson, number) and sax->number_integer(number);
  6522. }
  6523. case 'l':
  6524. {
  6525. std::int32_t number;
  6526. return get_number(input_format_t::ubjson, number) and sax->number_integer(number);
  6527. }
  6528. case 'L':
  6529. {
  6530. std::int64_t number;
  6531. return get_number(input_format_t::ubjson, number) and sax->number_integer(number);
  6532. }
  6533. case 'd':
  6534. {
  6535. float number;
  6536. return get_number(input_format_t::ubjson, number) and sax->number_float(static_cast<number_float_t>(number), "");
  6537. }
  6538. case 'D':
  6539. {
  6540. double number;
  6541. return get_number(input_format_t::ubjson, number) and sax->number_float(static_cast<number_float_t>(number), "");
  6542. }
  6543. case 'C': // char
  6544. {
  6545. get();
  6546. if (JSON_HEDLEY_UNLIKELY(not unexpect_eof(input_format_t::ubjson, "char")))
  6547. {
  6548. return false;
  6549. }
  6550. if (JSON_HEDLEY_UNLIKELY(current > 127))
  6551. {
  6552. auto last_token = get_token_string();
  6553. 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")));
  6554. }
  6555. string_t s(1, static_cast<char>(current));
  6556. return sax->string(s);
  6557. }
  6558. case 'S': // string
  6559. {
  6560. string_t s;
  6561. return get_ubjson_string(s) and sax->string(s);
  6562. }
  6563. case '[': // array
  6564. return get_ubjson_array();
  6565. case '{': // object
  6566. return get_ubjson_object();
  6567. default: // anything else
  6568. {
  6569. auto last_token = get_token_string();
  6570. 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")));
  6571. }
  6572. }
  6573. }
  6574. /*!
  6575. @return whether array creation completed
  6576. */
  6577. bool get_ubjson_array()
  6578. {
  6579. std::pair<std::size_t, int> size_and_type;
  6580. if (JSON_HEDLEY_UNLIKELY(not get_ubjson_size_type(size_and_type)))
  6581. {
  6582. return false;
  6583. }
  6584. if (size_and_type.first != string_t::npos)
  6585. {
  6586. if (JSON_HEDLEY_UNLIKELY(not sax->start_array(size_and_type.first)))
  6587. {
  6588. return false;
  6589. }
  6590. if (size_and_type.second != 0)
  6591. {
  6592. if (size_and_type.second != 'N')
  6593. {
  6594. for (std::size_t i = 0; i < size_and_type.first; ++i)
  6595. {
  6596. if (JSON_HEDLEY_UNLIKELY(not get_ubjson_value(size_and_type.second)))
  6597. {
  6598. return false;
  6599. }
  6600. }
  6601. }
  6602. }
  6603. else
  6604. {
  6605. for (std::size_t i = 0; i < size_and_type.first; ++i)
  6606. {
  6607. if (JSON_HEDLEY_UNLIKELY(not parse_ubjson_internal()))
  6608. {
  6609. return false;
  6610. }
  6611. }
  6612. }
  6613. }
  6614. else
  6615. {
  6616. if (JSON_HEDLEY_UNLIKELY(not sax->start_array(std::size_t(-1))))
  6617. {
  6618. return false;
  6619. }
  6620. while (current != ']')
  6621. {
  6622. if (JSON_HEDLEY_UNLIKELY(not parse_ubjson_internal(false)))
  6623. {
  6624. return false;
  6625. }
  6626. get_ignore_noop();
  6627. }
  6628. }
  6629. return sax->end_array();
  6630. }
  6631. /*!
  6632. @return whether object creation completed
  6633. */
  6634. bool get_ubjson_object()
  6635. {
  6636. std::pair<std::size_t, int> size_and_type;
  6637. if (JSON_HEDLEY_UNLIKELY(not get_ubjson_size_type(size_and_type)))
  6638. {
  6639. return false;
  6640. }
  6641. string_t key;
  6642. if (size_and_type.first != string_t::npos)
  6643. {
  6644. if (JSON_HEDLEY_UNLIKELY(not sax->start_object(size_and_type.first)))
  6645. {
  6646. return false;
  6647. }
  6648. if (size_and_type.second != 0)
  6649. {
  6650. for (std::size_t i = 0; i < size_and_type.first; ++i)
  6651. {
  6652. if (JSON_HEDLEY_UNLIKELY(not get_ubjson_string(key) or not sax->key(key)))
  6653. {
  6654. return false;
  6655. }
  6656. if (JSON_HEDLEY_UNLIKELY(not get_ubjson_value(size_and_type.second)))
  6657. {
  6658. return false;
  6659. }
  6660. key.clear();
  6661. }
  6662. }
  6663. else
  6664. {
  6665. for (std::size_t i = 0; i < size_and_type.first; ++i)
  6666. {
  6667. if (JSON_HEDLEY_UNLIKELY(not get_ubjson_string(key) or not sax->key(key)))
  6668. {
  6669. return false;
  6670. }
  6671. if (JSON_HEDLEY_UNLIKELY(not parse_ubjson_internal()))
  6672. {
  6673. return false;
  6674. }
  6675. key.clear();
  6676. }
  6677. }
  6678. }
  6679. else
  6680. {
  6681. if (JSON_HEDLEY_UNLIKELY(not sax->start_object(std::size_t(-1))))
  6682. {
  6683. return false;
  6684. }
  6685. while (current != '}')
  6686. {
  6687. if (JSON_HEDLEY_UNLIKELY(not get_ubjson_string(key, false) or not sax->key(key)))
  6688. {
  6689. return false;
  6690. }
  6691. if (JSON_HEDLEY_UNLIKELY(not parse_ubjson_internal()))
  6692. {
  6693. return false;
  6694. }
  6695. get_ignore_noop();
  6696. key.clear();
  6697. }
  6698. }
  6699. return sax->end_object();
  6700. }
  6701. // Note, no reader for UBJSON binary types is implemented because they do
  6702. // not exist
  6703. ///////////////////////
  6704. // Utility functions //
  6705. ///////////////////////
  6706. /*!
  6707. @brief get next character from the input
  6708. This function provides the interface to the used input adapter. It does
  6709. not throw in case the input reached EOF, but returns a -'ve valued
  6710. `std::char_traits<char>::eof()` in that case.
  6711. @return character read from the input
  6712. */
  6713. int get()
  6714. {
  6715. ++chars_read;
  6716. return current = ia->get_character();
  6717. }
  6718. /*!
  6719. @return character read from the input after ignoring all 'N' entries
  6720. */
  6721. int get_ignore_noop()
  6722. {
  6723. do
  6724. {
  6725. get();
  6726. }
  6727. while (current == 'N');
  6728. return current;
  6729. }
  6730. /*
  6731. @brief read a number from the input
  6732. @tparam NumberType the type of the number
  6733. @param[in] format the current format (for diagnostics)
  6734. @param[out] result number of type @a NumberType
  6735. @return whether conversion completed
  6736. @note This function needs to respect the system's endianess, because
  6737. bytes in CBOR, MessagePack, and UBJSON are stored in network order
  6738. (big endian) and therefore need reordering on little endian systems.
  6739. */
  6740. template<typename NumberType, bool InputIsLittleEndian = false>
  6741. bool get_number(const input_format_t format, NumberType& result)
  6742. {
  6743. // step 1: read input into array with system's byte order
  6744. std::array<std::uint8_t, sizeof(NumberType)> vec;
  6745. for (std::size_t i = 0; i < sizeof(NumberType); ++i)
  6746. {
  6747. get();
  6748. if (JSON_HEDLEY_UNLIKELY(not unexpect_eof(format, "number")))
  6749. {
  6750. return false;
  6751. }
  6752. // reverse byte order prior to conversion if necessary
  6753. if (is_little_endian != InputIsLittleEndian)
  6754. {
  6755. vec[sizeof(NumberType) - i - 1] = static_cast<std::uint8_t>(current);
  6756. }
  6757. else
  6758. {
  6759. vec[i] = static_cast<std::uint8_t>(current); // LCOV_EXCL_LINE
  6760. }
  6761. }
  6762. // step 2: convert array into number of type T and return
  6763. std::memcpy(&result, vec.data(), sizeof(NumberType));
  6764. return true;
  6765. }
  6766. /*!
  6767. @brief create a string by reading characters from the input
  6768. @tparam NumberType the type of the number
  6769. @param[in] format the current format (for diagnostics)
  6770. @param[in] len number of characters to read
  6771. @param[out] result string created by reading @a len bytes
  6772. @return whether string creation completed
  6773. @note We can not reserve @a len bytes for the result, because @a len
  6774. may be too large. Usually, @ref unexpect_eof() detects the end of
  6775. the input before we run out of string memory.
  6776. */
  6777. template<typename NumberType>
  6778. bool get_string(const input_format_t format,
  6779. const NumberType len,
  6780. string_t& result)
  6781. {
  6782. bool success = true;
  6783. std::generate_n(std::back_inserter(result), len, [this, &success, &format]()
  6784. {
  6785. get();
  6786. if (JSON_HEDLEY_UNLIKELY(not unexpect_eof(format, "string")))
  6787. {
  6788. success = false;
  6789. }
  6790. return static_cast<char>(current);
  6791. });
  6792. return success;
  6793. }
  6794. /*!
  6795. @brief create a byte array by reading bytes from the input
  6796. @tparam NumberType the type of the number
  6797. @param[in] format the current format (for diagnostics)
  6798. @param[in] len number of bytes to read
  6799. @param[out] result byte array created by reading @a len bytes
  6800. @return whether byte array creation completed
  6801. @note We can not reserve @a len bytes for the result, because @a len
  6802. may be too large. Usually, @ref unexpect_eof() detects the end of
  6803. the input before we run out of memory.
  6804. */
  6805. template<typename NumberType>
  6806. bool get_binary(const input_format_t format,
  6807. const NumberType len,
  6808. internal_binary_t& result)
  6809. {
  6810. bool success = true;
  6811. std::generate_n(std::back_inserter(result), len, [this, &success, &format]()
  6812. {
  6813. get();
  6814. if (JSON_HEDLEY_UNLIKELY(not unexpect_eof(format, "binary")))
  6815. {
  6816. success = false;
  6817. }
  6818. return static_cast<uint8_t>(current);
  6819. });
  6820. return success;
  6821. }
  6822. /*!
  6823. @param[in] format the current format (for diagnostics)
  6824. @param[in] context further context information (for diagnostics)
  6825. @return whether the last read character is not EOF
  6826. */
  6827. JSON_HEDLEY_NON_NULL(3)
  6828. bool unexpect_eof(const input_format_t format, const char* context) const
  6829. {
  6830. if (JSON_HEDLEY_UNLIKELY(current == std::char_traits<char>::eof()))
  6831. {
  6832. return sax->parse_error(chars_read, "<end of file>",
  6833. parse_error::create(110, chars_read, exception_message(format, "unexpected end of input", context)));
  6834. }
  6835. return true;
  6836. }
  6837. /*!
  6838. @return a string representation of the last read byte
  6839. */
  6840. std::string get_token_string() const
  6841. {
  6842. std::array<char, 3> cr{{}};
  6843. (std::snprintf)(cr.data(), cr.size(), "%.2hhX", static_cast<unsigned char>(current));
  6844. return std::string{cr.data()};
  6845. }
  6846. /*!
  6847. @param[in] format the current format
  6848. @param[in] detail a detailed error message
  6849. @param[in] context further context information
  6850. @return a message string to use in the parse_error exceptions
  6851. */
  6852. std::string exception_message(const input_format_t format,
  6853. const std::string& detail,
  6854. const std::string& context) const
  6855. {
  6856. std::string error_msg = "syntax error while parsing ";
  6857. switch (format)
  6858. {
  6859. case input_format_t::cbor:
  6860. error_msg += "CBOR";
  6861. break;
  6862. case input_format_t::msgpack:
  6863. error_msg += "MessagePack";
  6864. break;
  6865. case input_format_t::ubjson:
  6866. error_msg += "UBJSON";
  6867. break;
  6868. case input_format_t::bson:
  6869. error_msg += "BSON";
  6870. break;
  6871. default: // LCOV_EXCL_LINE
  6872. assert(false); // LCOV_EXCL_LINE
  6873. }
  6874. return error_msg + " " + context + ": " + detail;
  6875. }
  6876. private:
  6877. /// input adapter
  6878. input_adapter_t ia = nullptr;
  6879. /// the current character
  6880. int current = std::char_traits<char>::eof();
  6881. /// the number of characters read
  6882. std::size_t chars_read = 0;
  6883. /// whether we can assume little endianess
  6884. const bool is_little_endian = little_endianess();
  6885. /// the SAX parser
  6886. json_sax_t* sax = nullptr;
  6887. };
  6888. } // namespace detail
  6889. } // namespace nlohmann
  6890. // #include <nlohmann/detail/input/input_adapters.hpp>
  6891. // #include <nlohmann/detail/input/lexer.hpp>
  6892. #include <array> // array
  6893. #include <clocale> // localeconv
  6894. #include <cstddef> // size_t
  6895. #include <cstdio> // snprintf
  6896. #include <cstdlib> // strtof, strtod, strtold, strtoll, strtoull
  6897. #include <initializer_list> // initializer_list
  6898. #include <string> // char_traits, string
  6899. #include <utility> // move
  6900. #include <vector> // vector
  6901. // #include <nlohmann/detail/input/input_adapters.hpp>
  6902. // #include <nlohmann/detail/input/position_t.hpp>
  6903. // #include <nlohmann/detail/macro_scope.hpp>
  6904. namespace nlohmann
  6905. {
  6906. namespace detail
  6907. {
  6908. ///////////
  6909. // lexer //
  6910. ///////////
  6911. /*!
  6912. @brief lexical analysis
  6913. This class organizes the lexical analysis during JSON deserialization.
  6914. */
  6915. template<typename BasicJsonType>
  6916. class lexer
  6917. {
  6918. using number_integer_t = typename BasicJsonType::number_integer_t;
  6919. using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
  6920. using number_float_t = typename BasicJsonType::number_float_t;
  6921. using string_t = typename BasicJsonType::string_t;
  6922. public:
  6923. /// token types for the parser
  6924. enum class token_type
  6925. {
  6926. uninitialized, ///< indicating the scanner is uninitialized
  6927. literal_true, ///< the `true` literal
  6928. literal_false, ///< the `false` literal
  6929. literal_null, ///< the `null` literal
  6930. value_string, ///< a string -- use get_string() for actual value
  6931. value_unsigned, ///< an unsigned integer -- use get_number_unsigned() for actual value
  6932. value_integer, ///< a signed integer -- use get_number_integer() for actual value
  6933. value_float, ///< an floating point number -- use get_number_float() for actual value
  6934. begin_array, ///< the character for array begin `[`
  6935. begin_object, ///< the character for object begin `{`
  6936. end_array, ///< the character for array end `]`
  6937. end_object, ///< the character for object end `}`
  6938. name_separator, ///< the name separator `:`
  6939. value_separator, ///< the value separator `,`
  6940. parse_error, ///< indicating a parse error
  6941. end_of_input, ///< indicating the end of the input buffer
  6942. literal_or_value ///< a literal or the begin of a value (only for diagnostics)
  6943. };
  6944. /// return name of values of type token_type (only used for errors)
  6945. JSON_HEDLEY_RETURNS_NON_NULL
  6946. JSON_HEDLEY_CONST
  6947. static const char* token_type_name(const token_type t) noexcept
  6948. {
  6949. switch (t)
  6950. {
  6951. case token_type::uninitialized:
  6952. return "<uninitialized>";
  6953. case token_type::literal_true:
  6954. return "true literal";
  6955. case token_type::literal_false:
  6956. return "false literal";
  6957. case token_type::literal_null:
  6958. return "null literal";
  6959. case token_type::value_string:
  6960. return "string literal";
  6961. case lexer::token_type::value_unsigned:
  6962. case lexer::token_type::value_integer:
  6963. case lexer::token_type::value_float:
  6964. return "number literal";
  6965. case token_type::begin_array:
  6966. return "'['";
  6967. case token_type::begin_object:
  6968. return "'{'";
  6969. case token_type::end_array:
  6970. return "']'";
  6971. case token_type::end_object:
  6972. return "'}'";
  6973. case token_type::name_separator:
  6974. return "':'";
  6975. case token_type::value_separator:
  6976. return "','";
  6977. case token_type::parse_error:
  6978. return "<parse error>";
  6979. case token_type::end_of_input:
  6980. return "end of input";
  6981. case token_type::literal_or_value:
  6982. return "'[', '{', or a literal";
  6983. // LCOV_EXCL_START
  6984. default: // catch non-enum values
  6985. return "unknown token";
  6986. // LCOV_EXCL_STOP
  6987. }
  6988. }
  6989. explicit lexer(detail::input_adapter_t&& adapter)
  6990. : ia(std::move(adapter)), decimal_point_char(get_decimal_point()) {}
  6991. // delete because of pointer members
  6992. lexer(const lexer&) = delete;
  6993. lexer(lexer&&) = delete;
  6994. lexer& operator=(lexer&) = delete;
  6995. lexer& operator=(lexer&&) = delete;
  6996. ~lexer() = default;
  6997. private:
  6998. /////////////////////
  6999. // locales
  7000. /////////////////////
  7001. /// return the locale-dependent decimal point
  7002. JSON_HEDLEY_PURE
  7003. static char get_decimal_point() noexcept
  7004. {
  7005. const auto loc = localeconv();
  7006. assert(loc != nullptr);
  7007. return (loc->decimal_point == nullptr) ? '.' : *(loc->decimal_point);
  7008. }
  7009. /////////////////////
  7010. // scan functions
  7011. /////////////////////
  7012. /*!
  7013. @brief get codepoint from 4 hex characters following `\u`
  7014. For input "\u c1 c2 c3 c4" the codepoint is:
  7015. (c1 * 0x1000) + (c2 * 0x0100) + (c3 * 0x0010) + c4
  7016. = (c1 << 12) + (c2 << 8) + (c3 << 4) + (c4 << 0)
  7017. Furthermore, the possible characters '0'..'9', 'A'..'F', and 'a'..'f'
  7018. must be converted to the integers 0x0..0x9, 0xA..0xF, 0xA..0xF, resp. The
  7019. conversion is done by subtracting the offset (0x30, 0x37, and 0x57)
  7020. between the ASCII value of the character and the desired integer value.
  7021. @return codepoint (0x0000..0xFFFF) or -1 in case of an error (e.g. EOF or
  7022. non-hex character)
  7023. */
  7024. int get_codepoint()
  7025. {
  7026. // this function only makes sense after reading `\u`
  7027. assert(current == 'u');
  7028. int codepoint = 0;
  7029. const auto factors = { 12u, 8u, 4u, 0u };
  7030. for (const auto factor : factors)
  7031. {
  7032. get();
  7033. if (current >= '0' and current <= '9')
  7034. {
  7035. codepoint += static_cast<int>((static_cast<unsigned int>(current) - 0x30u) << factor);
  7036. }
  7037. else if (current >= 'A' and current <= 'F')
  7038. {
  7039. codepoint += static_cast<int>((static_cast<unsigned int>(current) - 0x37u) << factor);
  7040. }
  7041. else if (current >= 'a' and current <= 'f')
  7042. {
  7043. codepoint += static_cast<int>((static_cast<unsigned int>(current) - 0x57u) << factor);
  7044. }
  7045. else
  7046. {
  7047. return -1;
  7048. }
  7049. }
  7050. assert(0x0000 <= codepoint and codepoint <= 0xFFFF);
  7051. return codepoint;
  7052. }
  7053. /*!
  7054. @brief check if the next byte(s) are inside a given range
  7055. Adds the current byte and, for each passed range, reads a new byte and
  7056. checks if it is inside the range. If a violation was detected, set up an
  7057. error message and return false. Otherwise, return true.
  7058. @param[in] ranges list of integers; interpreted as list of pairs of
  7059. inclusive lower and upper bound, respectively
  7060. @pre The passed list @a ranges must have 2, 4, or 6 elements; that is,
  7061. 1, 2, or 3 pairs. This precondition is enforced by an assertion.
  7062. @return true if and only if no range violation was detected
  7063. */
  7064. bool next_byte_in_range(std::initializer_list<int> ranges)
  7065. {
  7066. assert(ranges.size() == 2 or ranges.size() == 4 or ranges.size() == 6);
  7067. add(current);
  7068. for (auto range = ranges.begin(); range != ranges.end(); ++range)
  7069. {
  7070. get();
  7071. if (JSON_HEDLEY_LIKELY(*range <= current and current <= *(++range)))
  7072. {
  7073. add(current);
  7074. }
  7075. else
  7076. {
  7077. error_message = "invalid string: ill-formed UTF-8 byte";
  7078. return false;
  7079. }
  7080. }
  7081. return true;
  7082. }
  7083. /*!
  7084. @brief scan a string literal
  7085. This function scans a string according to Sect. 7 of RFC 7159. While
  7086. scanning, bytes are escaped and copied into buffer token_buffer. Then the
  7087. function returns successfully, token_buffer is *not* null-terminated (as it
  7088. may contain \0 bytes), and token_buffer.size() is the number of bytes in the
  7089. string.
  7090. @return token_type::value_string if string could be successfully scanned,
  7091. token_type::parse_error otherwise
  7092. @note In case of errors, variable error_message contains a textual
  7093. description.
  7094. */
  7095. token_type scan_string()
  7096. {
  7097. // reset token_buffer (ignore opening quote)
  7098. reset();
  7099. // we entered the function by reading an open quote
  7100. assert(current == '\"');
  7101. while (true)
  7102. {
  7103. // get next character
  7104. switch (get())
  7105. {
  7106. // end of file while parsing string
  7107. case std::char_traits<char>::eof():
  7108. {
  7109. error_message = "invalid string: missing closing quote";
  7110. return token_type::parse_error;
  7111. }
  7112. // closing quote
  7113. case '\"':
  7114. {
  7115. return token_type::value_string;
  7116. }
  7117. // escapes
  7118. case '\\':
  7119. {
  7120. switch (get())
  7121. {
  7122. // quotation mark
  7123. case '\"':
  7124. add('\"');
  7125. break;
  7126. // reverse solidus
  7127. case '\\':
  7128. add('\\');
  7129. break;
  7130. // solidus
  7131. case '/':
  7132. add('/');
  7133. break;
  7134. // backspace
  7135. case 'b':
  7136. add('\b');
  7137. break;
  7138. // form feed
  7139. case 'f':
  7140. add('\f');
  7141. break;
  7142. // line feed
  7143. case 'n':
  7144. add('\n');
  7145. break;
  7146. // carriage return
  7147. case 'r':
  7148. add('\r');
  7149. break;
  7150. // tab
  7151. case 't':
  7152. add('\t');
  7153. break;
  7154. // unicode escapes
  7155. case 'u':
  7156. {
  7157. const int codepoint1 = get_codepoint();
  7158. int codepoint = codepoint1; // start with codepoint1
  7159. if (JSON_HEDLEY_UNLIKELY(codepoint1 == -1))
  7160. {
  7161. error_message = "invalid string: '\\u' must be followed by 4 hex digits";
  7162. return token_type::parse_error;
  7163. }
  7164. // check if code point is a high surrogate
  7165. if (0xD800 <= codepoint1 and codepoint1 <= 0xDBFF)
  7166. {
  7167. // expect next \uxxxx entry
  7168. if (JSON_HEDLEY_LIKELY(get() == '\\' and get() == 'u'))
  7169. {
  7170. const int codepoint2 = get_codepoint();
  7171. if (JSON_HEDLEY_UNLIKELY(codepoint2 == -1))
  7172. {
  7173. error_message = "invalid string: '\\u' must be followed by 4 hex digits";
  7174. return token_type::parse_error;
  7175. }
  7176. // check if codepoint2 is a low surrogate
  7177. if (JSON_HEDLEY_LIKELY(0xDC00 <= codepoint2 and codepoint2 <= 0xDFFF))
  7178. {
  7179. // overwrite codepoint
  7180. codepoint = static_cast<int>(
  7181. // high surrogate occupies the most significant 22 bits
  7182. (static_cast<unsigned int>(codepoint1) << 10u)
  7183. // low surrogate occupies the least significant 15 bits
  7184. + static_cast<unsigned int>(codepoint2)
  7185. // there is still the 0xD800, 0xDC00 and 0x10000 noise
  7186. // in the result so we have to subtract with:
  7187. // (0xD800 << 10) + DC00 - 0x10000 = 0x35FDC00
  7188. - 0x35FDC00u);
  7189. }
  7190. else
  7191. {
  7192. error_message = "invalid string: surrogate U+D800..U+DBFF must be followed by U+DC00..U+DFFF";
  7193. return token_type::parse_error;
  7194. }
  7195. }
  7196. else
  7197. {
  7198. error_message = "invalid string: surrogate U+D800..U+DBFF must be followed by U+DC00..U+DFFF";
  7199. return token_type::parse_error;
  7200. }
  7201. }
  7202. else
  7203. {
  7204. if (JSON_HEDLEY_UNLIKELY(0xDC00 <= codepoint1 and codepoint1 <= 0xDFFF))
  7205. {
  7206. error_message = "invalid string: surrogate U+DC00..U+DFFF must follow U+D800..U+DBFF";
  7207. return token_type::parse_error;
  7208. }
  7209. }
  7210. // result of the above calculation yields a proper codepoint
  7211. assert(0x00 <= codepoint and codepoint <= 0x10FFFF);
  7212. // translate codepoint into bytes
  7213. if (codepoint < 0x80)
  7214. {
  7215. // 1-byte characters: 0xxxxxxx (ASCII)
  7216. add(codepoint);
  7217. }
  7218. else if (codepoint <= 0x7FF)
  7219. {
  7220. // 2-byte characters: 110xxxxx 10xxxxxx
  7221. add(static_cast<int>(0xC0u | (static_cast<unsigned int>(codepoint) >> 6u)));
  7222. add(static_cast<int>(0x80u | (static_cast<unsigned int>(codepoint) & 0x3Fu)));
  7223. }
  7224. else if (codepoint <= 0xFFFF)
  7225. {
  7226. // 3-byte characters: 1110xxxx 10xxxxxx 10xxxxxx
  7227. add(static_cast<int>(0xE0u | (static_cast<unsigned int>(codepoint) >> 12u)));
  7228. add(static_cast<int>(0x80u | ((static_cast<unsigned int>(codepoint) >> 6u) & 0x3Fu)));
  7229. add(static_cast<int>(0x80u | (static_cast<unsigned int>(codepoint) & 0x3Fu)));
  7230. }
  7231. else
  7232. {
  7233. // 4-byte characters: 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
  7234. add(static_cast<int>(0xF0u | (static_cast<unsigned int>(codepoint) >> 18u)));
  7235. add(static_cast<int>(0x80u | ((static_cast<unsigned int>(codepoint) >> 12u) & 0x3Fu)));
  7236. add(static_cast<int>(0x80u | ((static_cast<unsigned int>(codepoint) >> 6u) & 0x3Fu)));
  7237. add(static_cast<int>(0x80u | (static_cast<unsigned int>(codepoint) & 0x3Fu)));
  7238. }
  7239. break;
  7240. }
  7241. // other characters after escape
  7242. default:
  7243. error_message = "invalid string: forbidden character after backslash";
  7244. return token_type::parse_error;
  7245. }
  7246. break;
  7247. }
  7248. // invalid control characters
  7249. case 0x00:
  7250. {
  7251. error_message = "invalid string: control character U+0000 (NUL) must be escaped to \\u0000";
  7252. return token_type::parse_error;
  7253. }
  7254. case 0x01:
  7255. {
  7256. error_message = "invalid string: control character U+0001 (SOH) must be escaped to \\u0001";
  7257. return token_type::parse_error;
  7258. }
  7259. case 0x02:
  7260. {
  7261. error_message = "invalid string: control character U+0002 (STX) must be escaped to \\u0002";
  7262. return token_type::parse_error;
  7263. }
  7264. case 0x03:
  7265. {
  7266. error_message = "invalid string: control character U+0003 (ETX) must be escaped to \\u0003";
  7267. return token_type::parse_error;
  7268. }
  7269. case 0x04:
  7270. {
  7271. error_message = "invalid string: control character U+0004 (EOT) must be escaped to \\u0004";
  7272. return token_type::parse_error;
  7273. }
  7274. case 0x05:
  7275. {
  7276. error_message = "invalid string: control character U+0005 (ENQ) must be escaped to \\u0005";
  7277. return token_type::parse_error;
  7278. }
  7279. case 0x06:
  7280. {
  7281. error_message = "invalid string: control character U+0006 (ACK) must be escaped to \\u0006";
  7282. return token_type::parse_error;
  7283. }
  7284. case 0x07:
  7285. {
  7286. error_message = "invalid string: control character U+0007 (BEL) must be escaped to \\u0007";
  7287. return token_type::parse_error;
  7288. }
  7289. case 0x08:
  7290. {
  7291. error_message = "invalid string: control character U+0008 (BS) must be escaped to \\u0008 or \\b";
  7292. return token_type::parse_error;
  7293. }
  7294. case 0x09:
  7295. {
  7296. error_message = "invalid string: control character U+0009 (HT) must be escaped to \\u0009 or \\t";
  7297. return token_type::parse_error;
  7298. }
  7299. case 0x0A:
  7300. {
  7301. error_message = "invalid string: control character U+000A (LF) must be escaped to \\u000A or \\n";
  7302. return token_type::parse_error;
  7303. }
  7304. case 0x0B:
  7305. {
  7306. error_message = "invalid string: control character U+000B (VT) must be escaped to \\u000B";
  7307. return token_type::parse_error;
  7308. }
  7309. case 0x0C:
  7310. {
  7311. error_message = "invalid string: control character U+000C (FF) must be escaped to \\u000C or \\f";
  7312. return token_type::parse_error;
  7313. }
  7314. case 0x0D:
  7315. {
  7316. error_message = "invalid string: control character U+000D (CR) must be escaped to \\u000D or \\r";
  7317. return token_type::parse_error;
  7318. }
  7319. case 0x0E:
  7320. {
  7321. error_message = "invalid string: control character U+000E (SO) must be escaped to \\u000E";
  7322. return token_type::parse_error;
  7323. }
  7324. case 0x0F:
  7325. {
  7326. error_message = "invalid string: control character U+000F (SI) must be escaped to \\u000F";
  7327. return token_type::parse_error;
  7328. }
  7329. case 0x10:
  7330. {
  7331. error_message = "invalid string: control character U+0010 (DLE) must be escaped to \\u0010";
  7332. return token_type::parse_error;
  7333. }
  7334. case 0x11:
  7335. {
  7336. error_message = "invalid string: control character U+0011 (DC1) must be escaped to \\u0011";
  7337. return token_type::parse_error;
  7338. }
  7339. case 0x12:
  7340. {
  7341. error_message = "invalid string: control character U+0012 (DC2) must be escaped to \\u0012";
  7342. return token_type::parse_error;
  7343. }
  7344. case 0x13:
  7345. {
  7346. error_message = "invalid string: control character U+0013 (DC3) must be escaped to \\u0013";
  7347. return token_type::parse_error;
  7348. }
  7349. case 0x14:
  7350. {
  7351. error_message = "invalid string: control character U+0014 (DC4) must be escaped to \\u0014";
  7352. return token_type::parse_error;
  7353. }
  7354. case 0x15:
  7355. {
  7356. error_message = "invalid string: control character U+0015 (NAK) must be escaped to \\u0015";
  7357. return token_type::parse_error;
  7358. }
  7359. case 0x16:
  7360. {
  7361. error_message = "invalid string: control character U+0016 (SYN) must be escaped to \\u0016";
  7362. return token_type::parse_error;
  7363. }
  7364. case 0x17:
  7365. {
  7366. error_message = "invalid string: control character U+0017 (ETB) must be escaped to \\u0017";
  7367. return token_type::parse_error;
  7368. }
  7369. case 0x18:
  7370. {
  7371. error_message = "invalid string: control character U+0018 (CAN) must be escaped to \\u0018";
  7372. return token_type::parse_error;
  7373. }
  7374. case 0x19:
  7375. {
  7376. error_message = "invalid string: control character U+0019 (EM) must be escaped to \\u0019";
  7377. return token_type::parse_error;
  7378. }
  7379. case 0x1A:
  7380. {
  7381. error_message = "invalid string: control character U+001A (SUB) must be escaped to \\u001A";
  7382. return token_type::parse_error;
  7383. }
  7384. case 0x1B:
  7385. {
  7386. error_message = "invalid string: control character U+001B (ESC) must be escaped to \\u001B";
  7387. return token_type::parse_error;
  7388. }
  7389. case 0x1C:
  7390. {
  7391. error_message = "invalid string: control character U+001C (FS) must be escaped to \\u001C";
  7392. return token_type::parse_error;
  7393. }
  7394. case 0x1D:
  7395. {
  7396. error_message = "invalid string: control character U+001D (GS) must be escaped to \\u001D";
  7397. return token_type::parse_error;
  7398. }
  7399. case 0x1E:
  7400. {
  7401. error_message = "invalid string: control character U+001E (RS) must be escaped to \\u001E";
  7402. return token_type::parse_error;
  7403. }
  7404. case 0x1F:
  7405. {
  7406. error_message = "invalid string: control character U+001F (US) must be escaped to \\u001F";
  7407. return token_type::parse_error;
  7408. }
  7409. // U+0020..U+007F (except U+0022 (quote) and U+005C (backspace))
  7410. case 0x20:
  7411. case 0x21:
  7412. case 0x23:
  7413. case 0x24:
  7414. case 0x25:
  7415. case 0x26:
  7416. case 0x27:
  7417. case 0x28:
  7418. case 0x29:
  7419. case 0x2A:
  7420. case 0x2B:
  7421. case 0x2C:
  7422. case 0x2D:
  7423. case 0x2E:
  7424. case 0x2F:
  7425. case 0x30:
  7426. case 0x31:
  7427. case 0x32:
  7428. case 0x33:
  7429. case 0x34:
  7430. case 0x35:
  7431. case 0x36:
  7432. case 0x37:
  7433. case 0x38:
  7434. case 0x39:
  7435. case 0x3A:
  7436. case 0x3B:
  7437. case 0x3C:
  7438. case 0x3D:
  7439. case 0x3E:
  7440. case 0x3F:
  7441. case 0x40:
  7442. case 0x41:
  7443. case 0x42:
  7444. case 0x43:
  7445. case 0x44:
  7446. case 0x45:
  7447. case 0x46:
  7448. case 0x47:
  7449. case 0x48:
  7450. case 0x49:
  7451. case 0x4A:
  7452. case 0x4B:
  7453. case 0x4C:
  7454. case 0x4D:
  7455. case 0x4E:
  7456. case 0x4F:
  7457. case 0x50:
  7458. case 0x51:
  7459. case 0x52:
  7460. case 0x53:
  7461. case 0x54:
  7462. case 0x55:
  7463. case 0x56:
  7464. case 0x57:
  7465. case 0x58:
  7466. case 0x59:
  7467. case 0x5A:
  7468. case 0x5B:
  7469. case 0x5D:
  7470. case 0x5E:
  7471. case 0x5F:
  7472. case 0x60:
  7473. case 0x61:
  7474. case 0x62:
  7475. case 0x63:
  7476. case 0x64:
  7477. case 0x65:
  7478. case 0x66:
  7479. case 0x67:
  7480. case 0x68:
  7481. case 0x69:
  7482. case 0x6A:
  7483. case 0x6B:
  7484. case 0x6C:
  7485. case 0x6D:
  7486. case 0x6E:
  7487. case 0x6F:
  7488. case 0x70:
  7489. case 0x71:
  7490. case 0x72:
  7491. case 0x73:
  7492. case 0x74:
  7493. case 0x75:
  7494. case 0x76:
  7495. case 0x77:
  7496. case 0x78:
  7497. case 0x79:
  7498. case 0x7A:
  7499. case 0x7B:
  7500. case 0x7C:
  7501. case 0x7D:
  7502. case 0x7E:
  7503. case 0x7F:
  7504. {
  7505. add(current);
  7506. break;
  7507. }
  7508. // U+0080..U+07FF: bytes C2..DF 80..BF
  7509. case 0xC2:
  7510. case 0xC3:
  7511. case 0xC4:
  7512. case 0xC5:
  7513. case 0xC6:
  7514. case 0xC7:
  7515. case 0xC8:
  7516. case 0xC9:
  7517. case 0xCA:
  7518. case 0xCB:
  7519. case 0xCC:
  7520. case 0xCD:
  7521. case 0xCE:
  7522. case 0xCF:
  7523. case 0xD0:
  7524. case 0xD1:
  7525. case 0xD2:
  7526. case 0xD3:
  7527. case 0xD4:
  7528. case 0xD5:
  7529. case 0xD6:
  7530. case 0xD7:
  7531. case 0xD8:
  7532. case 0xD9:
  7533. case 0xDA:
  7534. case 0xDB:
  7535. case 0xDC:
  7536. case 0xDD:
  7537. case 0xDE:
  7538. case 0xDF:
  7539. {
  7540. if (JSON_HEDLEY_UNLIKELY(not next_byte_in_range({0x80, 0xBF})))
  7541. {
  7542. return token_type::parse_error;
  7543. }
  7544. break;
  7545. }
  7546. // U+0800..U+0FFF: bytes E0 A0..BF 80..BF
  7547. case 0xE0:
  7548. {
  7549. if (JSON_HEDLEY_UNLIKELY(not (next_byte_in_range({0xA0, 0xBF, 0x80, 0xBF}))))
  7550. {
  7551. return token_type::parse_error;
  7552. }
  7553. break;
  7554. }
  7555. // U+1000..U+CFFF: bytes E1..EC 80..BF 80..BF
  7556. // U+E000..U+FFFF: bytes EE..EF 80..BF 80..BF
  7557. case 0xE1:
  7558. case 0xE2:
  7559. case 0xE3:
  7560. case 0xE4:
  7561. case 0xE5:
  7562. case 0xE6:
  7563. case 0xE7:
  7564. case 0xE8:
  7565. case 0xE9:
  7566. case 0xEA:
  7567. case 0xEB:
  7568. case 0xEC:
  7569. case 0xEE:
  7570. case 0xEF:
  7571. {
  7572. if (JSON_HEDLEY_UNLIKELY(not (next_byte_in_range({0x80, 0xBF, 0x80, 0xBF}))))
  7573. {
  7574. return token_type::parse_error;
  7575. }
  7576. break;
  7577. }
  7578. // U+D000..U+D7FF: bytes ED 80..9F 80..BF
  7579. case 0xED:
  7580. {
  7581. if (JSON_HEDLEY_UNLIKELY(not (next_byte_in_range({0x80, 0x9F, 0x80, 0xBF}))))
  7582. {
  7583. return token_type::parse_error;
  7584. }
  7585. break;
  7586. }
  7587. // U+10000..U+3FFFF F0 90..BF 80..BF 80..BF
  7588. case 0xF0:
  7589. {
  7590. if (JSON_HEDLEY_UNLIKELY(not (next_byte_in_range({0x90, 0xBF, 0x80, 0xBF, 0x80, 0xBF}))))
  7591. {
  7592. return token_type::parse_error;
  7593. }
  7594. break;
  7595. }
  7596. // U+40000..U+FFFFF F1..F3 80..BF 80..BF 80..BF
  7597. case 0xF1:
  7598. case 0xF2:
  7599. case 0xF3:
  7600. {
  7601. if (JSON_HEDLEY_UNLIKELY(not (next_byte_in_range({0x80, 0xBF, 0x80, 0xBF, 0x80, 0xBF}))))
  7602. {
  7603. return token_type::parse_error;
  7604. }
  7605. break;
  7606. }
  7607. // U+100000..U+10FFFF F4 80..8F 80..BF 80..BF
  7608. case 0xF4:
  7609. {
  7610. if (JSON_HEDLEY_UNLIKELY(not (next_byte_in_range({0x80, 0x8F, 0x80, 0xBF, 0x80, 0xBF}))))
  7611. {
  7612. return token_type::parse_error;
  7613. }
  7614. break;
  7615. }
  7616. // remaining bytes (80..C1 and F5..FF) are ill-formed
  7617. default:
  7618. {
  7619. error_message = "invalid string: ill-formed UTF-8 byte";
  7620. return token_type::parse_error;
  7621. }
  7622. }
  7623. }
  7624. }
  7625. JSON_HEDLEY_NON_NULL(2)
  7626. static void strtof(float& f, const char* str, char** endptr) noexcept
  7627. {
  7628. f = std::strtof(str, endptr);
  7629. }
  7630. JSON_HEDLEY_NON_NULL(2)
  7631. static void strtof(double& f, const char* str, char** endptr) noexcept
  7632. {
  7633. f = std::strtod(str, endptr);
  7634. }
  7635. JSON_HEDLEY_NON_NULL(2)
  7636. static void strtof(long double& f, const char* str, char** endptr) noexcept
  7637. {
  7638. f = std::strtold(str, endptr);
  7639. }
  7640. /*!
  7641. @brief scan a number literal
  7642. This function scans a string according to Sect. 6 of RFC 7159.
  7643. The function is realized with a deterministic finite state machine derived
  7644. from the grammar described in RFC 7159. Starting in state "init", the
  7645. input is read and used to determined the next state. Only state "done"
  7646. accepts the number. State "error" is a trap state to model errors. In the
  7647. table below, "anything" means any character but the ones listed before.
  7648. state | 0 | 1-9 | e E | + | - | . | anything
  7649. ---------|----------|----------|----------|---------|---------|----------|-----------
  7650. init | zero | any1 | [error] | [error] | minus | [error] | [error]
  7651. minus | zero | any1 | [error] | [error] | [error] | [error] | [error]
  7652. zero | done | done | exponent | done | done | decimal1 | done
  7653. any1 | any1 | any1 | exponent | done | done | decimal1 | done
  7654. decimal1 | decimal2 | decimal2 | [error] | [error] | [error] | [error] | [error]
  7655. decimal2 | decimal2 | decimal2 | exponent | done | done | done | done
  7656. exponent | any2 | any2 | [error] | sign | sign | [error] | [error]
  7657. sign | any2 | any2 | [error] | [error] | [error] | [error] | [error]
  7658. any2 | any2 | any2 | done | done | done | done | done
  7659. The state machine is realized with one label per state (prefixed with
  7660. "scan_number_") and `goto` statements between them. The state machine
  7661. contains cycles, but any cycle can be left when EOF is read. Therefore,
  7662. the function is guaranteed to terminate.
  7663. During scanning, the read bytes are stored in token_buffer. This string is
  7664. then converted to a signed integer, an unsigned integer, or a
  7665. floating-point number.
  7666. @return token_type::value_unsigned, token_type::value_integer, or
  7667. token_type::value_float if number could be successfully scanned,
  7668. token_type::parse_error otherwise
  7669. @note The scanner is independent of the current locale. Internally, the
  7670. locale's decimal point is used instead of `.` to work with the
  7671. locale-dependent converters.
  7672. */
  7673. token_type scan_number() // lgtm [cpp/use-of-goto]
  7674. {
  7675. // reset token_buffer to store the number's bytes
  7676. reset();
  7677. // the type of the parsed number; initially set to unsigned; will be
  7678. // changed if minus sign, decimal point or exponent is read
  7679. token_type number_type = token_type::value_unsigned;
  7680. // state (init): we just found out we need to scan a number
  7681. switch (current)
  7682. {
  7683. case '-':
  7684. {
  7685. add(current);
  7686. goto scan_number_minus;
  7687. }
  7688. case '0':
  7689. {
  7690. add(current);
  7691. goto scan_number_zero;
  7692. }
  7693. case '1':
  7694. case '2':
  7695. case '3':
  7696. case '4':
  7697. case '5':
  7698. case '6':
  7699. case '7':
  7700. case '8':
  7701. case '9':
  7702. {
  7703. add(current);
  7704. goto scan_number_any1;
  7705. }
  7706. // all other characters are rejected outside scan_number()
  7707. default: // LCOV_EXCL_LINE
  7708. assert(false); // LCOV_EXCL_LINE
  7709. }
  7710. scan_number_minus:
  7711. // state: we just parsed a leading minus sign
  7712. number_type = token_type::value_integer;
  7713. switch (get())
  7714. {
  7715. case '0':
  7716. {
  7717. add(current);
  7718. goto scan_number_zero;
  7719. }
  7720. case '1':
  7721. case '2':
  7722. case '3':
  7723. case '4':
  7724. case '5':
  7725. case '6':
  7726. case '7':
  7727. case '8':
  7728. case '9':
  7729. {
  7730. add(current);
  7731. goto scan_number_any1;
  7732. }
  7733. default:
  7734. {
  7735. error_message = "invalid number; expected digit after '-'";
  7736. return token_type::parse_error;
  7737. }
  7738. }
  7739. scan_number_zero:
  7740. // state: we just parse a zero (maybe with a leading minus sign)
  7741. switch (get())
  7742. {
  7743. case '.':
  7744. {
  7745. add(decimal_point_char);
  7746. goto scan_number_decimal1;
  7747. }
  7748. case 'e':
  7749. case 'E':
  7750. {
  7751. add(current);
  7752. goto scan_number_exponent;
  7753. }
  7754. default:
  7755. goto scan_number_done;
  7756. }
  7757. scan_number_any1:
  7758. // state: we just parsed a number 0-9 (maybe with a leading minus sign)
  7759. switch (get())
  7760. {
  7761. case '0':
  7762. case '1':
  7763. case '2':
  7764. case '3':
  7765. case '4':
  7766. case '5':
  7767. case '6':
  7768. case '7':
  7769. case '8':
  7770. case '9':
  7771. {
  7772. add(current);
  7773. goto scan_number_any1;
  7774. }
  7775. case '.':
  7776. {
  7777. add(decimal_point_char);
  7778. goto scan_number_decimal1;
  7779. }
  7780. case 'e':
  7781. case 'E':
  7782. {
  7783. add(current);
  7784. goto scan_number_exponent;
  7785. }
  7786. default:
  7787. goto scan_number_done;
  7788. }
  7789. scan_number_decimal1:
  7790. // state: we just parsed a decimal point
  7791. number_type = token_type::value_float;
  7792. switch (get())
  7793. {
  7794. case '0':
  7795. case '1':
  7796. case '2':
  7797. case '3':
  7798. case '4':
  7799. case '5':
  7800. case '6':
  7801. case '7':
  7802. case '8':
  7803. case '9':
  7804. {
  7805. add(current);
  7806. goto scan_number_decimal2;
  7807. }
  7808. default:
  7809. {
  7810. error_message = "invalid number; expected digit after '.'";
  7811. return token_type::parse_error;
  7812. }
  7813. }
  7814. scan_number_decimal2:
  7815. // we just parsed at least one number after a decimal point
  7816. switch (get())
  7817. {
  7818. case '0':
  7819. case '1':
  7820. case '2':
  7821. case '3':
  7822. case '4':
  7823. case '5':
  7824. case '6':
  7825. case '7':
  7826. case '8':
  7827. case '9':
  7828. {
  7829. add(current);
  7830. goto scan_number_decimal2;
  7831. }
  7832. case 'e':
  7833. case 'E':
  7834. {
  7835. add(current);
  7836. goto scan_number_exponent;
  7837. }
  7838. default:
  7839. goto scan_number_done;
  7840. }
  7841. scan_number_exponent:
  7842. // we just parsed an exponent
  7843. number_type = token_type::value_float;
  7844. switch (get())
  7845. {
  7846. case '+':
  7847. case '-':
  7848. {
  7849. add(current);
  7850. goto scan_number_sign;
  7851. }
  7852. case '0':
  7853. case '1':
  7854. case '2':
  7855. case '3':
  7856. case '4':
  7857. case '5':
  7858. case '6':
  7859. case '7':
  7860. case '8':
  7861. case '9':
  7862. {
  7863. add(current);
  7864. goto scan_number_any2;
  7865. }
  7866. default:
  7867. {
  7868. error_message =
  7869. "invalid number; expected '+', '-', or digit after exponent";
  7870. return token_type::parse_error;
  7871. }
  7872. }
  7873. scan_number_sign:
  7874. // we just parsed an exponent sign
  7875. switch (get())
  7876. {
  7877. case '0':
  7878. case '1':
  7879. case '2':
  7880. case '3':
  7881. case '4':
  7882. case '5':
  7883. case '6':
  7884. case '7':
  7885. case '8':
  7886. case '9':
  7887. {
  7888. add(current);
  7889. goto scan_number_any2;
  7890. }
  7891. default:
  7892. {
  7893. error_message = "invalid number; expected digit after exponent sign";
  7894. return token_type::parse_error;
  7895. }
  7896. }
  7897. scan_number_any2:
  7898. // we just parsed a number after the exponent or exponent sign
  7899. switch (get())
  7900. {
  7901. case '0':
  7902. case '1':
  7903. case '2':
  7904. case '3':
  7905. case '4':
  7906. case '5':
  7907. case '6':
  7908. case '7':
  7909. case '8':
  7910. case '9':
  7911. {
  7912. add(current);
  7913. goto scan_number_any2;
  7914. }
  7915. default:
  7916. goto scan_number_done;
  7917. }
  7918. scan_number_done:
  7919. // unget the character after the number (we only read it to know that
  7920. // we are done scanning a number)
  7921. unget();
  7922. char* endptr = nullptr;
  7923. errno = 0;
  7924. // try to parse integers first and fall back to floats
  7925. if (number_type == token_type::value_unsigned)
  7926. {
  7927. const auto x = std::strtoull(token_buffer.data(), &endptr, 10);
  7928. // we checked the number format before
  7929. assert(endptr == token_buffer.data() + token_buffer.size());
  7930. if (errno == 0)
  7931. {
  7932. value_unsigned = static_cast<number_unsigned_t>(x);
  7933. if (value_unsigned == x)
  7934. {
  7935. return token_type::value_unsigned;
  7936. }
  7937. }
  7938. }
  7939. else if (number_type == token_type::value_integer)
  7940. {
  7941. const auto x = std::strtoll(token_buffer.data(), &endptr, 10);
  7942. // we checked the number format before
  7943. assert(endptr == token_buffer.data() + token_buffer.size());
  7944. if (errno == 0)
  7945. {
  7946. value_integer = static_cast<number_integer_t>(x);
  7947. if (value_integer == x)
  7948. {
  7949. return token_type::value_integer;
  7950. }
  7951. }
  7952. }
  7953. // this code is reached if we parse a floating-point number or if an
  7954. // integer conversion above failed
  7955. strtof(value_float, token_buffer.data(), &endptr);
  7956. // we checked the number format before
  7957. assert(endptr == token_buffer.data() + token_buffer.size());
  7958. return token_type::value_float;
  7959. }
  7960. /*!
  7961. @param[in] literal_text the literal text to expect
  7962. @param[in] length the length of the passed literal text
  7963. @param[in] return_type the token type to return on success
  7964. */
  7965. JSON_HEDLEY_NON_NULL(2)
  7966. token_type scan_literal(const char* literal_text, const std::size_t length,
  7967. token_type return_type)
  7968. {
  7969. assert(current == literal_text[0]);
  7970. for (std::size_t i = 1; i < length; ++i)
  7971. {
  7972. if (JSON_HEDLEY_UNLIKELY(get() != literal_text[i]))
  7973. {
  7974. error_message = "invalid literal";
  7975. return token_type::parse_error;
  7976. }
  7977. }
  7978. return return_type;
  7979. }
  7980. /////////////////////
  7981. // input management
  7982. /////////////////////
  7983. /// reset token_buffer; current character is beginning of token
  7984. void reset() noexcept
  7985. {
  7986. token_buffer.clear();
  7987. token_string.clear();
  7988. token_string.push_back(std::char_traits<char>::to_char_type(current));
  7989. }
  7990. /*
  7991. @brief get next character from the input
  7992. This function provides the interface to the used input adapter. It does
  7993. not throw in case the input reached EOF, but returns a
  7994. `std::char_traits<char>::eof()` in that case. Stores the scanned characters
  7995. for use in error messages.
  7996. @return character read from the input
  7997. */
  7998. std::char_traits<char>::int_type get()
  7999. {
  8000. ++position.chars_read_total;
  8001. ++position.chars_read_current_line;
  8002. if (next_unget)
  8003. {
  8004. // just reset the next_unget variable and work with current
  8005. next_unget = false;
  8006. }
  8007. else
  8008. {
  8009. current = ia->get_character();
  8010. }
  8011. if (JSON_HEDLEY_LIKELY(current != std::char_traits<char>::eof()))
  8012. {
  8013. token_string.push_back(std::char_traits<char>::to_char_type(current));
  8014. }
  8015. if (current == '\n')
  8016. {
  8017. ++position.lines_read;
  8018. position.chars_read_current_line = 0;
  8019. }
  8020. return current;
  8021. }
  8022. /*!
  8023. @brief unget current character (read it again on next get)
  8024. We implement unget by setting variable next_unget to true. The input is not
  8025. changed - we just simulate ungetting by modifying chars_read_total,
  8026. chars_read_current_line, and token_string. The next call to get() will
  8027. behave as if the unget character is read again.
  8028. */
  8029. void unget()
  8030. {
  8031. next_unget = true;
  8032. --position.chars_read_total;
  8033. // in case we "unget" a newline, we have to also decrement the lines_read
  8034. if (position.chars_read_current_line == 0)
  8035. {
  8036. if (position.lines_read > 0)
  8037. {
  8038. --position.lines_read;
  8039. }
  8040. }
  8041. else
  8042. {
  8043. --position.chars_read_current_line;
  8044. }
  8045. if (JSON_HEDLEY_LIKELY(current != std::char_traits<char>::eof()))
  8046. {
  8047. assert(not token_string.empty());
  8048. token_string.pop_back();
  8049. }
  8050. }
  8051. /// add a character to token_buffer
  8052. void add(int c)
  8053. {
  8054. token_buffer.push_back(std::char_traits<char>::to_char_type(c));
  8055. }
  8056. public:
  8057. /////////////////////
  8058. // value getters
  8059. /////////////////////
  8060. /// return integer value
  8061. constexpr number_integer_t get_number_integer() const noexcept
  8062. {
  8063. return value_integer;
  8064. }
  8065. /// return unsigned integer value
  8066. constexpr number_unsigned_t get_number_unsigned() const noexcept
  8067. {
  8068. return value_unsigned;
  8069. }
  8070. /// return floating-point value
  8071. constexpr number_float_t get_number_float() const noexcept
  8072. {
  8073. return value_float;
  8074. }
  8075. /// return current string value (implicitly resets the token; useful only once)
  8076. string_t& get_string()
  8077. {
  8078. return token_buffer;
  8079. }
  8080. /////////////////////
  8081. // diagnostics
  8082. /////////////////////
  8083. /// return position of last read token
  8084. constexpr position_t get_position() const noexcept
  8085. {
  8086. return position;
  8087. }
  8088. /// return the last read token (for errors only). Will never contain EOF
  8089. /// (an arbitrary value that is not a valid char value, often -1), because
  8090. /// 255 may legitimately occur. May contain NUL, which should be escaped.
  8091. std::string get_token_string() const
  8092. {
  8093. // escape control characters
  8094. std::string result;
  8095. for (const auto c : token_string)
  8096. {
  8097. if ('\x00' <= c and c <= '\x1F')
  8098. {
  8099. // escape control characters
  8100. std::array<char, 9> cs{{}};
  8101. (std::snprintf)(cs.data(), cs.size(), "<U+%.4X>", static_cast<unsigned char>(c));
  8102. result += cs.data();
  8103. }
  8104. else
  8105. {
  8106. // add character as is
  8107. result.push_back(c);
  8108. }
  8109. }
  8110. return result;
  8111. }
  8112. /// return syntax error message
  8113. JSON_HEDLEY_RETURNS_NON_NULL
  8114. constexpr const char* get_error_message() const noexcept
  8115. {
  8116. return error_message;
  8117. }
  8118. /////////////////////
  8119. // actual scanner
  8120. /////////////////////
  8121. /*!
  8122. @brief skip the UTF-8 byte order mark
  8123. @return true iff there is no BOM or the correct BOM has been skipped
  8124. */
  8125. bool skip_bom()
  8126. {
  8127. if (get() == 0xEF)
  8128. {
  8129. // check if we completely parse the BOM
  8130. return get() == 0xBB and get() == 0xBF;
  8131. }
  8132. // the first character is not the beginning of the BOM; unget it to
  8133. // process is later
  8134. unget();
  8135. return true;
  8136. }
  8137. token_type scan()
  8138. {
  8139. // initially, skip the BOM
  8140. if (position.chars_read_total == 0 and not skip_bom())
  8141. {
  8142. error_message = "invalid BOM; must be 0xEF 0xBB 0xBF if given";
  8143. return token_type::parse_error;
  8144. }
  8145. // read next character and ignore whitespace
  8146. do
  8147. {
  8148. get();
  8149. }
  8150. while (current == ' ' or current == '\t' or current == '\n' or current == '\r');
  8151. switch (current)
  8152. {
  8153. // structural characters
  8154. case '[':
  8155. return token_type::begin_array;
  8156. case ']':
  8157. return token_type::end_array;
  8158. case '{':
  8159. return token_type::begin_object;
  8160. case '}':
  8161. return token_type::end_object;
  8162. case ':':
  8163. return token_type::name_separator;
  8164. case ',':
  8165. return token_type::value_separator;
  8166. // literals
  8167. case 't':
  8168. return scan_literal("true", 4, token_type::literal_true);
  8169. case 'f':
  8170. return scan_literal("false", 5, token_type::literal_false);
  8171. case 'n':
  8172. return scan_literal("null", 4, token_type::literal_null);
  8173. // string
  8174. case '\"':
  8175. return scan_string();
  8176. // number
  8177. case '-':
  8178. case '0':
  8179. case '1':
  8180. case '2':
  8181. case '3':
  8182. case '4':
  8183. case '5':
  8184. case '6':
  8185. case '7':
  8186. case '8':
  8187. case '9':
  8188. return scan_number();
  8189. // end of input (the null byte is needed when parsing from
  8190. // string literals)
  8191. case '\0':
  8192. case std::char_traits<char>::eof():
  8193. return token_type::end_of_input;
  8194. // error
  8195. default:
  8196. error_message = "invalid literal";
  8197. return token_type::parse_error;
  8198. }
  8199. }
  8200. private:
  8201. /// input adapter
  8202. detail::input_adapter_t ia = nullptr;
  8203. /// the current character
  8204. std::char_traits<char>::int_type current = std::char_traits<char>::eof();
  8205. /// whether the next get() call should just return current
  8206. bool next_unget = false;
  8207. /// the start position of the current token
  8208. position_t position {};
  8209. /// raw input token string (for error messages)
  8210. std::vector<char> token_string {};
  8211. /// buffer for variable-length tokens (numbers, strings)
  8212. string_t token_buffer {};
  8213. /// a description of occurred lexer errors
  8214. const char* error_message = "";
  8215. // number values
  8216. number_integer_t value_integer = 0;
  8217. number_unsigned_t value_unsigned = 0;
  8218. number_float_t value_float = 0;
  8219. /// the decimal point
  8220. const char decimal_point_char = '.';
  8221. };
  8222. } // namespace detail
  8223. } // namespace nlohmann
  8224. // #include <nlohmann/detail/input/parser.hpp>
  8225. #include <cassert> // assert
  8226. #include <cmath> // isfinite
  8227. #include <cstdint> // uint8_t
  8228. #include <functional> // function
  8229. #include <string> // string
  8230. #include <utility> // move
  8231. #include <vector> // vector
  8232. // #include <nlohmann/detail/exceptions.hpp>
  8233. // #include <nlohmann/detail/input/input_adapters.hpp>
  8234. // #include <nlohmann/detail/input/json_sax.hpp>
  8235. // #include <nlohmann/detail/input/lexer.hpp>
  8236. // #include <nlohmann/detail/macro_scope.hpp>
  8237. // #include <nlohmann/detail/meta/is_sax.hpp>
  8238. // #include <nlohmann/detail/value_t.hpp>
  8239. namespace nlohmann
  8240. {
  8241. namespace detail
  8242. {
  8243. ////////////
  8244. // parser //
  8245. ////////////
  8246. /*!
  8247. @brief syntax analysis
  8248. This class implements a recursive descent parser.
  8249. */
  8250. template<typename BasicJsonType>
  8251. class parser
  8252. {
  8253. using number_integer_t = typename BasicJsonType::number_integer_t;
  8254. using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
  8255. using number_float_t = typename BasicJsonType::number_float_t;
  8256. using string_t = typename BasicJsonType::string_t;
  8257. using lexer_t = lexer<BasicJsonType>;
  8258. using token_type = typename lexer_t::token_type;
  8259. public:
  8260. enum class parse_event_t : uint8_t
  8261. {
  8262. /// the parser read `{` and started to process a JSON object
  8263. object_start,
  8264. /// the parser read `}` and finished processing a JSON object
  8265. object_end,
  8266. /// the parser read `[` and started to process a JSON array
  8267. array_start,
  8268. /// the parser read `]` and finished processing a JSON array
  8269. array_end,
  8270. /// the parser read a key of a value in an object
  8271. key,
  8272. /// the parser finished reading a JSON value
  8273. value
  8274. };
  8275. using parser_callback_t =
  8276. std::function<bool(int depth, parse_event_t event, BasicJsonType& parsed)>;
  8277. /// a parser reading from an input adapter
  8278. explicit parser(detail::input_adapter_t&& adapter,
  8279. const parser_callback_t cb = nullptr,
  8280. const bool allow_exceptions_ = true)
  8281. : callback(cb), m_lexer(std::move(adapter)), allow_exceptions(allow_exceptions_)
  8282. {
  8283. // read first token
  8284. get_token();
  8285. }
  8286. /*!
  8287. @brief public parser interface
  8288. @param[in] strict whether to expect the last token to be EOF
  8289. @param[in,out] result parsed JSON value
  8290. @throw parse_error.101 in case of an unexpected token
  8291. @throw parse_error.102 if to_unicode fails or surrogate error
  8292. @throw parse_error.103 if to_unicode fails
  8293. */
  8294. void parse(const bool strict, BasicJsonType& result)
  8295. {
  8296. if (callback)
  8297. {
  8298. json_sax_dom_callback_parser<BasicJsonType> sdp(result, callback, allow_exceptions);
  8299. sax_parse_internal(&sdp);
  8300. result.assert_invariant();
  8301. // in strict mode, input must be completely read
  8302. if (strict and (get_token() != token_type::end_of_input))
  8303. {
  8304. sdp.parse_error(m_lexer.get_position(),
  8305. m_lexer.get_token_string(),
  8306. parse_error::create(101, m_lexer.get_position(),
  8307. exception_message(token_type::end_of_input, "value")));
  8308. }
  8309. // in case of an error, return discarded value
  8310. if (sdp.is_errored())
  8311. {
  8312. result = value_t::discarded;
  8313. return;
  8314. }
  8315. // set top-level value to null if it was discarded by the callback
  8316. // function
  8317. if (result.is_discarded())
  8318. {
  8319. result = nullptr;
  8320. }
  8321. }
  8322. else
  8323. {
  8324. json_sax_dom_parser<BasicJsonType> sdp(result, allow_exceptions);
  8325. sax_parse_internal(&sdp);
  8326. result.assert_invariant();
  8327. // in strict mode, input must be completely read
  8328. if (strict and (get_token() != token_type::end_of_input))
  8329. {
  8330. sdp.parse_error(m_lexer.get_position(),
  8331. m_lexer.get_token_string(),
  8332. parse_error::create(101, m_lexer.get_position(),
  8333. exception_message(token_type::end_of_input, "value")));
  8334. }
  8335. // in case of an error, return discarded value
  8336. if (sdp.is_errored())
  8337. {
  8338. result = value_t::discarded;
  8339. return;
  8340. }
  8341. }
  8342. }
  8343. /*!
  8344. @brief public accept interface
  8345. @param[in] strict whether to expect the last token to be EOF
  8346. @return whether the input is a proper JSON text
  8347. */
  8348. bool accept(const bool strict = true)
  8349. {
  8350. json_sax_acceptor<BasicJsonType> sax_acceptor;
  8351. return sax_parse(&sax_acceptor, strict);
  8352. }
  8353. template <typename SAX>
  8354. JSON_HEDLEY_NON_NULL(2)
  8355. bool sax_parse(SAX* sax, const bool strict = true)
  8356. {
  8357. (void)detail::is_sax_static_asserts<SAX, BasicJsonType> {};
  8358. const bool result = sax_parse_internal(sax);
  8359. // strict mode: next byte must be EOF
  8360. if (result and strict and (get_token() != token_type::end_of_input))
  8361. {
  8362. return sax->parse_error(m_lexer.get_position(),
  8363. m_lexer.get_token_string(),
  8364. parse_error::create(101, m_lexer.get_position(),
  8365. exception_message(token_type::end_of_input, "value")));
  8366. }
  8367. return result;
  8368. }
  8369. private:
  8370. template <typename SAX>
  8371. JSON_HEDLEY_NON_NULL(2)
  8372. bool sax_parse_internal(SAX* sax)
  8373. {
  8374. // stack to remember the hierarchy of structured values we are parsing
  8375. // true = array; false = object
  8376. std::vector<bool> states;
  8377. // value to avoid a goto (see comment where set to true)
  8378. bool skip_to_state_evaluation = false;
  8379. while (true)
  8380. {
  8381. if (not skip_to_state_evaluation)
  8382. {
  8383. // invariant: get_token() was called before each iteration
  8384. switch (last_token)
  8385. {
  8386. case token_type::begin_object:
  8387. {
  8388. if (JSON_HEDLEY_UNLIKELY(not sax->start_object(std::size_t(-1))))
  8389. {
  8390. return false;
  8391. }
  8392. // closing } -> we are done
  8393. if (get_token() == token_type::end_object)
  8394. {
  8395. if (JSON_HEDLEY_UNLIKELY(not sax->end_object()))
  8396. {
  8397. return false;
  8398. }
  8399. break;
  8400. }
  8401. // parse key
  8402. if (JSON_HEDLEY_UNLIKELY(last_token != token_type::value_string))
  8403. {
  8404. return sax->parse_error(m_lexer.get_position(),
  8405. m_lexer.get_token_string(),
  8406. parse_error::create(101, m_lexer.get_position(),
  8407. exception_message(token_type::value_string, "object key")));
  8408. }
  8409. if (JSON_HEDLEY_UNLIKELY(not sax->key(m_lexer.get_string())))
  8410. {
  8411. return false;
  8412. }
  8413. // parse separator (:)
  8414. if (JSON_HEDLEY_UNLIKELY(get_token() != token_type::name_separator))
  8415. {
  8416. return sax->parse_error(m_lexer.get_position(),
  8417. m_lexer.get_token_string(),
  8418. parse_error::create(101, m_lexer.get_position(),
  8419. exception_message(token_type::name_separator, "object separator")));
  8420. }
  8421. // remember we are now inside an object
  8422. states.push_back(false);
  8423. // parse values
  8424. get_token();
  8425. continue;
  8426. }
  8427. case token_type::begin_array:
  8428. {
  8429. if (JSON_HEDLEY_UNLIKELY(not sax->start_array(std::size_t(-1))))
  8430. {
  8431. return false;
  8432. }
  8433. // closing ] -> we are done
  8434. if (get_token() == token_type::end_array)
  8435. {
  8436. if (JSON_HEDLEY_UNLIKELY(not sax->end_array()))
  8437. {
  8438. return false;
  8439. }
  8440. break;
  8441. }
  8442. // remember we are now inside an array
  8443. states.push_back(true);
  8444. // parse values (no need to call get_token)
  8445. continue;
  8446. }
  8447. case token_type::value_float:
  8448. {
  8449. const auto res = m_lexer.get_number_float();
  8450. if (JSON_HEDLEY_UNLIKELY(not std::isfinite(res)))
  8451. {
  8452. return sax->parse_error(m_lexer.get_position(),
  8453. m_lexer.get_token_string(),
  8454. out_of_range::create(406, "number overflow parsing '" + m_lexer.get_token_string() + "'"));
  8455. }
  8456. if (JSON_HEDLEY_UNLIKELY(not sax->number_float(res, m_lexer.get_string())))
  8457. {
  8458. return false;
  8459. }
  8460. break;
  8461. }
  8462. case token_type::literal_false:
  8463. {
  8464. if (JSON_HEDLEY_UNLIKELY(not sax->boolean(false)))
  8465. {
  8466. return false;
  8467. }
  8468. break;
  8469. }
  8470. case token_type::literal_null:
  8471. {
  8472. if (JSON_HEDLEY_UNLIKELY(not sax->null()))
  8473. {
  8474. return false;
  8475. }
  8476. break;
  8477. }
  8478. case token_type::literal_true:
  8479. {
  8480. if (JSON_HEDLEY_UNLIKELY(not sax->boolean(true)))
  8481. {
  8482. return false;
  8483. }
  8484. break;
  8485. }
  8486. case token_type::value_integer:
  8487. {
  8488. if (JSON_HEDLEY_UNLIKELY(not sax->number_integer(m_lexer.get_number_integer())))
  8489. {
  8490. return false;
  8491. }
  8492. break;
  8493. }
  8494. case token_type::value_string:
  8495. {
  8496. if (JSON_HEDLEY_UNLIKELY(not sax->string(m_lexer.get_string())))
  8497. {
  8498. return false;
  8499. }
  8500. break;
  8501. }
  8502. case token_type::value_unsigned:
  8503. {
  8504. if (JSON_HEDLEY_UNLIKELY(not sax->number_unsigned(m_lexer.get_number_unsigned())))
  8505. {
  8506. return false;
  8507. }
  8508. break;
  8509. }
  8510. case token_type::parse_error:
  8511. {
  8512. // using "uninitialized" to avoid "expected" message
  8513. return sax->parse_error(m_lexer.get_position(),
  8514. m_lexer.get_token_string(),
  8515. parse_error::create(101, m_lexer.get_position(),
  8516. exception_message(token_type::uninitialized, "value")));
  8517. }
  8518. default: // the last token was unexpected
  8519. {
  8520. return sax->parse_error(m_lexer.get_position(),
  8521. m_lexer.get_token_string(),
  8522. parse_error::create(101, m_lexer.get_position(),
  8523. exception_message(token_type::literal_or_value, "value")));
  8524. }
  8525. }
  8526. }
  8527. else
  8528. {
  8529. skip_to_state_evaluation = false;
  8530. }
  8531. // we reached this line after we successfully parsed a value
  8532. if (states.empty())
  8533. {
  8534. // empty stack: we reached the end of the hierarchy: done
  8535. return true;
  8536. }
  8537. if (states.back()) // array
  8538. {
  8539. // comma -> next value
  8540. if (get_token() == token_type::value_separator)
  8541. {
  8542. // parse a new value
  8543. get_token();
  8544. continue;
  8545. }
  8546. // closing ]
  8547. if (JSON_HEDLEY_LIKELY(last_token == token_type::end_array))
  8548. {
  8549. if (JSON_HEDLEY_UNLIKELY(not sax->end_array()))
  8550. {
  8551. return false;
  8552. }
  8553. // We are done with this array. Before we can parse a
  8554. // new value, we need to evaluate the new state first.
  8555. // By setting skip_to_state_evaluation to false, we
  8556. // are effectively jumping to the beginning of this if.
  8557. assert(not states.empty());
  8558. states.pop_back();
  8559. skip_to_state_evaluation = true;
  8560. continue;
  8561. }
  8562. return sax->parse_error(m_lexer.get_position(),
  8563. m_lexer.get_token_string(),
  8564. parse_error::create(101, m_lexer.get_position(),
  8565. exception_message(token_type::end_array, "array")));
  8566. }
  8567. else // object
  8568. {
  8569. // comma -> next value
  8570. if (get_token() == token_type::value_separator)
  8571. {
  8572. // parse key
  8573. if (JSON_HEDLEY_UNLIKELY(get_token() != token_type::value_string))
  8574. {
  8575. return sax->parse_error(m_lexer.get_position(),
  8576. m_lexer.get_token_string(),
  8577. parse_error::create(101, m_lexer.get_position(),
  8578. exception_message(token_type::value_string, "object key")));
  8579. }
  8580. if (JSON_HEDLEY_UNLIKELY(not sax->key(m_lexer.get_string())))
  8581. {
  8582. return false;
  8583. }
  8584. // parse separator (:)
  8585. if (JSON_HEDLEY_UNLIKELY(get_token() != token_type::name_separator))
  8586. {
  8587. return sax->parse_error(m_lexer.get_position(),
  8588. m_lexer.get_token_string(),
  8589. parse_error::create(101, m_lexer.get_position(),
  8590. exception_message(token_type::name_separator, "object separator")));
  8591. }
  8592. // parse values
  8593. get_token();
  8594. continue;
  8595. }
  8596. // closing }
  8597. if (JSON_HEDLEY_LIKELY(last_token == token_type::end_object))
  8598. {
  8599. if (JSON_HEDLEY_UNLIKELY(not sax->end_object()))
  8600. {
  8601. return false;
  8602. }
  8603. // We are done with this object. Before we can parse a
  8604. // new value, we need to evaluate the new state first.
  8605. // By setting skip_to_state_evaluation to false, we
  8606. // are effectively jumping to the beginning of this if.
  8607. assert(not states.empty());
  8608. states.pop_back();
  8609. skip_to_state_evaluation = true;
  8610. continue;
  8611. }
  8612. return sax->parse_error(m_lexer.get_position(),
  8613. m_lexer.get_token_string(),
  8614. parse_error::create(101, m_lexer.get_position(),
  8615. exception_message(token_type::end_object, "object")));
  8616. }
  8617. }
  8618. }
  8619. /// get next token from lexer
  8620. token_type get_token()
  8621. {
  8622. return last_token = m_lexer.scan();
  8623. }
  8624. std::string exception_message(const token_type expected, const std::string& context)
  8625. {
  8626. std::string error_msg = "syntax error ";
  8627. if (not context.empty())
  8628. {
  8629. error_msg += "while parsing " + context + " ";
  8630. }
  8631. error_msg += "- ";
  8632. if (last_token == token_type::parse_error)
  8633. {
  8634. error_msg += std::string(m_lexer.get_error_message()) + "; last read: '" +
  8635. m_lexer.get_token_string() + "'";
  8636. }
  8637. else
  8638. {
  8639. error_msg += "unexpected " + std::string(lexer_t::token_type_name(last_token));
  8640. }
  8641. if (expected != token_type::uninitialized)
  8642. {
  8643. error_msg += "; expected " + std::string(lexer_t::token_type_name(expected));
  8644. }
  8645. return error_msg;
  8646. }
  8647. private:
  8648. /// callback function
  8649. const parser_callback_t callback = nullptr;
  8650. /// the type of the last read token
  8651. token_type last_token = token_type::uninitialized;
  8652. /// the lexer
  8653. lexer_t m_lexer;
  8654. /// whether to throw exceptions in case of errors
  8655. const bool allow_exceptions = true;
  8656. };
  8657. } // namespace detail
  8658. } // namespace nlohmann
  8659. // #include <nlohmann/detail/iterators/internal_iterator.hpp>
  8660. // #include <nlohmann/detail/iterators/primitive_iterator.hpp>
  8661. #include <cstddef> // ptrdiff_t
  8662. #include <limits> // numeric_limits
  8663. namespace nlohmann
  8664. {
  8665. namespace detail
  8666. {
  8667. /*
  8668. @brief an iterator for primitive JSON types
  8669. This class models an iterator for primitive JSON types (boolean, number,
  8670. string). It's only purpose is to allow the iterator/const_iterator classes
  8671. to "iterate" over primitive values. Internally, the iterator is modeled by
  8672. a `difference_type` variable. Value begin_value (`0`) models the begin,
  8673. end_value (`1`) models past the end.
  8674. */
  8675. class primitive_iterator_t
  8676. {
  8677. private:
  8678. using difference_type = std::ptrdiff_t;
  8679. static constexpr difference_type begin_value = 0;
  8680. static constexpr difference_type end_value = begin_value + 1;
  8681. /// iterator as signed integer type
  8682. difference_type m_it = (std::numeric_limits<std::ptrdiff_t>::min)();
  8683. public:
  8684. constexpr difference_type get_value() const noexcept
  8685. {
  8686. return m_it;
  8687. }
  8688. /// set iterator to a defined beginning
  8689. void set_begin() noexcept
  8690. {
  8691. m_it = begin_value;
  8692. }
  8693. /// set iterator to a defined past the end
  8694. void set_end() noexcept
  8695. {
  8696. m_it = end_value;
  8697. }
  8698. /// return whether the iterator can be dereferenced
  8699. constexpr bool is_begin() const noexcept
  8700. {
  8701. return m_it == begin_value;
  8702. }
  8703. /// return whether the iterator is at end
  8704. constexpr bool is_end() const noexcept
  8705. {
  8706. return m_it == end_value;
  8707. }
  8708. friend constexpr bool operator==(primitive_iterator_t lhs, primitive_iterator_t rhs) noexcept
  8709. {
  8710. return lhs.m_it == rhs.m_it;
  8711. }
  8712. friend constexpr bool operator<(primitive_iterator_t lhs, primitive_iterator_t rhs) noexcept
  8713. {
  8714. return lhs.m_it < rhs.m_it;
  8715. }
  8716. primitive_iterator_t operator+(difference_type n) noexcept
  8717. {
  8718. auto result = *this;
  8719. result += n;
  8720. return result;
  8721. }
  8722. friend constexpr difference_type operator-(primitive_iterator_t lhs, primitive_iterator_t rhs) noexcept
  8723. {
  8724. return lhs.m_it - rhs.m_it;
  8725. }
  8726. primitive_iterator_t& operator++() noexcept
  8727. {
  8728. ++m_it;
  8729. return *this;
  8730. }
  8731. primitive_iterator_t const operator++(int) noexcept
  8732. {
  8733. auto result = *this;
  8734. ++m_it;
  8735. return result;
  8736. }
  8737. primitive_iterator_t& operator--() noexcept
  8738. {
  8739. --m_it;
  8740. return *this;
  8741. }
  8742. primitive_iterator_t const operator--(int) noexcept
  8743. {
  8744. auto result = *this;
  8745. --m_it;
  8746. return result;
  8747. }
  8748. primitive_iterator_t& operator+=(difference_type n) noexcept
  8749. {
  8750. m_it += n;
  8751. return *this;
  8752. }
  8753. primitive_iterator_t& operator-=(difference_type n) noexcept
  8754. {
  8755. m_it -= n;
  8756. return *this;
  8757. }
  8758. };
  8759. } // namespace detail
  8760. } // namespace nlohmann
  8761. namespace nlohmann
  8762. {
  8763. namespace detail
  8764. {
  8765. /*!
  8766. @brief an iterator value
  8767. @note This structure could easily be a union, but MSVC currently does not allow
  8768. unions members with complex constructors, see https://github.com/nlohmann/json/pull/105.
  8769. */
  8770. template<typename BasicJsonType> struct internal_iterator
  8771. {
  8772. /// iterator for JSON objects
  8773. typename BasicJsonType::object_t::iterator object_iterator {};
  8774. /// iterator for JSON arrays
  8775. typename BasicJsonType::array_t::iterator array_iterator {};
  8776. /// iterator for JSON binary arrays
  8777. typename BasicJsonType::binary_t::iterator binary_iterator {};
  8778. /// generic iterator for all other types
  8779. primitive_iterator_t primitive_iterator {};
  8780. };
  8781. } // namespace detail
  8782. } // namespace nlohmann
  8783. // #include <nlohmann/detail/iterators/iter_impl.hpp>
  8784. #include <ciso646> // not
  8785. #include <iterator> // iterator, random_access_iterator_tag, bidirectional_iterator_tag, advance, next
  8786. #include <type_traits> // conditional, is_const, remove_const
  8787. // #include <nlohmann/detail/exceptions.hpp>
  8788. // #include <nlohmann/detail/iterators/internal_iterator.hpp>
  8789. // #include <nlohmann/detail/iterators/primitive_iterator.hpp>
  8790. // #include <nlohmann/detail/macro_scope.hpp>
  8791. // #include <nlohmann/detail/meta/cpp_future.hpp>
  8792. // #include <nlohmann/detail/meta/type_traits.hpp>
  8793. // #include <nlohmann/detail/value_t.hpp>
  8794. namespace nlohmann
  8795. {
  8796. namespace detail
  8797. {
  8798. // forward declare, to be able to friend it later on
  8799. template<typename IteratorType> class iteration_proxy;
  8800. template<typename IteratorType> class iteration_proxy_value;
  8801. /*!
  8802. @brief a template for a bidirectional iterator for the @ref basic_json class
  8803. This class implements a both iterators (iterator and const_iterator) for the
  8804. @ref basic_json class.
  8805. @note An iterator is called *initialized* when a pointer to a JSON value has
  8806. been set (e.g., by a constructor or a copy assignment). If the iterator is
  8807. default-constructed, it is *uninitialized* and most methods are undefined.
  8808. **The library uses assertions to detect calls on uninitialized iterators.**
  8809. @requirement The class satisfies the following concept requirements:
  8810. -
  8811. [BidirectionalIterator](https://en.cppreference.com/w/cpp/named_req/BidirectionalIterator):
  8812. The iterator that can be moved can be moved in both directions (i.e.
  8813. incremented and decremented).
  8814. @since version 1.0.0, simplified in version 2.0.9, change to bidirectional
  8815. iterators in version 3.0.0 (see https://github.com/nlohmann/json/issues/593)
  8816. */
  8817. template<typename BasicJsonType>
  8818. class iter_impl
  8819. {
  8820. /// allow basic_json to access private members
  8821. friend iter_impl<typename std::conditional<std::is_const<BasicJsonType>::value, typename std::remove_const<BasicJsonType>::type, const BasicJsonType>::type>;
  8822. friend BasicJsonType;
  8823. friend iteration_proxy<iter_impl>;
  8824. friend iteration_proxy_value<iter_impl>;
  8825. using object_t = typename BasicJsonType::object_t;
  8826. using array_t = typename BasicJsonType::array_t;
  8827. // make sure BasicJsonType is basic_json or const basic_json
  8828. static_assert(is_basic_json<typename std::remove_const<BasicJsonType>::type>::value,
  8829. "iter_impl only accepts (const) basic_json");
  8830. public:
  8831. /// The std::iterator class template (used as a base class to provide typedefs) is deprecated in C++17.
  8832. /// The C++ Standard has never required user-defined iterators to derive from std::iterator.
  8833. /// A user-defined iterator should provide publicly accessible typedefs named
  8834. /// iterator_category, value_type, difference_type, pointer, and reference.
  8835. /// Note that value_type is required to be non-const, even for constant iterators.
  8836. using iterator_category = std::bidirectional_iterator_tag;
  8837. /// the type of the values when the iterator is dereferenced
  8838. using value_type = typename BasicJsonType::value_type;
  8839. /// a type to represent differences between iterators
  8840. using difference_type = typename BasicJsonType::difference_type;
  8841. /// defines a pointer to the type iterated over (value_type)
  8842. using pointer = typename std::conditional<std::is_const<BasicJsonType>::value,
  8843. typename BasicJsonType::const_pointer,
  8844. typename BasicJsonType::pointer>::type;
  8845. /// defines a reference to the type iterated over (value_type)
  8846. using reference =
  8847. typename std::conditional<std::is_const<BasicJsonType>::value,
  8848. typename BasicJsonType::const_reference,
  8849. typename BasicJsonType::reference>::type;
  8850. /// default constructor
  8851. iter_impl() = default;
  8852. /*!
  8853. @brief constructor for a given JSON instance
  8854. @param[in] object pointer to a JSON object for this iterator
  8855. @pre object != nullptr
  8856. @post The iterator is initialized; i.e. `m_object != nullptr`.
  8857. */
  8858. explicit iter_impl(pointer object) noexcept : m_object(object)
  8859. {
  8860. assert(m_object != nullptr);
  8861. switch (m_object->m_type)
  8862. {
  8863. case value_t::object:
  8864. {
  8865. m_it.object_iterator = typename object_t::iterator();
  8866. break;
  8867. }
  8868. case value_t::array:
  8869. {
  8870. m_it.array_iterator = typename array_t::iterator();
  8871. break;
  8872. }
  8873. default:
  8874. {
  8875. m_it.primitive_iterator = primitive_iterator_t();
  8876. break;
  8877. }
  8878. }
  8879. }
  8880. /*!
  8881. @note The conventional copy constructor and copy assignment are implicitly
  8882. defined. Combined with the following converting constructor and
  8883. assignment, they support: (1) copy from iterator to iterator, (2)
  8884. copy from const iterator to const iterator, and (3) conversion from
  8885. iterator to const iterator. However conversion from const iterator
  8886. to iterator is not defined.
  8887. */
  8888. /*!
  8889. @brief const copy constructor
  8890. @param[in] other const iterator to copy from
  8891. @note This copy constructor had to be defined explicitly to circumvent a bug
  8892. occurring on msvc v19.0 compiler (VS 2015) debug build. For more
  8893. information refer to: https://github.com/nlohmann/json/issues/1608
  8894. */
  8895. iter_impl(const iter_impl<const BasicJsonType>& other) noexcept
  8896. : m_object(other.m_object), m_it(other.m_it)
  8897. {}
  8898. /*!
  8899. @brief converting assignment
  8900. @param[in] other const iterator to copy from
  8901. @return const/non-const iterator
  8902. @note It is not checked whether @a other is initialized.
  8903. */
  8904. iter_impl& operator=(const iter_impl<const BasicJsonType>& other) noexcept
  8905. {
  8906. m_object = other.m_object;
  8907. m_it = other.m_it;
  8908. return *this;
  8909. }
  8910. /*!
  8911. @brief converting constructor
  8912. @param[in] other non-const iterator to copy from
  8913. @note It is not checked whether @a other is initialized.
  8914. */
  8915. iter_impl(const iter_impl<typename std::remove_const<BasicJsonType>::type>& other) noexcept
  8916. : m_object(other.m_object), m_it(other.m_it)
  8917. {}
  8918. /*!
  8919. @brief converting assignment
  8920. @param[in] other non-const iterator to copy from
  8921. @return const/non-const iterator
  8922. @note It is not checked whether @a other is initialized.
  8923. */
  8924. iter_impl& operator=(const iter_impl<typename std::remove_const<BasicJsonType>::type>& other) noexcept
  8925. {
  8926. m_object = other.m_object;
  8927. m_it = other.m_it;
  8928. return *this;
  8929. }
  8930. private:
  8931. /*!
  8932. @brief set the iterator to the first value
  8933. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  8934. */
  8935. void set_begin() noexcept
  8936. {
  8937. assert(m_object != nullptr);
  8938. switch (m_object->m_type)
  8939. {
  8940. case value_t::object:
  8941. {
  8942. m_it.object_iterator = m_object->m_value.object->begin();
  8943. break;
  8944. }
  8945. case value_t::array:
  8946. {
  8947. m_it.array_iterator = m_object->m_value.array->begin();
  8948. break;
  8949. }
  8950. case value_t::null:
  8951. {
  8952. // set to end so begin()==end() is true: null is empty
  8953. m_it.primitive_iterator.set_end();
  8954. break;
  8955. }
  8956. default:
  8957. {
  8958. m_it.primitive_iterator.set_begin();
  8959. break;
  8960. }
  8961. }
  8962. }
  8963. /*!
  8964. @brief set the iterator past the last value
  8965. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  8966. */
  8967. void set_end() noexcept
  8968. {
  8969. assert(m_object != nullptr);
  8970. switch (m_object->m_type)
  8971. {
  8972. case value_t::object:
  8973. {
  8974. m_it.object_iterator = m_object->m_value.object->end();
  8975. break;
  8976. }
  8977. case value_t::array:
  8978. {
  8979. m_it.array_iterator = m_object->m_value.array->end();
  8980. break;
  8981. }
  8982. default:
  8983. {
  8984. m_it.primitive_iterator.set_end();
  8985. break;
  8986. }
  8987. }
  8988. }
  8989. public:
  8990. /*!
  8991. @brief return a reference to the value pointed to by the iterator
  8992. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  8993. */
  8994. reference operator*() const
  8995. {
  8996. assert(m_object != nullptr);
  8997. switch (m_object->m_type)
  8998. {
  8999. case value_t::object:
  9000. {
  9001. assert(m_it.object_iterator != m_object->m_value.object->end());
  9002. return m_it.object_iterator->second;
  9003. }
  9004. case value_t::array:
  9005. {
  9006. assert(m_it.array_iterator != m_object->m_value.array->end());
  9007. return *m_it.array_iterator;
  9008. }
  9009. case value_t::null:
  9010. JSON_THROW(invalid_iterator::create(214, "cannot get value"));
  9011. default:
  9012. {
  9013. if (JSON_HEDLEY_LIKELY(m_it.primitive_iterator.is_begin()))
  9014. {
  9015. return *m_object;
  9016. }
  9017. JSON_THROW(invalid_iterator::create(214, "cannot get value"));
  9018. }
  9019. }
  9020. }
  9021. /*!
  9022. @brief dereference the iterator
  9023. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  9024. */
  9025. pointer operator->() const
  9026. {
  9027. assert(m_object != nullptr);
  9028. switch (m_object->m_type)
  9029. {
  9030. case value_t::object:
  9031. {
  9032. assert(m_it.object_iterator != m_object->m_value.object->end());
  9033. return &(m_it.object_iterator->second);
  9034. }
  9035. case value_t::array:
  9036. {
  9037. assert(m_it.array_iterator != m_object->m_value.array->end());
  9038. return &*m_it.array_iterator;
  9039. }
  9040. default:
  9041. {
  9042. if (JSON_HEDLEY_LIKELY(m_it.primitive_iterator.is_begin()))
  9043. {
  9044. return m_object;
  9045. }
  9046. JSON_THROW(invalid_iterator::create(214, "cannot get value"));
  9047. }
  9048. }
  9049. }
  9050. /*!
  9051. @brief post-increment (it++)
  9052. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  9053. */
  9054. iter_impl const operator++(int)
  9055. {
  9056. auto result = *this;
  9057. ++(*this);
  9058. return result;
  9059. }
  9060. /*!
  9061. @brief pre-increment (++it)
  9062. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  9063. */
  9064. iter_impl& operator++()
  9065. {
  9066. assert(m_object != nullptr);
  9067. switch (m_object->m_type)
  9068. {
  9069. case value_t::object:
  9070. {
  9071. std::advance(m_it.object_iterator, 1);
  9072. break;
  9073. }
  9074. case value_t::array:
  9075. {
  9076. std::advance(m_it.array_iterator, 1);
  9077. break;
  9078. }
  9079. default:
  9080. {
  9081. ++m_it.primitive_iterator;
  9082. break;
  9083. }
  9084. }
  9085. return *this;
  9086. }
  9087. /*!
  9088. @brief post-decrement (it--)
  9089. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  9090. */
  9091. iter_impl const operator--(int)
  9092. {
  9093. auto result = *this;
  9094. --(*this);
  9095. return result;
  9096. }
  9097. /*!
  9098. @brief pre-decrement (--it)
  9099. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  9100. */
  9101. iter_impl& operator--()
  9102. {
  9103. assert(m_object != nullptr);
  9104. switch (m_object->m_type)
  9105. {
  9106. case value_t::object:
  9107. {
  9108. std::advance(m_it.object_iterator, -1);
  9109. break;
  9110. }
  9111. case value_t::array:
  9112. {
  9113. std::advance(m_it.array_iterator, -1);
  9114. break;
  9115. }
  9116. default:
  9117. {
  9118. --m_it.primitive_iterator;
  9119. break;
  9120. }
  9121. }
  9122. return *this;
  9123. }
  9124. /*!
  9125. @brief comparison: equal
  9126. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  9127. */
  9128. bool operator==(const iter_impl& other) const
  9129. {
  9130. // if objects are not the same, the comparison is undefined
  9131. if (JSON_HEDLEY_UNLIKELY(m_object != other.m_object))
  9132. {
  9133. JSON_THROW(invalid_iterator::create(212, "cannot compare iterators of different containers"));
  9134. }
  9135. assert(m_object != nullptr);
  9136. switch (m_object->m_type)
  9137. {
  9138. case value_t::object:
  9139. return (m_it.object_iterator == other.m_it.object_iterator);
  9140. case value_t::array:
  9141. return (m_it.array_iterator == other.m_it.array_iterator);
  9142. default:
  9143. return (m_it.primitive_iterator == other.m_it.primitive_iterator);
  9144. }
  9145. }
  9146. /*!
  9147. @brief comparison: not equal
  9148. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  9149. */
  9150. bool operator!=(const iter_impl& other) const
  9151. {
  9152. return not operator==(other);
  9153. }
  9154. /*!
  9155. @brief comparison: smaller
  9156. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  9157. */
  9158. bool operator<(const iter_impl& other) const
  9159. {
  9160. // if objects are not the same, the comparison is undefined
  9161. if (JSON_HEDLEY_UNLIKELY(m_object != other.m_object))
  9162. {
  9163. JSON_THROW(invalid_iterator::create(212, "cannot compare iterators of different containers"));
  9164. }
  9165. assert(m_object != nullptr);
  9166. switch (m_object->m_type)
  9167. {
  9168. case value_t::object:
  9169. JSON_THROW(invalid_iterator::create(213, "cannot compare order of object iterators"));
  9170. case value_t::array:
  9171. return (m_it.array_iterator < other.m_it.array_iterator);
  9172. default:
  9173. return (m_it.primitive_iterator < other.m_it.primitive_iterator);
  9174. }
  9175. }
  9176. /*!
  9177. @brief comparison: less than or equal
  9178. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  9179. */
  9180. bool operator<=(const iter_impl& other) const
  9181. {
  9182. return not other.operator < (*this);
  9183. }
  9184. /*!
  9185. @brief comparison: greater than
  9186. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  9187. */
  9188. bool operator>(const iter_impl& other) const
  9189. {
  9190. return not operator<=(other);
  9191. }
  9192. /*!
  9193. @brief comparison: greater than or equal
  9194. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  9195. */
  9196. bool operator>=(const iter_impl& other) const
  9197. {
  9198. return not operator<(other);
  9199. }
  9200. /*!
  9201. @brief add to iterator
  9202. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  9203. */
  9204. iter_impl& operator+=(difference_type i)
  9205. {
  9206. assert(m_object != nullptr);
  9207. switch (m_object->m_type)
  9208. {
  9209. case value_t::object:
  9210. JSON_THROW(invalid_iterator::create(209, "cannot use offsets with object iterators"));
  9211. case value_t::array:
  9212. {
  9213. std::advance(m_it.array_iterator, i);
  9214. break;
  9215. }
  9216. default:
  9217. {
  9218. m_it.primitive_iterator += i;
  9219. break;
  9220. }
  9221. }
  9222. return *this;
  9223. }
  9224. /*!
  9225. @brief subtract from iterator
  9226. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  9227. */
  9228. iter_impl& operator-=(difference_type i)
  9229. {
  9230. return operator+=(-i);
  9231. }
  9232. /*!
  9233. @brief add to iterator
  9234. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  9235. */
  9236. iter_impl operator+(difference_type i) const
  9237. {
  9238. auto result = *this;
  9239. result += i;
  9240. return result;
  9241. }
  9242. /*!
  9243. @brief addition of distance and iterator
  9244. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  9245. */
  9246. friend iter_impl operator+(difference_type i, const iter_impl& it)
  9247. {
  9248. auto result = it;
  9249. result += i;
  9250. return result;
  9251. }
  9252. /*!
  9253. @brief subtract from iterator
  9254. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  9255. */
  9256. iter_impl operator-(difference_type i) const
  9257. {
  9258. auto result = *this;
  9259. result -= i;
  9260. return result;
  9261. }
  9262. /*!
  9263. @brief return difference
  9264. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  9265. */
  9266. difference_type operator-(const iter_impl& other) const
  9267. {
  9268. assert(m_object != nullptr);
  9269. switch (m_object->m_type)
  9270. {
  9271. case value_t::object:
  9272. JSON_THROW(invalid_iterator::create(209, "cannot use offsets with object iterators"));
  9273. case value_t::array:
  9274. return m_it.array_iterator - other.m_it.array_iterator;
  9275. default:
  9276. return m_it.primitive_iterator - other.m_it.primitive_iterator;
  9277. }
  9278. }
  9279. /*!
  9280. @brief access to successor
  9281. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  9282. */
  9283. reference operator[](difference_type n) const
  9284. {
  9285. assert(m_object != nullptr);
  9286. switch (m_object->m_type)
  9287. {
  9288. case value_t::object:
  9289. JSON_THROW(invalid_iterator::create(208, "cannot use operator[] for object iterators"));
  9290. case value_t::array:
  9291. return *std::next(m_it.array_iterator, n);
  9292. case value_t::null:
  9293. JSON_THROW(invalid_iterator::create(214, "cannot get value"));
  9294. default:
  9295. {
  9296. if (JSON_HEDLEY_LIKELY(m_it.primitive_iterator.get_value() == -n))
  9297. {
  9298. return *m_object;
  9299. }
  9300. JSON_THROW(invalid_iterator::create(214, "cannot get value"));
  9301. }
  9302. }
  9303. }
  9304. /*!
  9305. @brief return the key of an object iterator
  9306. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  9307. */
  9308. const typename object_t::key_type& key() const
  9309. {
  9310. assert(m_object != nullptr);
  9311. if (JSON_HEDLEY_LIKELY(m_object->is_object()))
  9312. {
  9313. return m_it.object_iterator->first;
  9314. }
  9315. JSON_THROW(invalid_iterator::create(207, "cannot use key() for non-object iterators"));
  9316. }
  9317. /*!
  9318. @brief return the value of an iterator
  9319. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  9320. */
  9321. reference value() const
  9322. {
  9323. return operator*();
  9324. }
  9325. private:
  9326. /// associated JSON instance
  9327. pointer m_object = nullptr;
  9328. /// the actual iterator of the associated instance
  9329. internal_iterator<typename std::remove_const<BasicJsonType>::type> m_it {};
  9330. };
  9331. } // namespace detail
  9332. } // namespace nlohmann
  9333. // #include <nlohmann/detail/iterators/iteration_proxy.hpp>
  9334. // #include <nlohmann/detail/iterators/json_reverse_iterator.hpp>
  9335. #include <cstddef> // ptrdiff_t
  9336. #include <iterator> // reverse_iterator
  9337. #include <utility> // declval
  9338. namespace nlohmann
  9339. {
  9340. namespace detail
  9341. {
  9342. //////////////////////
  9343. // reverse_iterator //
  9344. //////////////////////
  9345. /*!
  9346. @brief a template for a reverse iterator class
  9347. @tparam Base the base iterator type to reverse. Valid types are @ref
  9348. iterator (to create @ref reverse_iterator) and @ref const_iterator (to
  9349. create @ref const_reverse_iterator).
  9350. @requirement The class satisfies the following concept requirements:
  9351. -
  9352. [BidirectionalIterator](https://en.cppreference.com/w/cpp/named_req/BidirectionalIterator):
  9353. The iterator that can be moved can be moved in both directions (i.e.
  9354. incremented and decremented).
  9355. - [OutputIterator](https://en.cppreference.com/w/cpp/named_req/OutputIterator):
  9356. It is possible to write to the pointed-to element (only if @a Base is
  9357. @ref iterator).
  9358. @since version 1.0.0
  9359. */
  9360. template<typename Base>
  9361. class json_reverse_iterator : public std::reverse_iterator<Base>
  9362. {
  9363. public:
  9364. using difference_type = std::ptrdiff_t;
  9365. /// shortcut to the reverse iterator adapter
  9366. using base_iterator = std::reverse_iterator<Base>;
  9367. /// the reference type for the pointed-to element
  9368. using reference = typename Base::reference;
  9369. /// create reverse iterator from iterator
  9370. explicit json_reverse_iterator(const typename base_iterator::iterator_type& it) noexcept
  9371. : base_iterator(it) {}
  9372. /// create reverse iterator from base class
  9373. explicit json_reverse_iterator(const base_iterator& it) noexcept : base_iterator(it) {}
  9374. /// post-increment (it++)
  9375. json_reverse_iterator const operator++(int)
  9376. {
  9377. return static_cast<json_reverse_iterator>(base_iterator::operator++(1));
  9378. }
  9379. /// pre-increment (++it)
  9380. json_reverse_iterator& operator++()
  9381. {
  9382. return static_cast<json_reverse_iterator&>(base_iterator::operator++());
  9383. }
  9384. /// post-decrement (it--)
  9385. json_reverse_iterator const operator--(int)
  9386. {
  9387. return static_cast<json_reverse_iterator>(base_iterator::operator--(1));
  9388. }
  9389. /// pre-decrement (--it)
  9390. json_reverse_iterator& operator--()
  9391. {
  9392. return static_cast<json_reverse_iterator&>(base_iterator::operator--());
  9393. }
  9394. /// add to iterator
  9395. json_reverse_iterator& operator+=(difference_type i)
  9396. {
  9397. return static_cast<json_reverse_iterator&>(base_iterator::operator+=(i));
  9398. }
  9399. /// add to iterator
  9400. json_reverse_iterator operator+(difference_type i) const
  9401. {
  9402. return static_cast<json_reverse_iterator>(base_iterator::operator+(i));
  9403. }
  9404. /// subtract from iterator
  9405. json_reverse_iterator operator-(difference_type i) const
  9406. {
  9407. return static_cast<json_reverse_iterator>(base_iterator::operator-(i));
  9408. }
  9409. /// return difference
  9410. difference_type operator-(const json_reverse_iterator& other) const
  9411. {
  9412. return base_iterator(*this) - base_iterator(other);
  9413. }
  9414. /// access to successor
  9415. reference operator[](difference_type n) const
  9416. {
  9417. return *(this->operator+(n));
  9418. }
  9419. /// return the key of an object iterator
  9420. auto key() const -> decltype(std::declval<Base>().key())
  9421. {
  9422. auto it = --this->base();
  9423. return it.key();
  9424. }
  9425. /// return the value of an iterator
  9426. reference value() const
  9427. {
  9428. auto it = --this->base();
  9429. return it.operator * ();
  9430. }
  9431. };
  9432. } // namespace detail
  9433. } // namespace nlohmann
  9434. // #include <nlohmann/detail/iterators/primitive_iterator.hpp>
  9435. // #include <nlohmann/detail/json_pointer.hpp>
  9436. #include <algorithm> // all_of
  9437. #include <cassert> // assert
  9438. #include <cctype> // isdigit
  9439. #include <numeric> // accumulate
  9440. #include <string> // string
  9441. #include <utility> // move
  9442. #include <vector> // vector
  9443. // #include <nlohmann/detail/exceptions.hpp>
  9444. // #include <nlohmann/detail/macro_scope.hpp>
  9445. // #include <nlohmann/detail/value_t.hpp>
  9446. namespace nlohmann
  9447. {
  9448. template<typename BasicJsonType>
  9449. class json_pointer
  9450. {
  9451. // allow basic_json to access private members
  9452. NLOHMANN_BASIC_JSON_TPL_DECLARATION
  9453. friend class basic_json;
  9454. public:
  9455. /*!
  9456. @brief create JSON pointer
  9457. Create a JSON pointer according to the syntax described in
  9458. [Section 3 of RFC6901](https://tools.ietf.org/html/rfc6901#section-3).
  9459. @param[in] s string representing the JSON pointer; if omitted, the empty
  9460. string is assumed which references the whole JSON value
  9461. @throw parse_error.107 if the given JSON pointer @a s is nonempty and does
  9462. not begin with a slash (`/`); see example below
  9463. @throw parse_error.108 if a tilde (`~`) in the given JSON pointer @a s is
  9464. not followed by `0` (representing `~`) or `1` (representing `/`); see
  9465. example below
  9466. @liveexample{The example shows the construction several valid JSON pointers
  9467. as well as the exceptional behavior.,json_pointer}
  9468. @since version 2.0.0
  9469. */
  9470. explicit json_pointer(const std::string& s = "")
  9471. : reference_tokens(split(s))
  9472. {}
  9473. /*!
  9474. @brief return a string representation of the JSON pointer
  9475. @invariant For each JSON pointer `ptr`, it holds:
  9476. @code {.cpp}
  9477. ptr == json_pointer(ptr.to_string());
  9478. @endcode
  9479. @return a string representation of the JSON pointer
  9480. @liveexample{The example shows the result of `to_string`.,json_pointer__to_string}
  9481. @since version 2.0.0
  9482. */
  9483. std::string to_string() const
  9484. {
  9485. return std::accumulate(reference_tokens.begin(), reference_tokens.end(),
  9486. std::string{},
  9487. [](const std::string & a, const std::string & b)
  9488. {
  9489. return a + "/" + escape(b);
  9490. });
  9491. }
  9492. /// @copydoc to_string()
  9493. operator std::string() const
  9494. {
  9495. return to_string();
  9496. }
  9497. /*!
  9498. @brief append another JSON pointer at the end of this JSON pointer
  9499. @param[in] ptr JSON pointer to append
  9500. @return JSON pointer with @a ptr appended
  9501. @liveexample{The example shows the usage of `operator/=`.,json_pointer__operator_add}
  9502. @complexity Linear in the length of @a ptr.
  9503. @sa @ref operator/=(std::string) to append a reference token
  9504. @sa @ref operator/=(std::size_t) to append an array index
  9505. @sa @ref operator/(const json_pointer&, const json_pointer&) for a binary operator
  9506. @since version 3.6.0
  9507. */
  9508. json_pointer& operator/=(const json_pointer& ptr)
  9509. {
  9510. reference_tokens.insert(reference_tokens.end(),
  9511. ptr.reference_tokens.begin(),
  9512. ptr.reference_tokens.end());
  9513. return *this;
  9514. }
  9515. /*!
  9516. @brief append an unescaped reference token at the end of this JSON pointer
  9517. @param[in] token reference token to append
  9518. @return JSON pointer with @a token appended without escaping @a token
  9519. @liveexample{The example shows the usage of `operator/=`.,json_pointer__operator_add}
  9520. @complexity Amortized constant.
  9521. @sa @ref operator/=(const json_pointer&) to append a JSON pointer
  9522. @sa @ref operator/=(std::size_t) to append an array index
  9523. @sa @ref operator/(const json_pointer&, std::size_t) for a binary operator
  9524. @since version 3.6.0
  9525. */
  9526. json_pointer& operator/=(std::string token)
  9527. {
  9528. push_back(std::move(token));
  9529. return *this;
  9530. }
  9531. /*!
  9532. @brief append an array index at the end of this JSON pointer
  9533. @param[in] array_idx array index to append
  9534. @return JSON pointer with @a array_idx appended
  9535. @liveexample{The example shows the usage of `operator/=`.,json_pointer__operator_add}
  9536. @complexity Amortized constant.
  9537. @sa @ref operator/=(const json_pointer&) to append a JSON pointer
  9538. @sa @ref operator/=(std::string) to append a reference token
  9539. @sa @ref operator/(const json_pointer&, std::string) for a binary operator
  9540. @since version 3.6.0
  9541. */
  9542. json_pointer& operator/=(std::size_t array_idx)
  9543. {
  9544. return *this /= std::to_string(array_idx);
  9545. }
  9546. /*!
  9547. @brief create a new JSON pointer by appending the right JSON pointer at the end of the left JSON pointer
  9548. @param[in] lhs JSON pointer
  9549. @param[in] rhs JSON pointer
  9550. @return a new JSON pointer with @a rhs appended to @a lhs
  9551. @liveexample{The example shows the usage of `operator/`.,json_pointer__operator_add_binary}
  9552. @complexity Linear in the length of @a lhs and @a rhs.
  9553. @sa @ref operator/=(const json_pointer&) to append a JSON pointer
  9554. @since version 3.6.0
  9555. */
  9556. friend json_pointer operator/(const json_pointer& lhs,
  9557. const json_pointer& rhs)
  9558. {
  9559. return json_pointer(lhs) /= rhs;
  9560. }
  9561. /*!
  9562. @brief create a new JSON pointer by appending the unescaped token at the end of the JSON pointer
  9563. @param[in] ptr JSON pointer
  9564. @param[in] token reference token
  9565. @return a new JSON pointer with unescaped @a token appended to @a ptr
  9566. @liveexample{The example shows the usage of `operator/`.,json_pointer__operator_add_binary}
  9567. @complexity Linear in the length of @a ptr.
  9568. @sa @ref operator/=(std::string) to append a reference token
  9569. @since version 3.6.0
  9570. */
  9571. friend json_pointer operator/(const json_pointer& ptr, std::string token)
  9572. {
  9573. return json_pointer(ptr) /= std::move(token);
  9574. }
  9575. /*!
  9576. @brief create a new JSON pointer by appending the array-index-token at the end of the JSON pointer
  9577. @param[in] ptr JSON pointer
  9578. @param[in] array_idx array index
  9579. @return a new JSON pointer with @a array_idx appended to @a ptr
  9580. @liveexample{The example shows the usage of `operator/`.,json_pointer__operator_add_binary}
  9581. @complexity Linear in the length of @a ptr.
  9582. @sa @ref operator/=(std::size_t) to append an array index
  9583. @since version 3.6.0
  9584. */
  9585. friend json_pointer operator/(const json_pointer& ptr, std::size_t array_idx)
  9586. {
  9587. return json_pointer(ptr) /= array_idx;
  9588. }
  9589. /*!
  9590. @brief returns the parent of this JSON pointer
  9591. @return parent of this JSON pointer; in case this JSON pointer is the root,
  9592. the root itself is returned
  9593. @complexity Linear in the length of the JSON pointer.
  9594. @liveexample{The example shows the result of `parent_pointer` for different
  9595. JSON Pointers.,json_pointer__parent_pointer}
  9596. @since version 3.6.0
  9597. */
  9598. json_pointer parent_pointer() const
  9599. {
  9600. if (empty())
  9601. {
  9602. return *this;
  9603. }
  9604. json_pointer res = *this;
  9605. res.pop_back();
  9606. return res;
  9607. }
  9608. /*!
  9609. @brief remove last reference token
  9610. @pre not `empty()`
  9611. @liveexample{The example shows the usage of `pop_back`.,json_pointer__pop_back}
  9612. @complexity Constant.
  9613. @throw out_of_range.405 if JSON pointer has no parent
  9614. @since version 3.6.0
  9615. */
  9616. void pop_back()
  9617. {
  9618. if (JSON_HEDLEY_UNLIKELY(empty()))
  9619. {
  9620. JSON_THROW(detail::out_of_range::create(405, "JSON pointer has no parent"));
  9621. }
  9622. reference_tokens.pop_back();
  9623. }
  9624. /*!
  9625. @brief return last reference token
  9626. @pre not `empty()`
  9627. @return last reference token
  9628. @liveexample{The example shows the usage of `back`.,json_pointer__back}
  9629. @complexity Constant.
  9630. @throw out_of_range.405 if JSON pointer has no parent
  9631. @since version 3.6.0
  9632. */
  9633. const std::string& back() const
  9634. {
  9635. if (JSON_HEDLEY_UNLIKELY(empty()))
  9636. {
  9637. JSON_THROW(detail::out_of_range::create(405, "JSON pointer has no parent"));
  9638. }
  9639. return reference_tokens.back();
  9640. }
  9641. /*!
  9642. @brief append an unescaped token at the end of the reference pointer
  9643. @param[in] token token to add
  9644. @complexity Amortized constant.
  9645. @liveexample{The example shows the result of `push_back` for different
  9646. JSON Pointers.,json_pointer__push_back}
  9647. @since version 3.6.0
  9648. */
  9649. void push_back(const std::string& token)
  9650. {
  9651. reference_tokens.push_back(token);
  9652. }
  9653. /// @copydoc push_back(const std::string&)
  9654. void push_back(std::string&& token)
  9655. {
  9656. reference_tokens.push_back(std::move(token));
  9657. }
  9658. /*!
  9659. @brief return whether pointer points to the root document
  9660. @return true iff the JSON pointer points to the root document
  9661. @complexity Constant.
  9662. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  9663. @liveexample{The example shows the result of `empty` for different JSON
  9664. Pointers.,json_pointer__empty}
  9665. @since version 3.6.0
  9666. */
  9667. bool empty() const noexcept
  9668. {
  9669. return reference_tokens.empty();
  9670. }
  9671. private:
  9672. /*!
  9673. @param[in] s reference token to be converted into an array index
  9674. @return integer representation of @a s
  9675. @throw out_of_range.404 if string @a s could not be converted to an integer
  9676. */
  9677. static int array_index(const std::string& s)
  9678. {
  9679. // error condition (cf. RFC 6901, Sect. 4)
  9680. if (JSON_HEDLEY_UNLIKELY(s.size() > 1 and s[0] == '0'))
  9681. {
  9682. JSON_THROW(detail::parse_error::create(106, 0,
  9683. "array index '" + s +
  9684. "' must not begin with '0'"));
  9685. }
  9686. // error condition (cf. RFC 6901, Sect. 4)
  9687. if (JSON_HEDLEY_UNLIKELY(s.size() > 1 and not (s[0] >= '1' and s[0] <= '9')))
  9688. {
  9689. JSON_THROW(detail::parse_error::create(109, 0, "array index '" + s + "' is not a number"));
  9690. }
  9691. std::size_t processed_chars = 0;
  9692. int res = 0;
  9693. JSON_TRY
  9694. {
  9695. res = std::stoi(s, &processed_chars);
  9696. }
  9697. JSON_CATCH(std::out_of_range&)
  9698. {
  9699. JSON_THROW(detail::out_of_range::create(404, "unresolved reference token '" + s + "'"));
  9700. }
  9701. // check if the string was completely read
  9702. if (JSON_HEDLEY_UNLIKELY(processed_chars != s.size()))
  9703. {
  9704. JSON_THROW(detail::out_of_range::create(404, "unresolved reference token '" + s + "'"));
  9705. }
  9706. return res;
  9707. }
  9708. json_pointer top() const
  9709. {
  9710. if (JSON_HEDLEY_UNLIKELY(empty()))
  9711. {
  9712. JSON_THROW(detail::out_of_range::create(405, "JSON pointer has no parent"));
  9713. }
  9714. json_pointer result = *this;
  9715. result.reference_tokens = {reference_tokens[0]};
  9716. return result;
  9717. }
  9718. /*!
  9719. @brief create and return a reference to the pointed to value
  9720. @complexity Linear in the number of reference tokens.
  9721. @throw parse_error.109 if array index is not a number
  9722. @throw type_error.313 if value cannot be unflattened
  9723. */
  9724. BasicJsonType& get_and_create(BasicJsonType& j) const
  9725. {
  9726. using size_type = typename BasicJsonType::size_type;
  9727. auto result = &j;
  9728. // in case no reference tokens exist, return a reference to the JSON value
  9729. // j which will be overwritten by a primitive value
  9730. for (const auto& reference_token : reference_tokens)
  9731. {
  9732. switch (result->type())
  9733. {
  9734. case detail::value_t::null:
  9735. {
  9736. if (reference_token == "0")
  9737. {
  9738. // start a new array if reference token is 0
  9739. result = &result->operator[](0);
  9740. }
  9741. else
  9742. {
  9743. // start a new object otherwise
  9744. result = &result->operator[](reference_token);
  9745. }
  9746. break;
  9747. }
  9748. case detail::value_t::object:
  9749. {
  9750. // create an entry in the object
  9751. result = &result->operator[](reference_token);
  9752. break;
  9753. }
  9754. case detail::value_t::array:
  9755. {
  9756. // create an entry in the array
  9757. result = &result->operator[](static_cast<size_type>(array_index(reference_token)));
  9758. break;
  9759. }
  9760. /*
  9761. The following code is only reached if there exists a reference
  9762. token _and_ the current value is primitive. In this case, we have
  9763. an error situation, because primitive values may only occur as
  9764. single value; that is, with an empty list of reference tokens.
  9765. */
  9766. default:
  9767. JSON_THROW(detail::type_error::create(313, "invalid value to unflatten"));
  9768. }
  9769. }
  9770. return *result;
  9771. }
  9772. /*!
  9773. @brief return a reference to the pointed to value
  9774. @note This version does not throw if a value is not present, but tries to
  9775. create nested values instead. For instance, calling this function
  9776. with pointer `"/this/that"` on a null value is equivalent to calling
  9777. `operator[]("this").operator[]("that")` on that value, effectively
  9778. changing the null value to an object.
  9779. @param[in] ptr a JSON value
  9780. @return reference to the JSON value pointed to by the JSON pointer
  9781. @complexity Linear in the length of the JSON pointer.
  9782. @throw parse_error.106 if an array index begins with '0'
  9783. @throw parse_error.109 if an array index was not a number
  9784. @throw out_of_range.404 if the JSON pointer can not be resolved
  9785. */
  9786. BasicJsonType& get_unchecked(BasicJsonType* ptr) const
  9787. {
  9788. using size_type = typename BasicJsonType::size_type;
  9789. for (const auto& reference_token : reference_tokens)
  9790. {
  9791. // convert null values to arrays or objects before continuing
  9792. if (ptr->is_null())
  9793. {
  9794. // check if reference token is a number
  9795. const bool nums =
  9796. std::all_of(reference_token.begin(), reference_token.end(),
  9797. [](const unsigned char x)
  9798. {
  9799. return std::isdigit(x);
  9800. });
  9801. // change value to array for numbers or "-" or to object otherwise
  9802. *ptr = (nums or reference_token == "-")
  9803. ? detail::value_t::array
  9804. : detail::value_t::object;
  9805. }
  9806. switch (ptr->type())
  9807. {
  9808. case detail::value_t::object:
  9809. {
  9810. // use unchecked object access
  9811. ptr = &ptr->operator[](reference_token);
  9812. break;
  9813. }
  9814. case detail::value_t::array:
  9815. {
  9816. if (reference_token == "-")
  9817. {
  9818. // explicitly treat "-" as index beyond the end
  9819. ptr = &ptr->operator[](ptr->m_value.array->size());
  9820. }
  9821. else
  9822. {
  9823. // convert array index to number; unchecked access
  9824. ptr = &ptr->operator[](
  9825. static_cast<size_type>(array_index(reference_token)));
  9826. }
  9827. break;
  9828. }
  9829. default:
  9830. JSON_THROW(detail::out_of_range::create(404, "unresolved reference token '" + reference_token + "'"));
  9831. }
  9832. }
  9833. return *ptr;
  9834. }
  9835. /*!
  9836. @throw parse_error.106 if an array index begins with '0'
  9837. @throw parse_error.109 if an array index was not a number
  9838. @throw out_of_range.402 if the array index '-' is used
  9839. @throw out_of_range.404 if the JSON pointer can not be resolved
  9840. */
  9841. BasicJsonType& get_checked(BasicJsonType* ptr) const
  9842. {
  9843. using size_type = typename BasicJsonType::size_type;
  9844. for (const auto& reference_token : reference_tokens)
  9845. {
  9846. switch (ptr->type())
  9847. {
  9848. case detail::value_t::object:
  9849. {
  9850. // note: at performs range check
  9851. ptr = &ptr->at(reference_token);
  9852. break;
  9853. }
  9854. case detail::value_t::array:
  9855. {
  9856. if (JSON_HEDLEY_UNLIKELY(reference_token == "-"))
  9857. {
  9858. // "-" always fails the range check
  9859. JSON_THROW(detail::out_of_range::create(402,
  9860. "array index '-' (" + std::to_string(ptr->m_value.array->size()) +
  9861. ") is out of range"));
  9862. }
  9863. // note: at performs range check
  9864. ptr = &ptr->at(static_cast<size_type>(array_index(reference_token)));
  9865. break;
  9866. }
  9867. default:
  9868. JSON_THROW(detail::out_of_range::create(404, "unresolved reference token '" + reference_token + "'"));
  9869. }
  9870. }
  9871. return *ptr;
  9872. }
  9873. /*!
  9874. @brief return a const reference to the pointed to value
  9875. @param[in] ptr a JSON value
  9876. @return const reference to the JSON value pointed to by the JSON
  9877. pointer
  9878. @throw parse_error.106 if an array index begins with '0'
  9879. @throw parse_error.109 if an array index was not a number
  9880. @throw out_of_range.402 if the array index '-' is used
  9881. @throw out_of_range.404 if the JSON pointer can not be resolved
  9882. */
  9883. const BasicJsonType& get_unchecked(const BasicJsonType* ptr) const
  9884. {
  9885. using size_type = typename BasicJsonType::size_type;
  9886. for (const auto& reference_token : reference_tokens)
  9887. {
  9888. switch (ptr->type())
  9889. {
  9890. case detail::value_t::object:
  9891. {
  9892. // use unchecked object access
  9893. ptr = &ptr->operator[](reference_token);
  9894. break;
  9895. }
  9896. case detail::value_t::array:
  9897. {
  9898. if (JSON_HEDLEY_UNLIKELY(reference_token == "-"))
  9899. {
  9900. // "-" cannot be used for const access
  9901. JSON_THROW(detail::out_of_range::create(402,
  9902. "array index '-' (" + std::to_string(ptr->m_value.array->size()) +
  9903. ") is out of range"));
  9904. }
  9905. // use unchecked array access
  9906. ptr = &ptr->operator[](
  9907. static_cast<size_type>(array_index(reference_token)));
  9908. break;
  9909. }
  9910. default:
  9911. JSON_THROW(detail::out_of_range::create(404, "unresolved reference token '" + reference_token + "'"));
  9912. }
  9913. }
  9914. return *ptr;
  9915. }
  9916. /*!
  9917. @throw parse_error.106 if an array index begins with '0'
  9918. @throw parse_error.109 if an array index was not a number
  9919. @throw out_of_range.402 if the array index '-' is used
  9920. @throw out_of_range.404 if the JSON pointer can not be resolved
  9921. */
  9922. const BasicJsonType& get_checked(const BasicJsonType* ptr) const
  9923. {
  9924. using size_type = typename BasicJsonType::size_type;
  9925. for (const auto& reference_token : reference_tokens)
  9926. {
  9927. switch (ptr->type())
  9928. {
  9929. case detail::value_t::object:
  9930. {
  9931. // note: at performs range check
  9932. ptr = &ptr->at(reference_token);
  9933. break;
  9934. }
  9935. case detail::value_t::array:
  9936. {
  9937. if (JSON_HEDLEY_UNLIKELY(reference_token == "-"))
  9938. {
  9939. // "-" always fails the range check
  9940. JSON_THROW(detail::out_of_range::create(402,
  9941. "array index '-' (" + std::to_string(ptr->m_value.array->size()) +
  9942. ") is out of range"));
  9943. }
  9944. // note: at performs range check
  9945. ptr = &ptr->at(static_cast<size_type>(array_index(reference_token)));
  9946. break;
  9947. }
  9948. default:
  9949. JSON_THROW(detail::out_of_range::create(404, "unresolved reference token '" + reference_token + "'"));
  9950. }
  9951. }
  9952. return *ptr;
  9953. }
  9954. /*!
  9955. @throw parse_error.106 if an array index begins with '0'
  9956. @throw parse_error.109 if an array index was not a number
  9957. */
  9958. bool contains(const BasicJsonType* ptr) const
  9959. {
  9960. using size_type = typename BasicJsonType::size_type;
  9961. for (const auto& reference_token : reference_tokens)
  9962. {
  9963. switch (ptr->type())
  9964. {
  9965. case detail::value_t::object:
  9966. {
  9967. if (not ptr->contains(reference_token))
  9968. {
  9969. // we did not find the key in the object
  9970. return false;
  9971. }
  9972. ptr = &ptr->operator[](reference_token);
  9973. break;
  9974. }
  9975. case detail::value_t::array:
  9976. {
  9977. if (JSON_HEDLEY_UNLIKELY(reference_token == "-"))
  9978. {
  9979. // "-" always fails the range check
  9980. return false;
  9981. }
  9982. if (JSON_HEDLEY_UNLIKELY(reference_token.size() == 1 and not ("0" <= reference_token and reference_token <= "9")))
  9983. {
  9984. // invalid char
  9985. return false;
  9986. }
  9987. if (JSON_HEDLEY_UNLIKELY(reference_token.size() > 1))
  9988. {
  9989. if (JSON_HEDLEY_UNLIKELY(not ('1' <= reference_token[0] and reference_token[0] <= '9')))
  9990. {
  9991. // first char should be between '1' and '9'
  9992. return false;
  9993. }
  9994. for (std::size_t i = 1; i < reference_token.size(); i++)
  9995. {
  9996. if (JSON_HEDLEY_UNLIKELY(not ('0' <= reference_token[i] and reference_token[i] <= '9')))
  9997. {
  9998. // other char should be between '0' and '9'
  9999. return false;
  10000. }
  10001. }
  10002. }
  10003. const auto idx = static_cast<size_type>(array_index(reference_token));
  10004. if (idx >= ptr->size())
  10005. {
  10006. // index out of range
  10007. return false;
  10008. }
  10009. ptr = &ptr->operator[](idx);
  10010. break;
  10011. }
  10012. default:
  10013. {
  10014. // we do not expect primitive values if there is still a
  10015. // reference token to process
  10016. return false;
  10017. }
  10018. }
  10019. }
  10020. // no reference token left means we found a primitive value
  10021. return true;
  10022. }
  10023. /*!
  10024. @brief split the string input to reference tokens
  10025. @note This function is only called by the json_pointer constructor.
  10026. All exceptions below are documented there.
  10027. @throw parse_error.107 if the pointer is not empty or begins with '/'
  10028. @throw parse_error.108 if character '~' is not followed by '0' or '1'
  10029. */
  10030. static std::vector<std::string> split(const std::string& reference_string)
  10031. {
  10032. std::vector<std::string> result;
  10033. // special case: empty reference string -> no reference tokens
  10034. if (reference_string.empty())
  10035. {
  10036. return result;
  10037. }
  10038. // check if nonempty reference string begins with slash
  10039. if (JSON_HEDLEY_UNLIKELY(reference_string[0] != '/'))
  10040. {
  10041. JSON_THROW(detail::parse_error::create(107, 1,
  10042. "JSON pointer must be empty or begin with '/' - was: '" +
  10043. reference_string + "'"));
  10044. }
  10045. // extract the reference tokens:
  10046. // - slash: position of the last read slash (or end of string)
  10047. // - start: position after the previous slash
  10048. for (
  10049. // search for the first slash after the first character
  10050. std::size_t slash = reference_string.find_first_of('/', 1),
  10051. // set the beginning of the first reference token
  10052. start = 1;
  10053. // we can stop if start == 0 (if slash == std::string::npos)
  10054. start != 0;
  10055. // set the beginning of the next reference token
  10056. // (will eventually be 0 if slash == std::string::npos)
  10057. start = (slash == std::string::npos) ? 0 : slash + 1,
  10058. // find next slash
  10059. slash = reference_string.find_first_of('/', start))
  10060. {
  10061. // use the text between the beginning of the reference token
  10062. // (start) and the last slash (slash).
  10063. auto reference_token = reference_string.substr(start, slash - start);
  10064. // check reference tokens are properly escaped
  10065. for (std::size_t pos = reference_token.find_first_of('~');
  10066. pos != std::string::npos;
  10067. pos = reference_token.find_first_of('~', pos + 1))
  10068. {
  10069. assert(reference_token[pos] == '~');
  10070. // ~ must be followed by 0 or 1
  10071. if (JSON_HEDLEY_UNLIKELY(pos == reference_token.size() - 1 or
  10072. (reference_token[pos + 1] != '0' and
  10073. reference_token[pos + 1] != '1')))
  10074. {
  10075. JSON_THROW(detail::parse_error::create(108, 0, "escape character '~' must be followed with '0' or '1'"));
  10076. }
  10077. }
  10078. // finally, store the reference token
  10079. unescape(reference_token);
  10080. result.push_back(reference_token);
  10081. }
  10082. return result;
  10083. }
  10084. /*!
  10085. @brief replace all occurrences of a substring by another string
  10086. @param[in,out] s the string to manipulate; changed so that all
  10087. occurrences of @a f are replaced with @a t
  10088. @param[in] f the substring to replace with @a t
  10089. @param[in] t the string to replace @a f
  10090. @pre The search string @a f must not be empty. **This precondition is
  10091. enforced with an assertion.**
  10092. @since version 2.0.0
  10093. */
  10094. static void replace_substring(std::string& s, const std::string& f,
  10095. const std::string& t)
  10096. {
  10097. assert(not f.empty());
  10098. for (auto pos = s.find(f); // find first occurrence of f
  10099. pos != std::string::npos; // make sure f was found
  10100. s.replace(pos, f.size(), t), // replace with t, and
  10101. pos = s.find(f, pos + t.size())) // find next occurrence of f
  10102. {}
  10103. }
  10104. /// escape "~" to "~0" and "/" to "~1"
  10105. static std::string escape(std::string s)
  10106. {
  10107. replace_substring(s, "~", "~0");
  10108. replace_substring(s, "/", "~1");
  10109. return s;
  10110. }
  10111. /// unescape "~1" to tilde and "~0" to slash (order is important!)
  10112. static void unescape(std::string& s)
  10113. {
  10114. replace_substring(s, "~1", "/");
  10115. replace_substring(s, "~0", "~");
  10116. }
  10117. /*!
  10118. @param[in] reference_string the reference string to the current value
  10119. @param[in] value the value to consider
  10120. @param[in,out] result the result object to insert values to
  10121. @note Empty objects or arrays are flattened to `null`.
  10122. */
  10123. static void flatten(const std::string& reference_string,
  10124. const BasicJsonType& value,
  10125. BasicJsonType& result)
  10126. {
  10127. switch (value.type())
  10128. {
  10129. case detail::value_t::array:
  10130. {
  10131. if (value.m_value.array->empty())
  10132. {
  10133. // flatten empty array as null
  10134. result[reference_string] = nullptr;
  10135. }
  10136. else
  10137. {
  10138. // iterate array and use index as reference string
  10139. for (std::size_t i = 0; i < value.m_value.array->size(); ++i)
  10140. {
  10141. flatten(reference_string + "/" + std::to_string(i),
  10142. value.m_value.array->operator[](i), result);
  10143. }
  10144. }
  10145. break;
  10146. }
  10147. case detail::value_t::object:
  10148. {
  10149. if (value.m_value.object->empty())
  10150. {
  10151. // flatten empty object as null
  10152. result[reference_string] = nullptr;
  10153. }
  10154. else
  10155. {
  10156. // iterate object and use keys as reference string
  10157. for (const auto& element : *value.m_value.object)
  10158. {
  10159. flatten(reference_string + "/" + escape(element.first), element.second, result);
  10160. }
  10161. }
  10162. break;
  10163. }
  10164. default:
  10165. {
  10166. // add primitive value with its reference string
  10167. result[reference_string] = value;
  10168. break;
  10169. }
  10170. }
  10171. }
  10172. /*!
  10173. @param[in] value flattened JSON
  10174. @return unflattened JSON
  10175. @throw parse_error.109 if array index is not a number
  10176. @throw type_error.314 if value is not an object
  10177. @throw type_error.315 if object values are not primitive
  10178. @throw type_error.313 if value cannot be unflattened
  10179. */
  10180. static BasicJsonType
  10181. unflatten(const BasicJsonType& value)
  10182. {
  10183. if (JSON_HEDLEY_UNLIKELY(not value.is_object()))
  10184. {
  10185. JSON_THROW(detail::type_error::create(314, "only objects can be unflattened"));
  10186. }
  10187. BasicJsonType result;
  10188. // iterate the JSON object values
  10189. for (const auto& element : *value.m_value.object)
  10190. {
  10191. if (JSON_HEDLEY_UNLIKELY(not element.second.is_primitive()))
  10192. {
  10193. JSON_THROW(detail::type_error::create(315, "values in object must be primitive"));
  10194. }
  10195. // assign value to reference pointed to by JSON pointer; Note that if
  10196. // the JSON pointer is "" (i.e., points to the whole value), function
  10197. // get_and_create returns a reference to result itself. An assignment
  10198. // will then create a primitive value.
  10199. json_pointer(element.first).get_and_create(result) = element.second;
  10200. }
  10201. return result;
  10202. }
  10203. /*!
  10204. @brief compares two JSON pointers for equality
  10205. @param[in] lhs JSON pointer to compare
  10206. @param[in] rhs JSON pointer to compare
  10207. @return whether @a lhs is equal to @a rhs
  10208. @complexity Linear in the length of the JSON pointer
  10209. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  10210. */
  10211. friend bool operator==(json_pointer const& lhs,
  10212. json_pointer const& rhs) noexcept
  10213. {
  10214. return lhs.reference_tokens == rhs.reference_tokens;
  10215. }
  10216. /*!
  10217. @brief compares two JSON pointers for inequality
  10218. @param[in] lhs JSON pointer to compare
  10219. @param[in] rhs JSON pointer to compare
  10220. @return whether @a lhs is not equal @a rhs
  10221. @complexity Linear in the length of the JSON pointer
  10222. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  10223. */
  10224. friend bool operator!=(json_pointer const& lhs,
  10225. json_pointer const& rhs) noexcept
  10226. {
  10227. return not (lhs == rhs);
  10228. }
  10229. /// the reference tokens
  10230. std::vector<std::string> reference_tokens;
  10231. };
  10232. } // namespace nlohmann
  10233. // #include <nlohmann/detail/json_ref.hpp>
  10234. #include <initializer_list>
  10235. #include <utility>
  10236. // #include <nlohmann/detail/meta/type_traits.hpp>
  10237. namespace nlohmann
  10238. {
  10239. namespace detail
  10240. {
  10241. template<typename BasicJsonType>
  10242. class json_ref
  10243. {
  10244. public:
  10245. using value_type = BasicJsonType;
  10246. json_ref(value_type&& value)
  10247. : owned_value(std::move(value)), value_ref(&owned_value), is_rvalue(true)
  10248. {}
  10249. json_ref(const value_type& value)
  10250. : value_ref(const_cast<value_type*>(&value)), is_rvalue(false)
  10251. {}
  10252. json_ref(std::initializer_list<json_ref> init)
  10253. : owned_value(init), value_ref(&owned_value), is_rvalue(true)
  10254. {}
  10255. template <
  10256. class... Args,
  10257. enable_if_t<std::is_constructible<value_type, Args...>::value, int> = 0 >
  10258. json_ref(Args && ... args)
  10259. : owned_value(std::forward<Args>(args)...), value_ref(&owned_value),
  10260. is_rvalue(true) {}
  10261. // class should be movable only
  10262. json_ref(json_ref&&) = default;
  10263. json_ref(const json_ref&) = delete;
  10264. json_ref& operator=(const json_ref&) = delete;
  10265. json_ref& operator=(json_ref&&) = delete;
  10266. ~json_ref() = default;
  10267. value_type moved_or_copied() const
  10268. {
  10269. if (is_rvalue)
  10270. {
  10271. return std::move(*value_ref);
  10272. }
  10273. return *value_ref;
  10274. }
  10275. value_type const& operator*() const
  10276. {
  10277. return *static_cast<value_type const*>(value_ref);
  10278. }
  10279. value_type const* operator->() const
  10280. {
  10281. return static_cast<value_type const*>(value_ref);
  10282. }
  10283. private:
  10284. mutable value_type owned_value = nullptr;
  10285. value_type* value_ref = nullptr;
  10286. const bool is_rvalue;
  10287. };
  10288. } // namespace detail
  10289. } // namespace nlohmann
  10290. // #include <nlohmann/detail/macro_scope.hpp>
  10291. // #include <nlohmann/detail/meta/cpp_future.hpp>
  10292. // #include <nlohmann/detail/meta/type_traits.hpp>
  10293. // #include <nlohmann/detail/output/binary_writer.hpp>
  10294. #include <algorithm> // reverse
  10295. #include <array> // array
  10296. #include <cstdint> // uint8_t, uint16_t, uint32_t, uint64_t
  10297. #include <cstring> // memcpy
  10298. #include <limits> // numeric_limits
  10299. #include <string> // string
  10300. // #include <nlohmann/detail/input/binary_reader.hpp>
  10301. // #include <nlohmann/detail/macro_scope.hpp>
  10302. // #include <nlohmann/detail/output/output_adapters.hpp>
  10303. #include <algorithm> // copy
  10304. #include <cstddef> // size_t
  10305. #include <ios> // streamsize
  10306. #include <iterator> // back_inserter
  10307. #include <memory> // shared_ptr, make_shared
  10308. #include <ostream> // basic_ostream
  10309. #include <string> // basic_string
  10310. #include <vector> // vector
  10311. // #include <nlohmann/detail/macro_scope.hpp>
  10312. namespace nlohmann
  10313. {
  10314. namespace detail
  10315. {
  10316. /// abstract output adapter interface
  10317. template<typename CharType> struct output_adapter_protocol
  10318. {
  10319. virtual void write_character(CharType c) = 0;
  10320. virtual void write_characters(const CharType* s, std::size_t length) = 0;
  10321. virtual ~output_adapter_protocol() = default;
  10322. };
  10323. /// a type to simplify interfaces
  10324. template<typename CharType>
  10325. using output_adapter_t = std::shared_ptr<output_adapter_protocol<CharType>>;
  10326. /// output adapter for byte vectors
  10327. template<typename CharType>
  10328. class output_vector_adapter : public output_adapter_protocol<CharType>
  10329. {
  10330. public:
  10331. explicit output_vector_adapter(std::vector<CharType>& vec) noexcept
  10332. : v(vec)
  10333. {}
  10334. void write_character(CharType c) override
  10335. {
  10336. v.push_back(c);
  10337. }
  10338. JSON_HEDLEY_NON_NULL(2)
  10339. void write_characters(const CharType* s, std::size_t length) override
  10340. {
  10341. std::copy(s, s + length, std::back_inserter(v));
  10342. }
  10343. private:
  10344. std::vector<CharType>& v;
  10345. };
  10346. /// output adapter for output streams
  10347. template<typename CharType>
  10348. class output_stream_adapter : public output_adapter_protocol<CharType>
  10349. {
  10350. public:
  10351. explicit output_stream_adapter(std::basic_ostream<CharType>& s) noexcept
  10352. : stream(s)
  10353. {}
  10354. void write_character(CharType c) override
  10355. {
  10356. stream.put(c);
  10357. }
  10358. JSON_HEDLEY_NON_NULL(2)
  10359. void write_characters(const CharType* s, std::size_t length) override
  10360. {
  10361. stream.write(s, static_cast<std::streamsize>(length));
  10362. }
  10363. private:
  10364. std::basic_ostream<CharType>& stream;
  10365. };
  10366. /// output adapter for basic_string
  10367. template<typename CharType, typename StringType = std::basic_string<CharType>>
  10368. class output_string_adapter : public output_adapter_protocol<CharType>
  10369. {
  10370. public:
  10371. explicit output_string_adapter(StringType& s) noexcept
  10372. : str(s)
  10373. {}
  10374. void write_character(CharType c) override
  10375. {
  10376. str.push_back(c);
  10377. }
  10378. JSON_HEDLEY_NON_NULL(2)
  10379. void write_characters(const CharType* s, std::size_t length) override
  10380. {
  10381. str.append(s, length);
  10382. }
  10383. private:
  10384. StringType& str;
  10385. };
  10386. template<typename CharType, typename StringType = std::basic_string<CharType>>
  10387. class output_adapter
  10388. {
  10389. public:
  10390. output_adapter(std::vector<CharType>& vec)
  10391. : oa(std::make_shared<output_vector_adapter<CharType>>(vec)) {}
  10392. output_adapter(std::basic_ostream<CharType>& s)
  10393. : oa(std::make_shared<output_stream_adapter<CharType>>(s)) {}
  10394. output_adapter(StringType& s)
  10395. : oa(std::make_shared<output_string_adapter<CharType, StringType>>(s)) {}
  10396. operator output_adapter_t<CharType>()
  10397. {
  10398. return oa;
  10399. }
  10400. private:
  10401. output_adapter_t<CharType> oa = nullptr;
  10402. };
  10403. } // namespace detail
  10404. } // namespace nlohmann
  10405. namespace nlohmann
  10406. {
  10407. namespace detail
  10408. {
  10409. ///////////////////
  10410. // binary writer //
  10411. ///////////////////
  10412. /*!
  10413. @brief serialization to CBOR and MessagePack values
  10414. */
  10415. template<typename BasicJsonType, typename CharType>
  10416. class binary_writer
  10417. {
  10418. using string_t = typename BasicJsonType::string_t;
  10419. using internal_binary_t = typename BasicJsonType::internal_binary_t;
  10420. public:
  10421. /*!
  10422. @brief create a binary writer
  10423. @param[in] adapter output adapter to write to
  10424. */
  10425. explicit binary_writer(output_adapter_t<CharType> adapter) : oa(adapter)
  10426. {
  10427. assert(oa);
  10428. }
  10429. /*!
  10430. @param[in] j JSON value to serialize
  10431. @pre j.type() == value_t::object
  10432. */
  10433. void write_bson(const BasicJsonType& j)
  10434. {
  10435. switch (j.type())
  10436. {
  10437. case value_t::object:
  10438. {
  10439. write_bson_object(*j.m_value.object);
  10440. break;
  10441. }
  10442. default:
  10443. {
  10444. JSON_THROW(type_error::create(317, "to serialize to BSON, top-level type must be object, but is " + std::string(j.type_name())));
  10445. }
  10446. }
  10447. }
  10448. /*!
  10449. @param[in] j JSON value to serialize
  10450. */
  10451. void write_cbor(const BasicJsonType& j)
  10452. {
  10453. switch (j.type())
  10454. {
  10455. case value_t::null:
  10456. {
  10457. oa->write_character(to_char_type(0xF6));
  10458. break;
  10459. }
  10460. case value_t::boolean:
  10461. {
  10462. oa->write_character(j.m_value.boolean
  10463. ? to_char_type(0xF5)
  10464. : to_char_type(0xF4));
  10465. break;
  10466. }
  10467. case value_t::number_integer:
  10468. {
  10469. if (j.m_value.number_integer >= 0)
  10470. {
  10471. // CBOR does not differentiate between positive signed
  10472. // integers and unsigned integers. Therefore, we used the
  10473. // code from the value_t::number_unsigned case here.
  10474. if (j.m_value.number_integer <= 0x17)
  10475. {
  10476. write_number(static_cast<std::uint8_t>(j.m_value.number_integer));
  10477. }
  10478. else if (j.m_value.number_integer <= (std::numeric_limits<std::uint8_t>::max)())
  10479. {
  10480. oa->write_character(to_char_type(0x18));
  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::uint16_t>::max)())
  10484. {
  10485. oa->write_character(to_char_type(0x19));
  10486. write_number(static_cast<std::uint16_t>(j.m_value.number_integer));
  10487. }
  10488. else if (j.m_value.number_integer <= (std::numeric_limits<std::uint32_t>::max)())
  10489. {
  10490. oa->write_character(to_char_type(0x1A));
  10491. write_number(static_cast<std::uint32_t>(j.m_value.number_integer));
  10492. }
  10493. else
  10494. {
  10495. oa->write_character(to_char_type(0x1B));
  10496. write_number(static_cast<std::uint64_t>(j.m_value.number_integer));
  10497. }
  10498. }
  10499. else
  10500. {
  10501. // The conversions below encode the sign in the first
  10502. // byte, and the value is converted to a positive number.
  10503. const auto positive_number = -1 - j.m_value.number_integer;
  10504. if (j.m_value.number_integer >= -24)
  10505. {
  10506. write_number(static_cast<std::uint8_t>(0x20 + positive_number));
  10507. }
  10508. else if (positive_number <= (std::numeric_limits<std::uint8_t>::max)())
  10509. {
  10510. oa->write_character(to_char_type(0x38));
  10511. write_number(static_cast<std::uint8_t>(positive_number));
  10512. }
  10513. else if (positive_number <= (std::numeric_limits<std::uint16_t>::max)())
  10514. {
  10515. oa->write_character(to_char_type(0x39));
  10516. write_number(static_cast<std::uint16_t>(positive_number));
  10517. }
  10518. else if (positive_number <= (std::numeric_limits<std::uint32_t>::max)())
  10519. {
  10520. oa->write_character(to_char_type(0x3A));
  10521. write_number(static_cast<std::uint32_t>(positive_number));
  10522. }
  10523. else
  10524. {
  10525. oa->write_character(to_char_type(0x3B));
  10526. write_number(static_cast<std::uint64_t>(positive_number));
  10527. }
  10528. }
  10529. break;
  10530. }
  10531. case value_t::number_unsigned:
  10532. {
  10533. if (j.m_value.number_unsigned <= 0x17)
  10534. {
  10535. write_number(static_cast<std::uint8_t>(j.m_value.number_unsigned));
  10536. }
  10537. else if (j.m_value.number_unsigned <= (std::numeric_limits<std::uint8_t>::max)())
  10538. {
  10539. oa->write_character(to_char_type(0x18));
  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::uint16_t>::max)())
  10543. {
  10544. oa->write_character(to_char_type(0x19));
  10545. write_number(static_cast<std::uint16_t>(j.m_value.number_unsigned));
  10546. }
  10547. else if (j.m_value.number_unsigned <= (std::numeric_limits<std::uint32_t>::max)())
  10548. {
  10549. oa->write_character(to_char_type(0x1A));
  10550. write_number(static_cast<std::uint32_t>(j.m_value.number_unsigned));
  10551. }
  10552. else
  10553. {
  10554. oa->write_character(to_char_type(0x1B));
  10555. write_number(static_cast<std::uint64_t>(j.m_value.number_unsigned));
  10556. }
  10557. break;
  10558. }
  10559. case value_t::number_float:
  10560. {
  10561. oa->write_character(get_cbor_float_prefix(j.m_value.number_float));
  10562. write_number(j.m_value.number_float);
  10563. break;
  10564. }
  10565. case value_t::string:
  10566. {
  10567. // step 1: write control byte and the string length
  10568. const auto N = j.m_value.string->size();
  10569. if (N <= 0x17)
  10570. {
  10571. write_number(static_cast<std::uint8_t>(0x60 + N));
  10572. }
  10573. else if (N <= (std::numeric_limits<std::uint8_t>::max)())
  10574. {
  10575. oa->write_character(to_char_type(0x78));
  10576. write_number(static_cast<std::uint8_t>(N));
  10577. }
  10578. else if (N <= (std::numeric_limits<std::uint16_t>::max)())
  10579. {
  10580. oa->write_character(to_char_type(0x79));
  10581. write_number(static_cast<std::uint16_t>(N));
  10582. }
  10583. else if (N <= (std::numeric_limits<std::uint32_t>::max)())
  10584. {
  10585. oa->write_character(to_char_type(0x7A));
  10586. write_number(static_cast<std::uint32_t>(N));
  10587. }
  10588. // LCOV_EXCL_START
  10589. else if (N <= (std::numeric_limits<std::uint64_t>::max)())
  10590. {
  10591. oa->write_character(to_char_type(0x7B));
  10592. write_number(static_cast<std::uint64_t>(N));
  10593. }
  10594. // LCOV_EXCL_STOP
  10595. // step 2: write the string
  10596. oa->write_characters(
  10597. reinterpret_cast<const CharType*>(j.m_value.string->c_str()),
  10598. j.m_value.string->size());
  10599. break;
  10600. }
  10601. case value_t::array:
  10602. {
  10603. // step 1: write control byte and the array size
  10604. const auto N = j.m_value.array->size();
  10605. if (N <= 0x17)
  10606. {
  10607. write_number(static_cast<std::uint8_t>(0x80 + N));
  10608. }
  10609. else if (N <= (std::numeric_limits<std::uint8_t>::max)())
  10610. {
  10611. oa->write_character(to_char_type(0x98));
  10612. write_number(static_cast<std::uint8_t>(N));
  10613. }
  10614. else if (N <= (std::numeric_limits<std::uint16_t>::max)())
  10615. {
  10616. oa->write_character(to_char_type(0x99));
  10617. write_number(static_cast<std::uint16_t>(N));
  10618. }
  10619. else if (N <= (std::numeric_limits<std::uint32_t>::max)())
  10620. {
  10621. oa->write_character(to_char_type(0x9A));
  10622. write_number(static_cast<std::uint32_t>(N));
  10623. }
  10624. // LCOV_EXCL_START
  10625. else if (N <= (std::numeric_limits<std::uint64_t>::max)())
  10626. {
  10627. oa->write_character(to_char_type(0x9B));
  10628. write_number(static_cast<std::uint64_t>(N));
  10629. }
  10630. // LCOV_EXCL_STOP
  10631. // step 2: write each element
  10632. for (const auto& el : *j.m_value.array)
  10633. {
  10634. write_cbor(el);
  10635. }
  10636. break;
  10637. }
  10638. case value_t::binary:
  10639. {
  10640. // step 1: write control byte and the binary array size
  10641. const auto N = j.m_value.binary->size();
  10642. if (N <= 0x17)
  10643. {
  10644. write_number(static_cast<std::uint8_t>(0x40 + N));
  10645. }
  10646. else if (N <= (std::numeric_limits<std::uint8_t>::max)())
  10647. {
  10648. oa->write_character(to_char_type(0x58));
  10649. write_number(static_cast<std::uint8_t>(N));
  10650. }
  10651. else if (N <= (std::numeric_limits<std::uint16_t>::max)())
  10652. {
  10653. oa->write_character(to_char_type(0x59));
  10654. write_number(static_cast<std::uint16_t>(N));
  10655. }
  10656. else if (N <= (std::numeric_limits<std::uint32_t>::max)())
  10657. {
  10658. oa->write_character(to_char_type(0x5A));
  10659. write_number(static_cast<std::uint32_t>(N));
  10660. }
  10661. // LCOV_EXCL_START
  10662. else if (N <= (std::numeric_limits<std::uint64_t>::max)())
  10663. {
  10664. oa->write_character(to_char_type(0x5B));
  10665. write_number(static_cast<std::uint64_t>(N));
  10666. }
  10667. // LCOV_EXCL_STOP
  10668. // step 2: write each element
  10669. oa->write_characters(
  10670. reinterpret_cast<const CharType*>(j.m_value.binary->data()),
  10671. N);
  10672. break;
  10673. }
  10674. case value_t::object:
  10675. {
  10676. // step 1: write control byte and the object size
  10677. const auto N = j.m_value.object->size();
  10678. if (N <= 0x17)
  10679. {
  10680. write_number(static_cast<std::uint8_t>(0xA0 + N));
  10681. }
  10682. else if (N <= (std::numeric_limits<std::uint8_t>::max)())
  10683. {
  10684. oa->write_character(to_char_type(0xB8));
  10685. write_number(static_cast<std::uint8_t>(N));
  10686. }
  10687. else if (N <= (std::numeric_limits<std::uint16_t>::max)())
  10688. {
  10689. oa->write_character(to_char_type(0xB9));
  10690. write_number(static_cast<std::uint16_t>(N));
  10691. }
  10692. else if (N <= (std::numeric_limits<std::uint32_t>::max)())
  10693. {
  10694. oa->write_character(to_char_type(0xBA));
  10695. write_number(static_cast<std::uint32_t>(N));
  10696. }
  10697. // LCOV_EXCL_START
  10698. else if (N <= (std::numeric_limits<std::uint64_t>::max)())
  10699. {
  10700. oa->write_character(to_char_type(0xBB));
  10701. write_number(static_cast<std::uint64_t>(N));
  10702. }
  10703. // LCOV_EXCL_STOP
  10704. // step 2: write each element
  10705. for (const auto& el : *j.m_value.object)
  10706. {
  10707. write_cbor(el.first);
  10708. write_cbor(el.second);
  10709. }
  10710. break;
  10711. }
  10712. default:
  10713. break;
  10714. }
  10715. }
  10716. /*!
  10717. @param[in] j JSON value to serialize
  10718. */
  10719. void write_msgpack(const BasicJsonType& j)
  10720. {
  10721. switch (j.type())
  10722. {
  10723. case value_t::null: // nil
  10724. {
  10725. oa->write_character(to_char_type(0xC0));
  10726. break;
  10727. }
  10728. case value_t::boolean: // true and false
  10729. {
  10730. oa->write_character(j.m_value.boolean
  10731. ? to_char_type(0xC3)
  10732. : to_char_type(0xC2));
  10733. break;
  10734. }
  10735. case value_t::number_integer:
  10736. {
  10737. if (j.m_value.number_integer >= 0)
  10738. {
  10739. // MessagePack does not differentiate between positive
  10740. // signed integers and unsigned integers. Therefore, we used
  10741. // the code from the value_t::number_unsigned case here.
  10742. if (j.m_value.number_unsigned < 128)
  10743. {
  10744. // positive fixnum
  10745. write_number(static_cast<std::uint8_t>(j.m_value.number_integer));
  10746. }
  10747. else if (j.m_value.number_unsigned <= (std::numeric_limits<std::uint8_t>::max)())
  10748. {
  10749. // uint 8
  10750. oa->write_character(to_char_type(0xCC));
  10751. write_number(static_cast<std::uint8_t>(j.m_value.number_integer));
  10752. }
  10753. else if (j.m_value.number_unsigned <= (std::numeric_limits<std::uint16_t>::max)())
  10754. {
  10755. // uint 16
  10756. oa->write_character(to_char_type(0xCD));
  10757. write_number(static_cast<std::uint16_t>(j.m_value.number_integer));
  10758. }
  10759. else if (j.m_value.number_unsigned <= (std::numeric_limits<std::uint32_t>::max)())
  10760. {
  10761. // uint 32
  10762. oa->write_character(to_char_type(0xCE));
  10763. write_number(static_cast<std::uint32_t>(j.m_value.number_integer));
  10764. }
  10765. else if (j.m_value.number_unsigned <= (std::numeric_limits<std::uint64_t>::max)())
  10766. {
  10767. // uint 64
  10768. oa->write_character(to_char_type(0xCF));
  10769. write_number(static_cast<std::uint64_t>(j.m_value.number_integer));
  10770. }
  10771. }
  10772. else
  10773. {
  10774. if (j.m_value.number_integer >= -32)
  10775. {
  10776. // negative fixnum
  10777. write_number(static_cast<std::int8_t>(j.m_value.number_integer));
  10778. }
  10779. else if (j.m_value.number_integer >= (std::numeric_limits<std::int8_t>::min)() and
  10780. j.m_value.number_integer <= (std::numeric_limits<std::int8_t>::max)())
  10781. {
  10782. // int 8
  10783. oa->write_character(to_char_type(0xD0));
  10784. write_number(static_cast<std::int8_t>(j.m_value.number_integer));
  10785. }
  10786. else if (j.m_value.number_integer >= (std::numeric_limits<std::int16_t>::min)() and
  10787. j.m_value.number_integer <= (std::numeric_limits<std::int16_t>::max)())
  10788. {
  10789. // int 16
  10790. oa->write_character(to_char_type(0xD1));
  10791. write_number(static_cast<std::int16_t>(j.m_value.number_integer));
  10792. }
  10793. else if (j.m_value.number_integer >= (std::numeric_limits<std::int32_t>::min)() and
  10794. j.m_value.number_integer <= (std::numeric_limits<std::int32_t>::max)())
  10795. {
  10796. // int 32
  10797. oa->write_character(to_char_type(0xD2));
  10798. write_number(static_cast<std::int32_t>(j.m_value.number_integer));
  10799. }
  10800. else if (j.m_value.number_integer >= (std::numeric_limits<std::int64_t>::min)() and
  10801. j.m_value.number_integer <= (std::numeric_limits<std::int64_t>::max)())
  10802. {
  10803. // int 64
  10804. oa->write_character(to_char_type(0xD3));
  10805. write_number(static_cast<std::int64_t>(j.m_value.number_integer));
  10806. }
  10807. }
  10808. break;
  10809. }
  10810. case value_t::number_unsigned:
  10811. {
  10812. if (j.m_value.number_unsigned < 128)
  10813. {
  10814. // positive fixnum
  10815. write_number(static_cast<std::uint8_t>(j.m_value.number_integer));
  10816. }
  10817. else if (j.m_value.number_unsigned <= (std::numeric_limits<std::uint8_t>::max)())
  10818. {
  10819. // uint 8
  10820. oa->write_character(to_char_type(0xCC));
  10821. write_number(static_cast<std::uint8_t>(j.m_value.number_integer));
  10822. }
  10823. else if (j.m_value.number_unsigned <= (std::numeric_limits<std::uint16_t>::max)())
  10824. {
  10825. // uint 16
  10826. oa->write_character(to_char_type(0xCD));
  10827. write_number(static_cast<std::uint16_t>(j.m_value.number_integer));
  10828. }
  10829. else if (j.m_value.number_unsigned <= (std::numeric_limits<std::uint32_t>::max)())
  10830. {
  10831. // uint 32
  10832. oa->write_character(to_char_type(0xCE));
  10833. write_number(static_cast<std::uint32_t>(j.m_value.number_integer));
  10834. }
  10835. else if (j.m_value.number_unsigned <= (std::numeric_limits<std::uint64_t>::max)())
  10836. {
  10837. // uint 64
  10838. oa->write_character(to_char_type(0xCF));
  10839. write_number(static_cast<std::uint64_t>(j.m_value.number_integer));
  10840. }
  10841. break;
  10842. }
  10843. case value_t::number_float:
  10844. {
  10845. oa->write_character(get_msgpack_float_prefix(j.m_value.number_float));
  10846. write_number(j.m_value.number_float);
  10847. break;
  10848. }
  10849. case value_t::string:
  10850. {
  10851. // step 1: write control byte and the string length
  10852. const auto N = j.m_value.string->size();
  10853. if (N <= 31)
  10854. {
  10855. // fixstr
  10856. write_number(static_cast<std::uint8_t>(0xA0 | N));
  10857. }
  10858. else if (N <= (std::numeric_limits<std::uint8_t>::max)())
  10859. {
  10860. // str 8
  10861. oa->write_character(to_char_type(0xD9));
  10862. write_number(static_cast<std::uint8_t>(N));
  10863. }
  10864. else if (N <= (std::numeric_limits<std::uint16_t>::max)())
  10865. {
  10866. // str 16
  10867. oa->write_character(to_char_type(0xDA));
  10868. write_number(static_cast<std::uint16_t>(N));
  10869. }
  10870. else if (N <= (std::numeric_limits<std::uint32_t>::max)())
  10871. {
  10872. // str 32
  10873. oa->write_character(to_char_type(0xDB));
  10874. write_number(static_cast<std::uint32_t>(N));
  10875. }
  10876. // step 2: write the string
  10877. oa->write_characters(
  10878. reinterpret_cast<const CharType*>(j.m_value.string->c_str()),
  10879. j.m_value.string->size());
  10880. break;
  10881. }
  10882. case value_t::array:
  10883. {
  10884. // step 1: write control byte and the array size
  10885. const auto N = j.m_value.array->size();
  10886. if (N <= 15)
  10887. {
  10888. // fixarray
  10889. write_number(static_cast<std::uint8_t>(0x90 | N));
  10890. }
  10891. else if (N <= (std::numeric_limits<std::uint16_t>::max)())
  10892. {
  10893. // array 16
  10894. oa->write_character(to_char_type(0xDC));
  10895. write_number(static_cast<std::uint16_t>(N));
  10896. }
  10897. else if (N <= (std::numeric_limits<std::uint32_t>::max)())
  10898. {
  10899. // array 32
  10900. oa->write_character(to_char_type(0xDD));
  10901. write_number(static_cast<std::uint32_t>(N));
  10902. }
  10903. // step 2: write each element
  10904. for (const auto& el : *j.m_value.array)
  10905. {
  10906. write_msgpack(el);
  10907. }
  10908. break;
  10909. }
  10910. case value_t::binary:
  10911. {
  10912. // step 0: determine if the binary type has a set subtype to
  10913. // determine whether or not to use the ext or fixext types
  10914. const bool use_ext = j.m_value.binary->has_subtype;
  10915. // step 1: write control byte and the byte string length
  10916. const auto N = j.m_value.binary->size();
  10917. if (N <= (std::numeric_limits<std::uint8_t>::max)())
  10918. {
  10919. std::uint8_t output_type;
  10920. bool fixed = true;
  10921. if (use_ext)
  10922. {
  10923. switch (N)
  10924. {
  10925. case 1:
  10926. output_type = 0xD4; // fixext 1
  10927. break;
  10928. case 2:
  10929. output_type = 0xD5; // fixext 2
  10930. break;
  10931. case 4:
  10932. output_type = 0xD6; // fixext 4
  10933. break;
  10934. case 8:
  10935. output_type = 0xD7; // fixext 8
  10936. break;
  10937. case 16:
  10938. output_type = 0xD8; // fixext 16
  10939. break;
  10940. default:
  10941. output_type = 0xC7; // ext 8
  10942. fixed = false;
  10943. break;
  10944. }
  10945. }
  10946. else
  10947. {
  10948. output_type = 0xC4; // bin 8
  10949. fixed = false;
  10950. }
  10951. oa->write_character(to_char_type(output_type));
  10952. if (not fixed)
  10953. {
  10954. write_number(static_cast<std::uint8_t>(N));
  10955. }
  10956. }
  10957. else if (N <= (std::numeric_limits<std::uint16_t>::max)())
  10958. {
  10959. std::uint8_t output_type;
  10960. if (use_ext)
  10961. {
  10962. output_type = 0xC8; // ext 16
  10963. }
  10964. else
  10965. {
  10966. output_type = 0xC5; // bin 16
  10967. }
  10968. oa->write_character(to_char_type(output_type));
  10969. write_number(static_cast<std::uint16_t>(N));
  10970. }
  10971. else if (N <= (std::numeric_limits<std::uint32_t>::max)())
  10972. {
  10973. std::uint8_t output_type;
  10974. if (use_ext)
  10975. {
  10976. output_type = 0xC9; // ext 32
  10977. }
  10978. else
  10979. {
  10980. output_type = 0xC6; // bin 32
  10981. }
  10982. oa->write_character(to_char_type(output_type));
  10983. write_number(static_cast<std::uint32_t>(N));
  10984. }
  10985. // step 1.5: if this is an ext type, write the subtype
  10986. if (use_ext)
  10987. {
  10988. write_number(j.m_value.binary->subtype);
  10989. }
  10990. // step 2: write the byte string
  10991. oa->write_characters(
  10992. reinterpret_cast<const CharType*>(j.m_value.binary->data()),
  10993. N);
  10994. break;
  10995. }
  10996. case value_t::object:
  10997. {
  10998. // step 1: write control byte and the object size
  10999. const auto N = j.m_value.object->size();
  11000. if (N <= 15)
  11001. {
  11002. // fixmap
  11003. write_number(static_cast<std::uint8_t>(0x80 | (N & 0xF)));
  11004. }
  11005. else if (N <= (std::numeric_limits<std::uint16_t>::max)())
  11006. {
  11007. // map 16
  11008. oa->write_character(to_char_type(0xDE));
  11009. write_number(static_cast<std::uint16_t>(N));
  11010. }
  11011. else if (N <= (std::numeric_limits<std::uint32_t>::max)())
  11012. {
  11013. // map 32
  11014. oa->write_character(to_char_type(0xDF));
  11015. write_number(static_cast<std::uint32_t>(N));
  11016. }
  11017. // step 2: write each element
  11018. for (const auto& el : *j.m_value.object)
  11019. {
  11020. write_msgpack(el.first);
  11021. write_msgpack(el.second);
  11022. }
  11023. break;
  11024. }
  11025. default:
  11026. break;
  11027. }
  11028. }
  11029. /*!
  11030. @param[in] j JSON value to serialize
  11031. @param[in] use_count whether to use '#' prefixes (optimized format)
  11032. @param[in] use_type whether to use '$' prefixes (optimized format)
  11033. @param[in] add_prefix whether prefixes need to be used for this value
  11034. */
  11035. void write_ubjson(const BasicJsonType& j, const bool use_count,
  11036. const bool use_type, const bool add_prefix = true)
  11037. {
  11038. switch (j.type())
  11039. {
  11040. case value_t::null:
  11041. {
  11042. if (add_prefix)
  11043. {
  11044. oa->write_character(to_char_type('Z'));
  11045. }
  11046. break;
  11047. }
  11048. case value_t::boolean:
  11049. {
  11050. if (add_prefix)
  11051. {
  11052. oa->write_character(j.m_value.boolean
  11053. ? to_char_type('T')
  11054. : to_char_type('F'));
  11055. }
  11056. break;
  11057. }
  11058. case value_t::number_integer:
  11059. {
  11060. write_number_with_ubjson_prefix(j.m_value.number_integer, add_prefix);
  11061. break;
  11062. }
  11063. case value_t::number_unsigned:
  11064. {
  11065. write_number_with_ubjson_prefix(j.m_value.number_unsigned, add_prefix);
  11066. break;
  11067. }
  11068. case value_t::number_float:
  11069. {
  11070. write_number_with_ubjson_prefix(j.m_value.number_float, add_prefix);
  11071. break;
  11072. }
  11073. case value_t::string:
  11074. {
  11075. if (add_prefix)
  11076. {
  11077. oa->write_character(to_char_type('S'));
  11078. }
  11079. write_number_with_ubjson_prefix(j.m_value.string->size(), true);
  11080. oa->write_characters(
  11081. reinterpret_cast<const CharType*>(j.m_value.string->c_str()),
  11082. j.m_value.string->size());
  11083. break;
  11084. }
  11085. case value_t::array:
  11086. {
  11087. if (add_prefix)
  11088. {
  11089. oa->write_character(to_char_type('['));
  11090. }
  11091. bool prefix_required = true;
  11092. if (use_type and not j.m_value.array->empty())
  11093. {
  11094. assert(use_count);
  11095. const CharType first_prefix = ubjson_prefix(j.front());
  11096. const bool same_prefix = std::all_of(j.begin() + 1, j.end(),
  11097. [this, first_prefix](const BasicJsonType & v)
  11098. {
  11099. return ubjson_prefix(v) == first_prefix;
  11100. });
  11101. if (same_prefix)
  11102. {
  11103. prefix_required = false;
  11104. oa->write_character(to_char_type('$'));
  11105. oa->write_character(first_prefix);
  11106. }
  11107. }
  11108. if (use_count)
  11109. {
  11110. oa->write_character(to_char_type('#'));
  11111. write_number_with_ubjson_prefix(j.m_value.array->size(), true);
  11112. }
  11113. for (const auto& el : *j.m_value.array)
  11114. {
  11115. write_ubjson(el, use_count, use_type, prefix_required);
  11116. }
  11117. if (not use_count)
  11118. {
  11119. oa->write_character(to_char_type(']'));
  11120. }
  11121. break;
  11122. }
  11123. case value_t::binary:
  11124. {
  11125. if (add_prefix)
  11126. {
  11127. oa->write_character(to_char_type('['));
  11128. }
  11129. if (use_type and not j.m_value.binary->empty())
  11130. {
  11131. assert(use_count);
  11132. oa->write_character(to_char_type('$'));
  11133. oa->write_character('U');
  11134. }
  11135. if (use_count)
  11136. {
  11137. oa->write_character(to_char_type('#'));
  11138. write_number_with_ubjson_prefix(j.m_value.binary->size(), true);
  11139. }
  11140. if (use_type)
  11141. {
  11142. oa->write_characters(
  11143. reinterpret_cast<const CharType*>(j.m_value.binary->data()),
  11144. j.m_value.binary->size());
  11145. }
  11146. else
  11147. {
  11148. for (size_t i = 0; i < j.m_value.binary->size(); ++i)
  11149. {
  11150. oa->write_character(to_char_type('U'));
  11151. oa->write_character(j.m_value.binary->data()[i]);
  11152. }
  11153. }
  11154. if (not use_count)
  11155. {
  11156. oa->write_character(to_char_type(']'));
  11157. }
  11158. break;
  11159. }
  11160. case value_t::object:
  11161. {
  11162. if (add_prefix)
  11163. {
  11164. oa->write_character(to_char_type('{'));
  11165. }
  11166. bool prefix_required = true;
  11167. if (use_type and not j.m_value.object->empty())
  11168. {
  11169. assert(use_count);
  11170. const CharType first_prefix = ubjson_prefix(j.front());
  11171. const bool same_prefix = std::all_of(j.begin(), j.end(),
  11172. [this, first_prefix](const BasicJsonType & v)
  11173. {
  11174. return ubjson_prefix(v) == first_prefix;
  11175. });
  11176. if (same_prefix)
  11177. {
  11178. prefix_required = false;
  11179. oa->write_character(to_char_type('$'));
  11180. oa->write_character(first_prefix);
  11181. }
  11182. }
  11183. if (use_count)
  11184. {
  11185. oa->write_character(to_char_type('#'));
  11186. write_number_with_ubjson_prefix(j.m_value.object->size(), true);
  11187. }
  11188. for (const auto& el : *j.m_value.object)
  11189. {
  11190. write_number_with_ubjson_prefix(el.first.size(), true);
  11191. oa->write_characters(
  11192. reinterpret_cast<const CharType*>(el.first.c_str()),
  11193. el.first.size());
  11194. write_ubjson(el.second, use_count, use_type, prefix_required);
  11195. }
  11196. if (not use_count)
  11197. {
  11198. oa->write_character(to_char_type('}'));
  11199. }
  11200. break;
  11201. }
  11202. default:
  11203. break;
  11204. }
  11205. }
  11206. private:
  11207. //////////
  11208. // BSON //
  11209. //////////
  11210. /*!
  11211. @return The size of a BSON document entry header, including the id marker
  11212. and the entry name size (and its null-terminator).
  11213. */
  11214. static std::size_t calc_bson_entry_header_size(const string_t& name)
  11215. {
  11216. const auto it = name.find(static_cast<typename string_t::value_type>(0));
  11217. if (JSON_HEDLEY_UNLIKELY(it != BasicJsonType::string_t::npos))
  11218. {
  11219. JSON_THROW(out_of_range::create(409,
  11220. "BSON key cannot contain code point U+0000 (at byte " + std::to_string(it) + ")"));
  11221. }
  11222. return /*id*/ 1ul + name.size() + /*zero-terminator*/1u;
  11223. }
  11224. /*!
  11225. @brief Writes the given @a element_type and @a name to the output adapter
  11226. */
  11227. void write_bson_entry_header(const string_t& name,
  11228. const std::uint8_t element_type)
  11229. {
  11230. oa->write_character(to_char_type(element_type)); // boolean
  11231. oa->write_characters(
  11232. reinterpret_cast<const CharType*>(name.c_str()),
  11233. name.size() + 1u);
  11234. }
  11235. /*!
  11236. @brief Writes a BSON element with key @a name and boolean value @a value
  11237. */
  11238. void write_bson_boolean(const string_t& name,
  11239. const bool value)
  11240. {
  11241. write_bson_entry_header(name, 0x08);
  11242. oa->write_character(value ? to_char_type(0x01) : to_char_type(0x00));
  11243. }
  11244. /*!
  11245. @brief Writes a BSON element with key @a name and double value @a value
  11246. */
  11247. void write_bson_double(const string_t& name,
  11248. const double value)
  11249. {
  11250. write_bson_entry_header(name, 0x01);
  11251. write_number<double, true>(value);
  11252. }
  11253. /*!
  11254. @return The size of the BSON-encoded string in @a value
  11255. */
  11256. static std::size_t calc_bson_string_size(const string_t& value)
  11257. {
  11258. return sizeof(std::int32_t) + value.size() + 1ul;
  11259. }
  11260. /*!
  11261. @brief Writes a BSON element with key @a name and string value @a value
  11262. */
  11263. void write_bson_string(const string_t& name,
  11264. const string_t& value)
  11265. {
  11266. write_bson_entry_header(name, 0x02);
  11267. write_number<std::int32_t, true>(static_cast<std::int32_t>(value.size() + 1ul));
  11268. oa->write_characters(
  11269. reinterpret_cast<const CharType*>(value.c_str()),
  11270. value.size() + 1);
  11271. }
  11272. /*!
  11273. @brief Writes a BSON element with key @a name and null value
  11274. */
  11275. void write_bson_null(const string_t& name)
  11276. {
  11277. write_bson_entry_header(name, 0x0A);
  11278. }
  11279. /*!
  11280. @return The size of the BSON-encoded integer @a value
  11281. */
  11282. static std::size_t calc_bson_integer_size(const std::int64_t value)
  11283. {
  11284. return (std::numeric_limits<std::int32_t>::min)() <= value and value <= (std::numeric_limits<std::int32_t>::max)()
  11285. ? sizeof(std::int32_t)
  11286. : sizeof(std::int64_t);
  11287. }
  11288. /*!
  11289. @brief Writes a BSON element with key @a name and integer @a value
  11290. */
  11291. void write_bson_integer(const string_t& name,
  11292. const std::int64_t value)
  11293. {
  11294. if ((std::numeric_limits<std::int32_t>::min)() <= value and value <= (std::numeric_limits<std::int32_t>::max)())
  11295. {
  11296. write_bson_entry_header(name, 0x10); // int32
  11297. write_number<std::int32_t, true>(static_cast<std::int32_t>(value));
  11298. }
  11299. else
  11300. {
  11301. write_bson_entry_header(name, 0x12); // int64
  11302. write_number<std::int64_t, true>(static_cast<std::int64_t>(value));
  11303. }
  11304. }
  11305. /*!
  11306. @return The size of the BSON-encoded unsigned integer in @a j
  11307. */
  11308. static constexpr std::size_t calc_bson_unsigned_size(const std::uint64_t value) noexcept
  11309. {
  11310. return (value <= static_cast<std::uint64_t>((std::numeric_limits<std::int32_t>::max)()))
  11311. ? sizeof(std::int32_t)
  11312. : sizeof(std::int64_t);
  11313. }
  11314. /*!
  11315. @brief Writes a BSON element with key @a name and unsigned @a value
  11316. */
  11317. void write_bson_unsigned(const string_t& name,
  11318. const std::uint64_t value)
  11319. {
  11320. if (value <= static_cast<std::uint64_t>((std::numeric_limits<std::int32_t>::max)()))
  11321. {
  11322. write_bson_entry_header(name, 0x10 /* int32 */);
  11323. write_number<std::int32_t, true>(static_cast<std::int32_t>(value));
  11324. }
  11325. else if (value <= static_cast<std::uint64_t>((std::numeric_limits<std::int64_t>::max)()))
  11326. {
  11327. write_bson_entry_header(name, 0x12 /* int64 */);
  11328. write_number<std::int64_t, true>(static_cast<std::int64_t>(value));
  11329. }
  11330. else
  11331. {
  11332. JSON_THROW(out_of_range::create(407, "integer number " + std::to_string(value) + " cannot be represented by BSON as it does not fit int64"));
  11333. }
  11334. }
  11335. /*!
  11336. @brief Writes a BSON element with key @a name and object @a value
  11337. */
  11338. void write_bson_object_entry(const string_t& name,
  11339. const typename BasicJsonType::object_t& value)
  11340. {
  11341. write_bson_entry_header(name, 0x03); // object
  11342. write_bson_object(value);
  11343. }
  11344. /*!
  11345. @return The size of the BSON-encoded array @a value
  11346. */
  11347. static std::size_t calc_bson_array_size(const typename BasicJsonType::array_t& value)
  11348. {
  11349. std::size_t array_index = 0ul;
  11350. 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)
  11351. {
  11352. return result + calc_bson_element_size(std::to_string(array_index++), el);
  11353. });
  11354. return sizeof(std::int32_t) + embedded_document_size + 1ul;
  11355. }
  11356. /*!
  11357. @return The size of the BSON-encoded binary array @a value
  11358. */
  11359. static std::size_t calc_bson_binary_size(const typename BasicJsonType::internal_binary_t& value)
  11360. {
  11361. return sizeof(std::int32_t) + value.size() + 1ul;
  11362. }
  11363. /*!
  11364. @brief Writes a BSON element with key @a name and array @a value
  11365. */
  11366. void write_bson_array(const string_t& name,
  11367. const typename BasicJsonType::array_t& value)
  11368. {
  11369. write_bson_entry_header(name, 0x04); // array
  11370. write_number<std::int32_t, true>(static_cast<std::int32_t>(calc_bson_array_size(value)));
  11371. std::size_t array_index = 0ul;
  11372. for (const auto& el : value)
  11373. {
  11374. write_bson_element(std::to_string(array_index++), el);
  11375. }
  11376. oa->write_character(to_char_type(0x00));
  11377. }
  11378. /*!
  11379. @brief Writes a BSON element with key @a name and binary value @a value
  11380. */
  11381. void write_bson_binary(const string_t& name,
  11382. const internal_binary_t& value)
  11383. {
  11384. write_bson_entry_header(name, 0x05);
  11385. write_number<std::int32_t, true>(static_cast<std::int32_t>(value.size()));
  11386. std::uint8_t subtype = 0x00; // Generic Binary Subtype
  11387. if (value.has_subtype)
  11388. {
  11389. subtype = value.subtype;
  11390. }
  11391. write_number(subtype);
  11392. oa->write_characters(
  11393. reinterpret_cast<const CharType*>(value.data()),
  11394. value.size());
  11395. }
  11396. /*!
  11397. @brief Calculates the size necessary to serialize the JSON value @a j with its @a name
  11398. @return The calculated size for the BSON document entry for @a j with the given @a name.
  11399. */
  11400. static std::size_t calc_bson_element_size(const string_t& name,
  11401. const BasicJsonType& j)
  11402. {
  11403. const auto header_size = calc_bson_entry_header_size(name);
  11404. switch (j.type())
  11405. {
  11406. case value_t::object:
  11407. return header_size + calc_bson_object_size(*j.m_value.object);
  11408. case value_t::array:
  11409. return header_size + calc_bson_array_size(*j.m_value.array);
  11410. case value_t::binary:
  11411. return header_size + calc_bson_binary_size(*j.m_value.binary);
  11412. case value_t::boolean:
  11413. return header_size + 1ul;
  11414. case value_t::number_float:
  11415. return header_size + 8ul;
  11416. case value_t::number_integer:
  11417. return header_size + calc_bson_integer_size(j.m_value.number_integer);
  11418. case value_t::number_unsigned:
  11419. return header_size + calc_bson_unsigned_size(j.m_value.number_unsigned);
  11420. case value_t::string:
  11421. return header_size + calc_bson_string_size(*j.m_value.string);
  11422. case value_t::null:
  11423. return header_size + 0ul;
  11424. // LCOV_EXCL_START
  11425. default:
  11426. assert(false);
  11427. return 0ul;
  11428. // LCOV_EXCL_STOP
  11429. }
  11430. }
  11431. /*!
  11432. @brief Serializes the JSON value @a j to BSON and associates it with the
  11433. key @a name.
  11434. @param name The name to associate with the JSON entity @a j within the
  11435. current BSON document
  11436. @return The size of the BSON entry
  11437. */
  11438. void write_bson_element(const string_t& name,
  11439. const BasicJsonType& j)
  11440. {
  11441. switch (j.type())
  11442. {
  11443. case value_t::object:
  11444. return write_bson_object_entry(name, *j.m_value.object);
  11445. case value_t::array:
  11446. return write_bson_array(name, *j.m_value.array);
  11447. case value_t::binary:
  11448. return write_bson_binary(name, *j.m_value.binary);
  11449. case value_t::boolean:
  11450. return write_bson_boolean(name, j.m_value.boolean);
  11451. case value_t::number_float:
  11452. return write_bson_double(name, j.m_value.number_float);
  11453. case value_t::number_integer:
  11454. return write_bson_integer(name, j.m_value.number_integer);
  11455. case value_t::number_unsigned:
  11456. return write_bson_unsigned(name, j.m_value.number_unsigned);
  11457. case value_t::string:
  11458. return write_bson_string(name, *j.m_value.string);
  11459. case value_t::null:
  11460. return write_bson_null(name);
  11461. // LCOV_EXCL_START
  11462. default:
  11463. assert(false);
  11464. return;
  11465. // LCOV_EXCL_STOP
  11466. }
  11467. }
  11468. /*!
  11469. @brief Calculates the size of the BSON serialization of the given
  11470. JSON-object @a j.
  11471. @param[in] j JSON value to serialize
  11472. @pre j.type() == value_t::object
  11473. */
  11474. static std::size_t calc_bson_object_size(const typename BasicJsonType::object_t& value)
  11475. {
  11476. std::size_t document_size = std::accumulate(value.begin(), value.end(), std::size_t(0),
  11477. [](size_t result, const typename BasicJsonType::object_t::value_type & el)
  11478. {
  11479. return result += calc_bson_element_size(el.first, el.second);
  11480. });
  11481. return sizeof(std::int32_t) + document_size + 1ul;
  11482. }
  11483. /*!
  11484. @param[in] j JSON value to serialize
  11485. @pre j.type() == value_t::object
  11486. */
  11487. void write_bson_object(const typename BasicJsonType::object_t& value)
  11488. {
  11489. write_number<std::int32_t, true>(static_cast<std::int32_t>(calc_bson_object_size(value)));
  11490. for (const auto& el : value)
  11491. {
  11492. write_bson_element(el.first, el.second);
  11493. }
  11494. oa->write_character(to_char_type(0x00));
  11495. }
  11496. //////////
  11497. // CBOR //
  11498. //////////
  11499. static constexpr CharType get_cbor_float_prefix(float /*unused*/)
  11500. {
  11501. return to_char_type(0xFA); // Single-Precision Float
  11502. }
  11503. static constexpr CharType get_cbor_float_prefix(double /*unused*/)
  11504. {
  11505. return to_char_type(0xFB); // Double-Precision Float
  11506. }
  11507. /////////////
  11508. // MsgPack //
  11509. /////////////
  11510. static constexpr CharType get_msgpack_float_prefix(float /*unused*/)
  11511. {
  11512. return to_char_type(0xCA); // float 32
  11513. }
  11514. static constexpr CharType get_msgpack_float_prefix(double /*unused*/)
  11515. {
  11516. return to_char_type(0xCB); // float 64
  11517. }
  11518. ////////////
  11519. // UBJSON //
  11520. ////////////
  11521. // UBJSON: write number (floating point)
  11522. template<typename NumberType, typename std::enable_if<
  11523. std::is_floating_point<NumberType>::value, int>::type = 0>
  11524. void write_number_with_ubjson_prefix(const NumberType n,
  11525. const bool add_prefix)
  11526. {
  11527. if (add_prefix)
  11528. {
  11529. oa->write_character(get_ubjson_float_prefix(n));
  11530. }
  11531. write_number(n);
  11532. }
  11533. // UBJSON: write number (unsigned integer)
  11534. template<typename NumberType, typename std::enable_if<
  11535. std::is_unsigned<NumberType>::value, int>::type = 0>
  11536. void write_number_with_ubjson_prefix(const NumberType n,
  11537. const bool add_prefix)
  11538. {
  11539. if (n <= static_cast<std::uint64_t>((std::numeric_limits<std::int8_t>::max)()))
  11540. {
  11541. if (add_prefix)
  11542. {
  11543. oa->write_character(to_char_type('i')); // int8
  11544. }
  11545. write_number(static_cast<std::uint8_t>(n));
  11546. }
  11547. else if (n <= (std::numeric_limits<std::uint8_t>::max)())
  11548. {
  11549. if (add_prefix)
  11550. {
  11551. oa->write_character(to_char_type('U')); // uint8
  11552. }
  11553. write_number(static_cast<std::uint8_t>(n));
  11554. }
  11555. else if (n <= static_cast<std::uint64_t>((std::numeric_limits<std::int16_t>::max)()))
  11556. {
  11557. if (add_prefix)
  11558. {
  11559. oa->write_character(to_char_type('I')); // int16
  11560. }
  11561. write_number(static_cast<std::int16_t>(n));
  11562. }
  11563. else if (n <= static_cast<std::uint64_t>((std::numeric_limits<std::int32_t>::max)()))
  11564. {
  11565. if (add_prefix)
  11566. {
  11567. oa->write_character(to_char_type('l')); // int32
  11568. }
  11569. write_number(static_cast<std::int32_t>(n));
  11570. }
  11571. else if (n <= static_cast<std::uint64_t>((std::numeric_limits<std::int64_t>::max)()))
  11572. {
  11573. if (add_prefix)
  11574. {
  11575. oa->write_character(to_char_type('L')); // int64
  11576. }
  11577. write_number(static_cast<std::int64_t>(n));
  11578. }
  11579. else
  11580. {
  11581. JSON_THROW(out_of_range::create(407, "integer number " + std::to_string(n) + " cannot be represented by UBJSON as it does not fit int64"));
  11582. }
  11583. }
  11584. // UBJSON: write number (signed integer)
  11585. template<typename NumberType, typename std::enable_if<
  11586. std::is_signed<NumberType>::value and
  11587. not std::is_floating_point<NumberType>::value, int>::type = 0>
  11588. void write_number_with_ubjson_prefix(const NumberType n,
  11589. const bool add_prefix)
  11590. {
  11591. if ((std::numeric_limits<std::int8_t>::min)() <= n and n <= (std::numeric_limits<std::int8_t>::max)())
  11592. {
  11593. if (add_prefix)
  11594. {
  11595. oa->write_character(to_char_type('i')); // int8
  11596. }
  11597. write_number(static_cast<std::int8_t>(n));
  11598. }
  11599. 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)()))
  11600. {
  11601. if (add_prefix)
  11602. {
  11603. oa->write_character(to_char_type('U')); // uint8
  11604. }
  11605. write_number(static_cast<std::uint8_t>(n));
  11606. }
  11607. else if ((std::numeric_limits<std::int16_t>::min)() <= n and n <= (std::numeric_limits<std::int16_t>::max)())
  11608. {
  11609. if (add_prefix)
  11610. {
  11611. oa->write_character(to_char_type('I')); // int16
  11612. }
  11613. write_number(static_cast<std::int16_t>(n));
  11614. }
  11615. else if ((std::numeric_limits<std::int32_t>::min)() <= n and n <= (std::numeric_limits<std::int32_t>::max)())
  11616. {
  11617. if (add_prefix)
  11618. {
  11619. oa->write_character(to_char_type('l')); // int32
  11620. }
  11621. write_number(static_cast<std::int32_t>(n));
  11622. }
  11623. else if ((std::numeric_limits<std::int64_t>::min)() <= n and n <= (std::numeric_limits<std::int64_t>::max)())
  11624. {
  11625. if (add_prefix)
  11626. {
  11627. oa->write_character(to_char_type('L')); // int64
  11628. }
  11629. write_number(static_cast<std::int64_t>(n));
  11630. }
  11631. // LCOV_EXCL_START
  11632. else
  11633. {
  11634. JSON_THROW(out_of_range::create(407, "integer number " + std::to_string(n) + " cannot be represented by UBJSON as it does not fit int64"));
  11635. }
  11636. // LCOV_EXCL_STOP
  11637. }
  11638. /*!
  11639. @brief determine the type prefix of container values
  11640. @note This function does not need to be 100% accurate when it comes to
  11641. integer limits. In case a number exceeds the limits of int64_t,
  11642. this will be detected by a later call to function
  11643. write_number_with_ubjson_prefix. Therefore, we return 'L' for any
  11644. value that does not fit the previous limits.
  11645. */
  11646. CharType ubjson_prefix(const BasicJsonType& j) const noexcept
  11647. {
  11648. switch (j.type())
  11649. {
  11650. case value_t::null:
  11651. return 'Z';
  11652. case value_t::boolean:
  11653. return j.m_value.boolean ? 'T' : 'F';
  11654. case value_t::number_integer:
  11655. {
  11656. 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)())
  11657. {
  11658. return 'i';
  11659. }
  11660. 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)())
  11661. {
  11662. return 'U';
  11663. }
  11664. 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)())
  11665. {
  11666. return 'I';
  11667. }
  11668. 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)())
  11669. {
  11670. return 'l';
  11671. }
  11672. // no check and assume int64_t (see note above)
  11673. return 'L';
  11674. }
  11675. case value_t::number_unsigned:
  11676. {
  11677. if (j.m_value.number_unsigned <= static_cast<std::uint64_t>((std::numeric_limits<std::int8_t>::max)()))
  11678. {
  11679. return 'i';
  11680. }
  11681. if (j.m_value.number_unsigned <= static_cast<std::uint64_t>((std::numeric_limits<std::uint8_t>::max)()))
  11682. {
  11683. return 'U';
  11684. }
  11685. if (j.m_value.number_unsigned <= static_cast<std::uint64_t>((std::numeric_limits<std::int16_t>::max)()))
  11686. {
  11687. return 'I';
  11688. }
  11689. if (j.m_value.number_unsigned <= static_cast<std::uint64_t>((std::numeric_limits<std::int32_t>::max)()))
  11690. {
  11691. return 'l';
  11692. }
  11693. // no check and assume int64_t (see note above)
  11694. return 'L';
  11695. }
  11696. case value_t::number_float:
  11697. return get_ubjson_float_prefix(j.m_value.number_float);
  11698. case value_t::string:
  11699. return 'S';
  11700. case value_t::array: // fallthrough
  11701. case value_t::binary:
  11702. return '[';
  11703. case value_t::object:
  11704. return '{';
  11705. default: // discarded values
  11706. return 'N';
  11707. }
  11708. }
  11709. static constexpr CharType get_ubjson_float_prefix(float /*unused*/)
  11710. {
  11711. return 'd'; // float 32
  11712. }
  11713. static constexpr CharType get_ubjson_float_prefix(double /*unused*/)
  11714. {
  11715. return 'D'; // float 64
  11716. }
  11717. ///////////////////////
  11718. // Utility functions //
  11719. ///////////////////////
  11720. /*
  11721. @brief write a number to output input
  11722. @param[in] n number of type @a NumberType
  11723. @tparam NumberType the type of the number
  11724. @tparam OutputIsLittleEndian Set to true if output data is
  11725. required to be little endian
  11726. @note This function needs to respect the system's endianess, because bytes
  11727. in CBOR, MessagePack, and UBJSON are stored in network order (big
  11728. endian) and therefore need reordering on little endian systems.
  11729. */
  11730. template<typename NumberType, bool OutputIsLittleEndian = false>
  11731. void write_number(const NumberType n)
  11732. {
  11733. // step 1: write number to array of length NumberType
  11734. std::array<CharType, sizeof(NumberType)> vec;
  11735. std::memcpy(vec.data(), &n, sizeof(NumberType));
  11736. // step 2: write array to output (with possible reordering)
  11737. if (is_little_endian != OutputIsLittleEndian)
  11738. {
  11739. // reverse byte order prior to conversion if necessary
  11740. std::reverse(vec.begin(), vec.end());
  11741. }
  11742. oa->write_characters(vec.data(), sizeof(NumberType));
  11743. }
  11744. public:
  11745. // The following to_char_type functions are implement the conversion
  11746. // between uint8_t and CharType. In case CharType is not unsigned,
  11747. // such a conversion is required to allow values greater than 128.
  11748. // See <https://github.com/nlohmann/json/issues/1286> for a discussion.
  11749. template < typename C = CharType,
  11750. enable_if_t < std::is_signed<C>::value and std::is_signed<char>::value > * = nullptr >
  11751. static constexpr CharType to_char_type(std::uint8_t x) noexcept
  11752. {
  11753. return *reinterpret_cast<char*>(&x);
  11754. }
  11755. template < typename C = CharType,
  11756. enable_if_t < std::is_signed<C>::value and std::is_unsigned<char>::value > * = nullptr >
  11757. static CharType to_char_type(std::uint8_t x) noexcept
  11758. {
  11759. static_assert(sizeof(std::uint8_t) == sizeof(CharType), "size of CharType must be equal to std::uint8_t");
  11760. static_assert(std::is_trivial<CharType>::value, "CharType must be trivial");
  11761. CharType result;
  11762. std::memcpy(&result, &x, sizeof(x));
  11763. return result;
  11764. }
  11765. template<typename C = CharType,
  11766. enable_if_t<std::is_unsigned<C>::value>* = nullptr>
  11767. static constexpr CharType to_char_type(std::uint8_t x) noexcept
  11768. {
  11769. return x;
  11770. }
  11771. template < typename InputCharType, typename C = CharType,
  11772. enable_if_t <
  11773. std::is_signed<C>::value and
  11774. std::is_signed<char>::value and
  11775. std::is_same<char, typename std::remove_cv<InputCharType>::type>::value
  11776. > * = nullptr >
  11777. static constexpr CharType to_char_type(InputCharType x) noexcept
  11778. {
  11779. return x;
  11780. }
  11781. private:
  11782. /// whether we can assume little endianess
  11783. const bool is_little_endian = binary_reader<BasicJsonType>::little_endianess();
  11784. /// the output
  11785. output_adapter_t<CharType> oa = nullptr;
  11786. };
  11787. } // namespace detail
  11788. } // namespace nlohmann
  11789. // #include <nlohmann/detail/output/output_adapters.hpp>
  11790. // #include <nlohmann/detail/output/serializer.hpp>
  11791. #include <algorithm> // reverse, remove, fill, find, none_of
  11792. #include <array> // array
  11793. #include <cassert> // assert
  11794. #include <ciso646> // and, or
  11795. #include <clocale> // localeconv, lconv
  11796. #include <cmath> // labs, isfinite, isnan, signbit
  11797. #include <cstddef> // size_t, ptrdiff_t
  11798. #include <cstdint> // uint8_t
  11799. #include <cstdio> // snprintf
  11800. #include <limits> // numeric_limits
  11801. #include <string> // string
  11802. #include <type_traits> // is_same
  11803. #include <utility> // move
  11804. // #include <nlohmann/detail/conversions/to_chars.hpp>
  11805. #include <array> // array
  11806. #include <cassert> // assert
  11807. #include <ciso646> // or, and, not
  11808. #include <cmath> // signbit, isfinite
  11809. #include <cstdint> // intN_t, uintN_t
  11810. #include <cstring> // memcpy, memmove
  11811. #include <limits> // numeric_limits
  11812. #include <type_traits> // conditional
  11813. // #include <nlohmann/detail/macro_scope.hpp>
  11814. namespace nlohmann
  11815. {
  11816. namespace detail
  11817. {
  11818. /*!
  11819. @brief implements the Grisu2 algorithm for binary to decimal floating-point
  11820. conversion.
  11821. This implementation is a slightly modified version of the reference
  11822. implementation which may be obtained from
  11823. http://florian.loitsch.com/publications (bench.tar.gz).
  11824. The code is distributed under the MIT license, Copyright (c) 2009 Florian Loitsch.
  11825. For a detailed description of the algorithm see:
  11826. [1] Loitsch, "Printing Floating-Point Numbers Quickly and Accurately with
  11827. Integers", Proceedings of the ACM SIGPLAN 2010 Conference on Programming
  11828. Language Design and Implementation, PLDI 2010
  11829. [2] Burger, Dybvig, "Printing Floating-Point Numbers Quickly and Accurately",
  11830. Proceedings of the ACM SIGPLAN 1996 Conference on Programming Language
  11831. Design and Implementation, PLDI 1996
  11832. */
  11833. namespace dtoa_impl
  11834. {
  11835. template <typename Target, typename Source>
  11836. Target reinterpret_bits(const Source source)
  11837. {
  11838. static_assert(sizeof(Target) == sizeof(Source), "size mismatch");
  11839. Target target;
  11840. std::memcpy(&target, &source, sizeof(Source));
  11841. return target;
  11842. }
  11843. struct diyfp // f * 2^e
  11844. {
  11845. static constexpr int kPrecision = 64; // = q
  11846. std::uint64_t f = 0;
  11847. int e = 0;
  11848. constexpr diyfp(std::uint64_t f_, int e_) noexcept : f(f_), e(e_) {}
  11849. /*!
  11850. @brief returns x - y
  11851. @pre x.e == y.e and x.f >= y.f
  11852. */
  11853. static diyfp sub(const diyfp& x, const diyfp& y) noexcept
  11854. {
  11855. assert(x.e == y.e);
  11856. assert(x.f >= y.f);
  11857. return {x.f - y.f, x.e};
  11858. }
  11859. /*!
  11860. @brief returns x * y
  11861. @note The result is rounded. (Only the upper q bits are returned.)
  11862. */
  11863. static diyfp mul(const diyfp& x, const diyfp& y) noexcept
  11864. {
  11865. static_assert(kPrecision == 64, "internal error");
  11866. // Computes:
  11867. // f = round((x.f * y.f) / 2^q)
  11868. // e = x.e + y.e + q
  11869. // Emulate the 64-bit * 64-bit multiplication:
  11870. //
  11871. // p = u * v
  11872. // = (u_lo + 2^32 u_hi) (v_lo + 2^32 v_hi)
  11873. // = (u_lo v_lo ) + 2^32 ((u_lo v_hi ) + (u_hi v_lo )) + 2^64 (u_hi v_hi )
  11874. // = (p0 ) + 2^32 ((p1 ) + (p2 )) + 2^64 (p3 )
  11875. // = (p0_lo + 2^32 p0_hi) + 2^32 ((p1_lo + 2^32 p1_hi) + (p2_lo + 2^32 p2_hi)) + 2^64 (p3 )
  11876. // = (p0_lo ) + 2^32 (p0_hi + p1_lo + p2_lo ) + 2^64 (p1_hi + p2_hi + p3)
  11877. // = (p0_lo ) + 2^32 (Q ) + 2^64 (H )
  11878. // = (p0_lo ) + 2^32 (Q_lo + 2^32 Q_hi ) + 2^64 (H )
  11879. //
  11880. // (Since Q might be larger than 2^32 - 1)
  11881. //
  11882. // = (p0_lo + 2^32 Q_lo) + 2^64 (Q_hi + H)
  11883. //
  11884. // (Q_hi + H does not overflow a 64-bit int)
  11885. //
  11886. // = p_lo + 2^64 p_hi
  11887. const std::uint64_t u_lo = x.f & 0xFFFFFFFFu;
  11888. const std::uint64_t u_hi = x.f >> 32u;
  11889. const std::uint64_t v_lo = y.f & 0xFFFFFFFFu;
  11890. const std::uint64_t v_hi = y.f >> 32u;
  11891. const std::uint64_t p0 = u_lo * v_lo;
  11892. const std::uint64_t p1 = u_lo * v_hi;
  11893. const std::uint64_t p2 = u_hi * v_lo;
  11894. const std::uint64_t p3 = u_hi * v_hi;
  11895. const std::uint64_t p0_hi = p0 >> 32u;
  11896. const std::uint64_t p1_lo = p1 & 0xFFFFFFFFu;
  11897. const std::uint64_t p1_hi = p1 >> 32u;
  11898. const std::uint64_t p2_lo = p2 & 0xFFFFFFFFu;
  11899. const std::uint64_t p2_hi = p2 >> 32u;
  11900. std::uint64_t Q = p0_hi + p1_lo + p2_lo;
  11901. // The full product might now be computed as
  11902. //
  11903. // p_hi = p3 + p2_hi + p1_hi + (Q >> 32)
  11904. // p_lo = p0_lo + (Q << 32)
  11905. //
  11906. // But in this particular case here, the full p_lo is not required.
  11907. // Effectively we only need to add the highest bit in p_lo to p_hi (and
  11908. // Q_hi + 1 does not overflow).
  11909. Q += std::uint64_t{1} << (64u - 32u - 1u); // round, ties up
  11910. const std::uint64_t h = p3 + p2_hi + p1_hi + (Q >> 32u);
  11911. return {h, x.e + y.e + 64};
  11912. }
  11913. /*!
  11914. @brief normalize x such that the significand is >= 2^(q-1)
  11915. @pre x.f != 0
  11916. */
  11917. static diyfp normalize(diyfp x) noexcept
  11918. {
  11919. assert(x.f != 0);
  11920. while ((x.f >> 63u) == 0)
  11921. {
  11922. x.f <<= 1u;
  11923. x.e--;
  11924. }
  11925. return x;
  11926. }
  11927. /*!
  11928. @brief normalize x such that the result has the exponent E
  11929. @pre e >= x.e and the upper e - x.e bits of x.f must be zero.
  11930. */
  11931. static diyfp normalize_to(const diyfp& x, const int target_exponent) noexcept
  11932. {
  11933. const int delta = x.e - target_exponent;
  11934. assert(delta >= 0);
  11935. assert(((x.f << delta) >> delta) == x.f);
  11936. return {x.f << delta, target_exponent};
  11937. }
  11938. };
  11939. struct boundaries
  11940. {
  11941. diyfp w;
  11942. diyfp minus;
  11943. diyfp plus;
  11944. };
  11945. /*!
  11946. Compute the (normalized) diyfp representing the input number 'value' and its
  11947. boundaries.
  11948. @pre value must be finite and positive
  11949. */
  11950. template <typename FloatType>
  11951. boundaries compute_boundaries(FloatType value)
  11952. {
  11953. assert(std::isfinite(value));
  11954. assert(value > 0);
  11955. // Convert the IEEE representation into a diyfp.
  11956. //
  11957. // If v is denormal:
  11958. // value = 0.F * 2^(1 - bias) = ( F) * 2^(1 - bias - (p-1))
  11959. // If v is normalized:
  11960. // value = 1.F * 2^(E - bias) = (2^(p-1) + F) * 2^(E - bias - (p-1))
  11961. static_assert(std::numeric_limits<FloatType>::is_iec559,
  11962. "internal error: dtoa_short requires an IEEE-754 floating-point implementation");
  11963. constexpr int kPrecision = std::numeric_limits<FloatType>::digits; // = p (includes the hidden bit)
  11964. constexpr int kBias = std::numeric_limits<FloatType>::max_exponent - 1 + (kPrecision - 1);
  11965. constexpr int kMinExp = 1 - kBias;
  11966. constexpr std::uint64_t kHiddenBit = std::uint64_t{1} << (kPrecision - 1); // = 2^(p-1)
  11967. using bits_type = typename std::conditional<kPrecision == 24, std::uint32_t, std::uint64_t >::type;
  11968. const std::uint64_t bits = reinterpret_bits<bits_type>(value);
  11969. const std::uint64_t E = bits >> (kPrecision - 1);
  11970. const std::uint64_t F = bits & (kHiddenBit - 1);
  11971. const bool is_denormal = E == 0;
  11972. const diyfp v = is_denormal
  11973. ? diyfp(F, kMinExp)
  11974. : diyfp(F + kHiddenBit, static_cast<int>(E) - kBias);
  11975. // Compute the boundaries m- and m+ of the floating-point value
  11976. // v = f * 2^e.
  11977. //
  11978. // Determine v- and v+, the floating-point predecessor and successor if v,
  11979. // respectively.
  11980. //
  11981. // v- = v - 2^e if f != 2^(p-1) or e == e_min (A)
  11982. // = v - 2^(e-1) if f == 2^(p-1) and e > e_min (B)
  11983. //
  11984. // v+ = v + 2^e
  11985. //
  11986. // Let m- = (v- + v) / 2 and m+ = (v + v+) / 2. All real numbers _strictly_
  11987. // between m- and m+ round to v, regardless of how the input rounding
  11988. // algorithm breaks ties.
  11989. //
  11990. // ---+-------------+-------------+-------------+-------------+--- (A)
  11991. // v- m- v m+ v+
  11992. //
  11993. // -----------------+------+------+-------------+-------------+--- (B)
  11994. // v- m- v m+ v+
  11995. const bool lower_boundary_is_closer = F == 0 and E > 1;
  11996. const diyfp m_plus = diyfp(2 * v.f + 1, v.e - 1);
  11997. const diyfp m_minus = lower_boundary_is_closer
  11998. ? diyfp(4 * v.f - 1, v.e - 2) // (B)
  11999. : diyfp(2 * v.f - 1, v.e - 1); // (A)
  12000. // Determine the normalized w+ = m+.
  12001. const diyfp w_plus = diyfp::normalize(m_plus);
  12002. // Determine w- = m- such that e_(w-) = e_(w+).
  12003. const diyfp w_minus = diyfp::normalize_to(m_minus, w_plus.e);
  12004. return {diyfp::normalize(v), w_minus, w_plus};
  12005. }
  12006. // Given normalized diyfp w, Grisu needs to find a (normalized) cached
  12007. // power-of-ten c, such that the exponent of the product c * w = f * 2^e lies
  12008. // within a certain range [alpha, gamma] (Definition 3.2 from [1])
  12009. //
  12010. // alpha <= e = e_c + e_w + q <= gamma
  12011. //
  12012. // or
  12013. //
  12014. // f_c * f_w * 2^alpha <= f_c 2^(e_c) * f_w 2^(e_w) * 2^q
  12015. // <= f_c * f_w * 2^gamma
  12016. //
  12017. // Since c and w are normalized, i.e. 2^(q-1) <= f < 2^q, this implies
  12018. //
  12019. // 2^(q-1) * 2^(q-1) * 2^alpha <= c * w * 2^q < 2^q * 2^q * 2^gamma
  12020. //
  12021. // or
  12022. //
  12023. // 2^(q - 2 + alpha) <= c * w < 2^(q + gamma)
  12024. //
  12025. // The choice of (alpha,gamma) determines the size of the table and the form of
  12026. // the digit generation procedure. Using (alpha,gamma)=(-60,-32) works out well
  12027. // in practice:
  12028. //
  12029. // The idea is to cut the number c * w = f * 2^e into two parts, which can be
  12030. // processed independently: An integral part p1, and a fractional part p2:
  12031. //
  12032. // f * 2^e = ( (f div 2^-e) * 2^-e + (f mod 2^-e) ) * 2^e
  12033. // = (f div 2^-e) + (f mod 2^-e) * 2^e
  12034. // = p1 + p2 * 2^e
  12035. //
  12036. // The conversion of p1 into decimal form requires a series of divisions and
  12037. // modulos by (a power of) 10. These operations are faster for 32-bit than for
  12038. // 64-bit integers, so p1 should ideally fit into a 32-bit integer. This can be
  12039. // achieved by choosing
  12040. //
  12041. // -e >= 32 or e <= -32 := gamma
  12042. //
  12043. // In order to convert the fractional part
  12044. //
  12045. // p2 * 2^e = p2 / 2^-e = d[-1] / 10^1 + d[-2] / 10^2 + ...
  12046. //
  12047. // into decimal form, the fraction is repeatedly multiplied by 10 and the digits
  12048. // d[-i] are extracted in order:
  12049. //
  12050. // (10 * p2) div 2^-e = d[-1]
  12051. // (10 * p2) mod 2^-e = d[-2] / 10^1 + ...
  12052. //
  12053. // The multiplication by 10 must not overflow. It is sufficient to choose
  12054. //
  12055. // 10 * p2 < 16 * p2 = 2^4 * p2 <= 2^64.
  12056. //
  12057. // Since p2 = f mod 2^-e < 2^-e,
  12058. //
  12059. // -e <= 60 or e >= -60 := alpha
  12060. constexpr int kAlpha = -60;
  12061. constexpr int kGamma = -32;
  12062. struct cached_power // c = f * 2^e ~= 10^k
  12063. {
  12064. std::uint64_t f;
  12065. int e;
  12066. int k;
  12067. };
  12068. /*!
  12069. For a normalized diyfp w = f * 2^e, this function returns a (normalized) cached
  12070. power-of-ten c = f_c * 2^e_c, such that the exponent of the product w * c
  12071. satisfies (Definition 3.2 from [1])
  12072. alpha <= e_c + e + q <= gamma.
  12073. */
  12074. inline cached_power get_cached_power_for_binary_exponent(int e)
  12075. {
  12076. // Now
  12077. //
  12078. // alpha <= e_c + e + q <= gamma (1)
  12079. // ==> f_c * 2^alpha <= c * 2^e * 2^q
  12080. //
  12081. // and since the c's are normalized, 2^(q-1) <= f_c,
  12082. //
  12083. // ==> 2^(q - 1 + alpha) <= c * 2^(e + q)
  12084. // ==> 2^(alpha - e - 1) <= c
  12085. //
  12086. // If c were an exact power of ten, i.e. c = 10^k, one may determine k as
  12087. //
  12088. // k = ceil( log_10( 2^(alpha - e - 1) ) )
  12089. // = ceil( (alpha - e - 1) * log_10(2) )
  12090. //
  12091. // From the paper:
  12092. // "In theory the result of the procedure could be wrong since c is rounded,
  12093. // and the computation itself is approximated [...]. In practice, however,
  12094. // this simple function is sufficient."
  12095. //
  12096. // For IEEE double precision floating-point numbers converted into
  12097. // normalized diyfp's w = f * 2^e, with q = 64,
  12098. //
  12099. // e >= -1022 (min IEEE exponent)
  12100. // -52 (p - 1)
  12101. // -52 (p - 1, possibly normalize denormal IEEE numbers)
  12102. // -11 (normalize the diyfp)
  12103. // = -1137
  12104. //
  12105. // and
  12106. //
  12107. // e <= +1023 (max IEEE exponent)
  12108. // -52 (p - 1)
  12109. // -11 (normalize the diyfp)
  12110. // = 960
  12111. //
  12112. // This binary exponent range [-1137,960] results in a decimal exponent
  12113. // range [-307,324]. One does not need to store a cached power for each
  12114. // k in this range. For each such k it suffices to find a cached power
  12115. // such that the exponent of the product lies in [alpha,gamma].
  12116. // This implies that the difference of the decimal exponents of adjacent
  12117. // table entries must be less than or equal to
  12118. //
  12119. // floor( (gamma - alpha) * log_10(2) ) = 8.
  12120. //
  12121. // (A smaller distance gamma-alpha would require a larger table.)
  12122. // NB:
  12123. // Actually this function returns c, such that -60 <= e_c + e + 64 <= -34.
  12124. constexpr int kCachedPowersMinDecExp = -300;
  12125. constexpr int kCachedPowersDecStep = 8;
  12126. static constexpr std::array<cached_power, 79> kCachedPowers =
  12127. {
  12128. {
  12129. { 0xAB70FE17C79AC6CA, -1060, -300 },
  12130. { 0xFF77B1FCBEBCDC4F, -1034, -292 },
  12131. { 0xBE5691EF416BD60C, -1007, -284 },
  12132. { 0x8DD01FAD907FFC3C, -980, -276 },
  12133. { 0xD3515C2831559A83, -954, -268 },
  12134. { 0x9D71AC8FADA6C9B5, -927, -260 },
  12135. { 0xEA9C227723EE8BCB, -901, -252 },
  12136. { 0xAECC49914078536D, -874, -244 },
  12137. { 0x823C12795DB6CE57, -847, -236 },
  12138. { 0xC21094364DFB5637, -821, -228 },
  12139. { 0x9096EA6F3848984F, -794, -220 },
  12140. { 0xD77485CB25823AC7, -768, -212 },
  12141. { 0xA086CFCD97BF97F4, -741, -204 },
  12142. { 0xEF340A98172AACE5, -715, -196 },
  12143. { 0xB23867FB2A35B28E, -688, -188 },
  12144. { 0x84C8D4DFD2C63F3B, -661, -180 },
  12145. { 0xC5DD44271AD3CDBA, -635, -172 },
  12146. { 0x936B9FCEBB25C996, -608, -164 },
  12147. { 0xDBAC6C247D62A584, -582, -156 },
  12148. { 0xA3AB66580D5FDAF6, -555, -148 },
  12149. { 0xF3E2F893DEC3F126, -529, -140 },
  12150. { 0xB5B5ADA8AAFF80B8, -502, -132 },
  12151. { 0x87625F056C7C4A8B, -475, -124 },
  12152. { 0xC9BCFF6034C13053, -449, -116 },
  12153. { 0x964E858C91BA2655, -422, -108 },
  12154. { 0xDFF9772470297EBD, -396, -100 },
  12155. { 0xA6DFBD9FB8E5B88F, -369, -92 },
  12156. { 0xF8A95FCF88747D94, -343, -84 },
  12157. { 0xB94470938FA89BCF, -316, -76 },
  12158. { 0x8A08F0F8BF0F156B, -289, -68 },
  12159. { 0xCDB02555653131B6, -263, -60 },
  12160. { 0x993FE2C6D07B7FAC, -236, -52 },
  12161. { 0xE45C10C42A2B3B06, -210, -44 },
  12162. { 0xAA242499697392D3, -183, -36 },
  12163. { 0xFD87B5F28300CA0E, -157, -28 },
  12164. { 0xBCE5086492111AEB, -130, -20 },
  12165. { 0x8CBCCC096F5088CC, -103, -12 },
  12166. { 0xD1B71758E219652C, -77, -4 },
  12167. { 0x9C40000000000000, -50, 4 },
  12168. { 0xE8D4A51000000000, -24, 12 },
  12169. { 0xAD78EBC5AC620000, 3, 20 },
  12170. { 0x813F3978F8940984, 30, 28 },
  12171. { 0xC097CE7BC90715B3, 56, 36 },
  12172. { 0x8F7E32CE7BEA5C70, 83, 44 },
  12173. { 0xD5D238A4ABE98068, 109, 52 },
  12174. { 0x9F4F2726179A2245, 136, 60 },
  12175. { 0xED63A231D4C4FB27, 162, 68 },
  12176. { 0xB0DE65388CC8ADA8, 189, 76 },
  12177. { 0x83C7088E1AAB65DB, 216, 84 },
  12178. { 0xC45D1DF942711D9A, 242, 92 },
  12179. { 0x924D692CA61BE758, 269, 100 },
  12180. { 0xDA01EE641A708DEA, 295, 108 },
  12181. { 0xA26DA3999AEF774A, 322, 116 },
  12182. { 0xF209787BB47D6B85, 348, 124 },
  12183. { 0xB454E4A179DD1877, 375, 132 },
  12184. { 0x865B86925B9BC5C2, 402, 140 },
  12185. { 0xC83553C5C8965D3D, 428, 148 },
  12186. { 0x952AB45CFA97A0B3, 455, 156 },
  12187. { 0xDE469FBD99A05FE3, 481, 164 },
  12188. { 0xA59BC234DB398C25, 508, 172 },
  12189. { 0xF6C69A72A3989F5C, 534, 180 },
  12190. { 0xB7DCBF5354E9BECE, 561, 188 },
  12191. { 0x88FCF317F22241E2, 588, 196 },
  12192. { 0xCC20CE9BD35C78A5, 614, 204 },
  12193. { 0x98165AF37B2153DF, 641, 212 },
  12194. { 0xE2A0B5DC971F303A, 667, 220 },
  12195. { 0xA8D9D1535CE3B396, 694, 228 },
  12196. { 0xFB9B7CD9A4A7443C, 720, 236 },
  12197. { 0xBB764C4CA7A44410, 747, 244 },
  12198. { 0x8BAB8EEFB6409C1A, 774, 252 },
  12199. { 0xD01FEF10A657842C, 800, 260 },
  12200. { 0x9B10A4E5E9913129, 827, 268 },
  12201. { 0xE7109BFBA19C0C9D, 853, 276 },
  12202. { 0xAC2820D9623BF429, 880, 284 },
  12203. { 0x80444B5E7AA7CF85, 907, 292 },
  12204. { 0xBF21E44003ACDD2D, 933, 300 },
  12205. { 0x8E679C2F5E44FF8F, 960, 308 },
  12206. { 0xD433179D9C8CB841, 986, 316 },
  12207. { 0x9E19DB92B4E31BA9, 1013, 324 },
  12208. }
  12209. };
  12210. // This computation gives exactly the same results for k as
  12211. // k = ceil((kAlpha - e - 1) * 0.30102999566398114)
  12212. // for |e| <= 1500, but doesn't require floating-point operations.
  12213. // NB: log_10(2) ~= 78913 / 2^18
  12214. assert(e >= -1500);
  12215. assert(e <= 1500);
  12216. const int f = kAlpha - e - 1;
  12217. const int k = (f * 78913) / (1 << 18) + static_cast<int>(f > 0);
  12218. const int index = (-kCachedPowersMinDecExp + k + (kCachedPowersDecStep - 1)) / kCachedPowersDecStep;
  12219. assert(index >= 0);
  12220. assert(static_cast<std::size_t>(index) < kCachedPowers.size());
  12221. const cached_power cached = kCachedPowers[static_cast<std::size_t>(index)];
  12222. assert(kAlpha <= cached.e + e + 64);
  12223. assert(kGamma >= cached.e + e + 64);
  12224. return cached;
  12225. }
  12226. /*!
  12227. For n != 0, returns k, such that pow10 := 10^(k-1) <= n < 10^k.
  12228. For n == 0, returns 1 and sets pow10 := 1.
  12229. */
  12230. inline int find_largest_pow10(const std::uint32_t n, std::uint32_t& pow10)
  12231. {
  12232. // LCOV_EXCL_START
  12233. if (n >= 1000000000)
  12234. {
  12235. pow10 = 1000000000;
  12236. return 10;
  12237. }
  12238. // LCOV_EXCL_STOP
  12239. else if (n >= 100000000)
  12240. {
  12241. pow10 = 100000000;
  12242. return 9;
  12243. }
  12244. else if (n >= 10000000)
  12245. {
  12246. pow10 = 10000000;
  12247. return 8;
  12248. }
  12249. else if (n >= 1000000)
  12250. {
  12251. pow10 = 1000000;
  12252. return 7;
  12253. }
  12254. else if (n >= 100000)
  12255. {
  12256. pow10 = 100000;
  12257. return 6;
  12258. }
  12259. else if (n >= 10000)
  12260. {
  12261. pow10 = 10000;
  12262. return 5;
  12263. }
  12264. else if (n >= 1000)
  12265. {
  12266. pow10 = 1000;
  12267. return 4;
  12268. }
  12269. else if (n >= 100)
  12270. {
  12271. pow10 = 100;
  12272. return 3;
  12273. }
  12274. else if (n >= 10)
  12275. {
  12276. pow10 = 10;
  12277. return 2;
  12278. }
  12279. else
  12280. {
  12281. pow10 = 1;
  12282. return 1;
  12283. }
  12284. }
  12285. inline void grisu2_round(char* buf, int len, std::uint64_t dist, std::uint64_t delta,
  12286. std::uint64_t rest, std::uint64_t ten_k)
  12287. {
  12288. assert(len >= 1);
  12289. assert(dist <= delta);
  12290. assert(rest <= delta);
  12291. assert(ten_k > 0);
  12292. // <--------------------------- delta ---->
  12293. // <---- dist --------->
  12294. // --------------[------------------+-------------------]--------------
  12295. // M- w M+
  12296. //
  12297. // ten_k
  12298. // <------>
  12299. // <---- rest ---->
  12300. // --------------[------------------+----+--------------]--------------
  12301. // w V
  12302. // = buf * 10^k
  12303. //
  12304. // ten_k represents a unit-in-the-last-place in the decimal representation
  12305. // stored in buf.
  12306. // Decrement buf by ten_k while this takes buf closer to w.
  12307. // The tests are written in this order to avoid overflow in unsigned
  12308. // integer arithmetic.
  12309. while (rest < dist
  12310. and delta - rest >= ten_k
  12311. and (rest + ten_k < dist or dist - rest > rest + ten_k - dist))
  12312. {
  12313. assert(buf[len - 1] != '0');
  12314. buf[len - 1]--;
  12315. rest += ten_k;
  12316. }
  12317. }
  12318. /*!
  12319. Generates V = buffer * 10^decimal_exponent, such that M- <= V <= M+.
  12320. M- and M+ must be normalized and share the same exponent -60 <= e <= -32.
  12321. */
  12322. inline void grisu2_digit_gen(char* buffer, int& length, int& decimal_exponent,
  12323. diyfp M_minus, diyfp w, diyfp M_plus)
  12324. {
  12325. static_assert(kAlpha >= -60, "internal error");
  12326. static_assert(kGamma <= -32, "internal error");
  12327. // Generates the digits (and the exponent) of a decimal floating-point
  12328. // number V = buffer * 10^decimal_exponent in the range [M-, M+]. The diyfp's
  12329. // w, M- and M+ share the same exponent e, which satisfies alpha <= e <= gamma.
  12330. //
  12331. // <--------------------------- delta ---->
  12332. // <---- dist --------->
  12333. // --------------[------------------+-------------------]--------------
  12334. // M- w M+
  12335. //
  12336. // Grisu2 generates the digits of M+ from left to right and stops as soon as
  12337. // V is in [M-,M+].
  12338. assert(M_plus.e >= kAlpha);
  12339. assert(M_plus.e <= kGamma);
  12340. std::uint64_t delta = diyfp::sub(M_plus, M_minus).f; // (significand of (M+ - M-), implicit exponent is e)
  12341. std::uint64_t dist = diyfp::sub(M_plus, w ).f; // (significand of (M+ - w ), implicit exponent is e)
  12342. // Split M+ = f * 2^e into two parts p1 and p2 (note: e < 0):
  12343. //
  12344. // M+ = f * 2^e
  12345. // = ((f div 2^-e) * 2^-e + (f mod 2^-e)) * 2^e
  12346. // = ((p1 ) * 2^-e + (p2 )) * 2^e
  12347. // = p1 + p2 * 2^e
  12348. const diyfp one(std::uint64_t{1} << -M_plus.e, M_plus.e);
  12349. 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.)
  12350. std::uint64_t p2 = M_plus.f & (one.f - 1); // p2 = f mod 2^-e
  12351. // 1)
  12352. //
  12353. // Generate the digits of the integral part p1 = d[n-1]...d[1]d[0]
  12354. assert(p1 > 0);
  12355. std::uint32_t pow10;
  12356. const int k = find_largest_pow10(p1, pow10);
  12357. // 10^(k-1) <= p1 < 10^k, pow10 = 10^(k-1)
  12358. //
  12359. // p1 = (p1 div 10^(k-1)) * 10^(k-1) + (p1 mod 10^(k-1))
  12360. // = (d[k-1] ) * 10^(k-1) + (p1 mod 10^(k-1))
  12361. //
  12362. // M+ = p1 + p2 * 2^e
  12363. // = d[k-1] * 10^(k-1) + (p1 mod 10^(k-1)) + p2 * 2^e
  12364. // = d[k-1] * 10^(k-1) + ((p1 mod 10^(k-1)) * 2^-e + p2) * 2^e
  12365. // = d[k-1] * 10^(k-1) + ( rest) * 2^e
  12366. //
  12367. // Now generate the digits d[n] of p1 from left to right (n = k-1,...,0)
  12368. //
  12369. // p1 = d[k-1]...d[n] * 10^n + d[n-1]...d[0]
  12370. //
  12371. // but stop as soon as
  12372. //
  12373. // rest * 2^e = (d[n-1]...d[0] * 2^-e + p2) * 2^e <= delta * 2^e
  12374. int n = k;
  12375. while (n > 0)
  12376. {
  12377. // Invariants:
  12378. // M+ = buffer * 10^n + (p1 + p2 * 2^e) (buffer = 0 for n = k)
  12379. // pow10 = 10^(n-1) <= p1 < 10^n
  12380. //
  12381. const std::uint32_t d = p1 / pow10; // d = p1 div 10^(n-1)
  12382. const std::uint32_t r = p1 % pow10; // r = p1 mod 10^(n-1)
  12383. //
  12384. // M+ = buffer * 10^n + (d * 10^(n-1) + r) + p2 * 2^e
  12385. // = (buffer * 10 + d) * 10^(n-1) + (r + p2 * 2^e)
  12386. //
  12387. assert(d <= 9);
  12388. buffer[length++] = static_cast<char>('0' + d); // buffer := buffer * 10 + d
  12389. //
  12390. // M+ = buffer * 10^(n-1) + (r + p2 * 2^e)
  12391. //
  12392. p1 = r;
  12393. n--;
  12394. //
  12395. // M+ = buffer * 10^n + (p1 + p2 * 2^e)
  12396. // pow10 = 10^n
  12397. //
  12398. // Now check if enough digits have been generated.
  12399. // Compute
  12400. //
  12401. // p1 + p2 * 2^e = (p1 * 2^-e + p2) * 2^e = rest * 2^e
  12402. //
  12403. // Note:
  12404. // Since rest and delta share the same exponent e, it suffices to
  12405. // compare the significands.
  12406. const std::uint64_t rest = (std::uint64_t{p1} << -one.e) + p2;
  12407. if (rest <= delta)
  12408. {
  12409. // V = buffer * 10^n, with M- <= V <= M+.
  12410. decimal_exponent += n;
  12411. // We may now just stop. But instead look if the buffer could be
  12412. // decremented to bring V closer to w.
  12413. //
  12414. // pow10 = 10^n is now 1 ulp in the decimal representation V.
  12415. // The rounding procedure works with diyfp's with an implicit
  12416. // exponent of e.
  12417. //
  12418. // 10^n = (10^n * 2^-e) * 2^e = ulp * 2^e
  12419. //
  12420. const std::uint64_t ten_n = std::uint64_t{pow10} << -one.e;
  12421. grisu2_round(buffer, length, dist, delta, rest, ten_n);
  12422. return;
  12423. }
  12424. pow10 /= 10;
  12425. //
  12426. // pow10 = 10^(n-1) <= p1 < 10^n
  12427. // Invariants restored.
  12428. }
  12429. // 2)
  12430. //
  12431. // The digits of the integral part have been generated:
  12432. //
  12433. // M+ = d[k-1]...d[1]d[0] + p2 * 2^e
  12434. // = buffer + p2 * 2^e
  12435. //
  12436. // Now generate the digits of the fractional part p2 * 2^e.
  12437. //
  12438. // Note:
  12439. // No decimal point is generated: the exponent is adjusted instead.
  12440. //
  12441. // p2 actually represents the fraction
  12442. //
  12443. // p2 * 2^e
  12444. // = p2 / 2^-e
  12445. // = d[-1] / 10^1 + d[-2] / 10^2 + ...
  12446. //
  12447. // Now generate the digits d[-m] of p1 from left to right (m = 1,2,...)
  12448. //
  12449. // p2 * 2^e = d[-1]d[-2]...d[-m] * 10^-m
  12450. // + 10^-m * (d[-m-1] / 10^1 + d[-m-2] / 10^2 + ...)
  12451. //
  12452. // using
  12453. //
  12454. // 10^m * p2 = ((10^m * p2) div 2^-e) * 2^-e + ((10^m * p2) mod 2^-e)
  12455. // = ( d) * 2^-e + ( r)
  12456. //
  12457. // or
  12458. // 10^m * p2 * 2^e = d + r * 2^e
  12459. //
  12460. // i.e.
  12461. //
  12462. // M+ = buffer + p2 * 2^e
  12463. // = buffer + 10^-m * (d + r * 2^e)
  12464. // = (buffer * 10^m + d) * 10^-m + 10^-m * r * 2^e
  12465. //
  12466. // and stop as soon as 10^-m * r * 2^e <= delta * 2^e
  12467. assert(p2 > delta);
  12468. int m = 0;
  12469. for (;;)
  12470. {
  12471. // Invariant:
  12472. // M+ = buffer * 10^-m + 10^-m * (d[-m-1] / 10 + d[-m-2] / 10^2 + ...) * 2^e
  12473. // = buffer * 10^-m + 10^-m * (p2 ) * 2^e
  12474. // = buffer * 10^-m + 10^-m * (1/10 * (10 * p2) ) * 2^e
  12475. // = buffer * 10^-m + 10^-m * (1/10 * ((10*p2 div 2^-e) * 2^-e + (10*p2 mod 2^-e)) * 2^e
  12476. //
  12477. assert(p2 <= (std::numeric_limits<std::uint64_t>::max)() / 10);
  12478. p2 *= 10;
  12479. const std::uint64_t d = p2 >> -one.e; // d = (10 * p2) div 2^-e
  12480. const std::uint64_t r = p2 & (one.f - 1); // r = (10 * p2) mod 2^-e
  12481. //
  12482. // M+ = buffer * 10^-m + 10^-m * (1/10 * (d * 2^-e + r) * 2^e
  12483. // = buffer * 10^-m + 10^-m * (1/10 * (d + r * 2^e))
  12484. // = (buffer * 10 + d) * 10^(-m-1) + 10^(-m-1) * r * 2^e
  12485. //
  12486. assert(d <= 9);
  12487. buffer[length++] = static_cast<char>('0' + d); // buffer := buffer * 10 + d
  12488. //
  12489. // M+ = buffer * 10^(-m-1) + 10^(-m-1) * r * 2^e
  12490. //
  12491. p2 = r;
  12492. m++;
  12493. //
  12494. // M+ = buffer * 10^-m + 10^-m * p2 * 2^e
  12495. // Invariant restored.
  12496. // Check if enough digits have been generated.
  12497. //
  12498. // 10^-m * p2 * 2^e <= delta * 2^e
  12499. // p2 * 2^e <= 10^m * delta * 2^e
  12500. // p2 <= 10^m * delta
  12501. delta *= 10;
  12502. dist *= 10;
  12503. if (p2 <= delta)
  12504. {
  12505. break;
  12506. }
  12507. }
  12508. // V = buffer * 10^-m, with M- <= V <= M+.
  12509. decimal_exponent -= m;
  12510. // 1 ulp in the decimal representation is now 10^-m.
  12511. // Since delta and dist are now scaled by 10^m, we need to do the
  12512. // same with ulp in order to keep the units in sync.
  12513. //
  12514. // 10^m * 10^-m = 1 = 2^-e * 2^e = ten_m * 2^e
  12515. //
  12516. const std::uint64_t ten_m = one.f;
  12517. grisu2_round(buffer, length, dist, delta, p2, ten_m);
  12518. // By construction this algorithm generates the shortest possible decimal
  12519. // number (Loitsch, Theorem 6.2) which rounds back to w.
  12520. // For an input number of precision p, at least
  12521. //
  12522. // N = 1 + ceil(p * log_10(2))
  12523. //
  12524. // decimal digits are sufficient to identify all binary floating-point
  12525. // numbers (Matula, "In-and-Out conversions").
  12526. // This implies that the algorithm does not produce more than N decimal
  12527. // digits.
  12528. //
  12529. // N = 17 for p = 53 (IEEE double precision)
  12530. // N = 9 for p = 24 (IEEE single precision)
  12531. }
  12532. /*!
  12533. v = buf * 10^decimal_exponent
  12534. len is the length of the buffer (number of decimal digits)
  12535. The buffer must be large enough, i.e. >= max_digits10.
  12536. */
  12537. JSON_HEDLEY_NON_NULL(1)
  12538. inline void grisu2(char* buf, int& len, int& decimal_exponent,
  12539. diyfp m_minus, diyfp v, diyfp m_plus)
  12540. {
  12541. assert(m_plus.e == m_minus.e);
  12542. assert(m_plus.e == v.e);
  12543. // --------(-----------------------+-----------------------)-------- (A)
  12544. // m- v m+
  12545. //
  12546. // --------------------(-----------+-----------------------)-------- (B)
  12547. // m- v m+
  12548. //
  12549. // First scale v (and m- and m+) such that the exponent is in the range
  12550. // [alpha, gamma].
  12551. const cached_power cached = get_cached_power_for_binary_exponent(m_plus.e);
  12552. const diyfp c_minus_k(cached.f, cached.e); // = c ~= 10^-k
  12553. // The exponent of the products is = v.e + c_minus_k.e + q and is in the range [alpha,gamma]
  12554. const diyfp w = diyfp::mul(v, c_minus_k);
  12555. const diyfp w_minus = diyfp::mul(m_minus, c_minus_k);
  12556. const diyfp w_plus = diyfp::mul(m_plus, c_minus_k);
  12557. // ----(---+---)---------------(---+---)---------------(---+---)----
  12558. // w- w w+
  12559. // = c*m- = c*v = c*m+
  12560. //
  12561. // diyfp::mul rounds its result and c_minus_k is approximated too. w, w- and
  12562. // w+ are now off by a small amount.
  12563. // In fact:
  12564. //
  12565. // w - v * 10^k < 1 ulp
  12566. //
  12567. // To account for this inaccuracy, add resp. subtract 1 ulp.
  12568. //
  12569. // --------+---[---------------(---+---)---------------]---+--------
  12570. // w- M- w M+ w+
  12571. //
  12572. // Now any number in [M-, M+] (bounds included) will round to w when input,
  12573. // regardless of how the input rounding algorithm breaks ties.
  12574. //
  12575. // And digit_gen generates the shortest possible such number in [M-, M+].
  12576. // Note that this does not mean that Grisu2 always generates the shortest
  12577. // possible number in the interval (m-, m+).
  12578. const diyfp M_minus(w_minus.f + 1, w_minus.e);
  12579. const diyfp M_plus (w_plus.f - 1, w_plus.e );
  12580. decimal_exponent = -cached.k; // = -(-k) = k
  12581. grisu2_digit_gen(buf, len, decimal_exponent, M_minus, w, M_plus);
  12582. }
  12583. /*!
  12584. v = buf * 10^decimal_exponent
  12585. len is the length of the buffer (number of decimal digits)
  12586. The buffer must be large enough, i.e. >= max_digits10.
  12587. */
  12588. template <typename FloatType>
  12589. JSON_HEDLEY_NON_NULL(1)
  12590. void grisu2(char* buf, int& len, int& decimal_exponent, FloatType value)
  12591. {
  12592. static_assert(diyfp::kPrecision >= std::numeric_limits<FloatType>::digits + 3,
  12593. "internal error: not enough precision");
  12594. assert(std::isfinite(value));
  12595. assert(value > 0);
  12596. // If the neighbors (and boundaries) of 'value' are always computed for double-precision
  12597. // numbers, all float's can be recovered using strtod (and strtof). However, the resulting
  12598. // decimal representations are not exactly "short".
  12599. //
  12600. // The documentation for 'std::to_chars' (https://en.cppreference.com/w/cpp/utility/to_chars)
  12601. // says "value is converted to a string as if by std::sprintf in the default ("C") locale"
  12602. // and since sprintf promotes float's to double's, I think this is exactly what 'std::to_chars'
  12603. // does.
  12604. // On the other hand, the documentation for 'std::to_chars' requires that "parsing the
  12605. // representation using the corresponding std::from_chars function recovers value exactly". That
  12606. // indicates that single precision floating-point numbers should be recovered using
  12607. // 'std::strtof'.
  12608. //
  12609. // NB: If the neighbors are computed for single-precision numbers, there is a single float
  12610. // (7.0385307e-26f) which can't be recovered using strtod. The resulting double precision
  12611. // value is off by 1 ulp.
  12612. #if 0
  12613. const boundaries w = compute_boundaries(static_cast<double>(value));
  12614. #else
  12615. const boundaries w = compute_boundaries(value);
  12616. #endif
  12617. grisu2(buf, len, decimal_exponent, w.minus, w.w, w.plus);
  12618. }
  12619. /*!
  12620. @brief appends a decimal representation of e to buf
  12621. @return a pointer to the element following the exponent.
  12622. @pre -1000 < e < 1000
  12623. */
  12624. JSON_HEDLEY_NON_NULL(1)
  12625. JSON_HEDLEY_RETURNS_NON_NULL
  12626. inline char* append_exponent(char* buf, int e)
  12627. {
  12628. assert(e > -1000);
  12629. assert(e < 1000);
  12630. if (e < 0)
  12631. {
  12632. e = -e;
  12633. *buf++ = '-';
  12634. }
  12635. else
  12636. {
  12637. *buf++ = '+';
  12638. }
  12639. auto k = static_cast<std::uint32_t>(e);
  12640. if (k < 10)
  12641. {
  12642. // Always print at least two digits in the exponent.
  12643. // This is for compatibility with printf("%g").
  12644. *buf++ = '0';
  12645. *buf++ = static_cast<char>('0' + k);
  12646. }
  12647. else if (k < 100)
  12648. {
  12649. *buf++ = static_cast<char>('0' + k / 10);
  12650. k %= 10;
  12651. *buf++ = static_cast<char>('0' + k);
  12652. }
  12653. else
  12654. {
  12655. *buf++ = static_cast<char>('0' + k / 100);
  12656. k %= 100;
  12657. *buf++ = static_cast<char>('0' + k / 10);
  12658. k %= 10;
  12659. *buf++ = static_cast<char>('0' + k);
  12660. }
  12661. return buf;
  12662. }
  12663. /*!
  12664. @brief prettify v = buf * 10^decimal_exponent
  12665. If v is in the range [10^min_exp, 10^max_exp) it will be printed in fixed-point
  12666. notation. Otherwise it will be printed in exponential notation.
  12667. @pre min_exp < 0
  12668. @pre max_exp > 0
  12669. */
  12670. JSON_HEDLEY_NON_NULL(1)
  12671. JSON_HEDLEY_RETURNS_NON_NULL
  12672. inline char* format_buffer(char* buf, int len, int decimal_exponent,
  12673. int min_exp, int max_exp)
  12674. {
  12675. assert(min_exp < 0);
  12676. assert(max_exp > 0);
  12677. const int k = len;
  12678. const int n = len + decimal_exponent;
  12679. // v = buf * 10^(n-k)
  12680. // k is the length of the buffer (number of decimal digits)
  12681. // n is the position of the decimal point relative to the start of the buffer.
  12682. if (k <= n and n <= max_exp)
  12683. {
  12684. // digits[000]
  12685. // len <= max_exp + 2
  12686. std::memset(buf + k, '0', static_cast<size_t>(n) - static_cast<size_t>(k));
  12687. // Make it look like a floating-point number (#362, #378)
  12688. buf[n + 0] = '.';
  12689. buf[n + 1] = '0';
  12690. return buf + (static_cast<size_t>(n) + 2);
  12691. }
  12692. if (0 < n and n <= max_exp)
  12693. {
  12694. // dig.its
  12695. // len <= max_digits10 + 1
  12696. assert(k > n);
  12697. std::memmove(buf + (static_cast<size_t>(n) + 1), buf + n, static_cast<size_t>(k) - static_cast<size_t>(n));
  12698. buf[n] = '.';
  12699. return buf + (static_cast<size_t>(k) + 1U);
  12700. }
  12701. if (min_exp < n and n <= 0)
  12702. {
  12703. // 0.[000]digits
  12704. // len <= 2 + (-min_exp - 1) + max_digits10
  12705. std::memmove(buf + (2 + static_cast<size_t>(-n)), buf, static_cast<size_t>(k));
  12706. buf[0] = '0';
  12707. buf[1] = '.';
  12708. std::memset(buf + 2, '0', static_cast<size_t>(-n));
  12709. return buf + (2U + static_cast<size_t>(-n) + static_cast<size_t>(k));
  12710. }
  12711. if (k == 1)
  12712. {
  12713. // dE+123
  12714. // len <= 1 + 5
  12715. buf += 1;
  12716. }
  12717. else
  12718. {
  12719. // d.igitsE+123
  12720. // len <= max_digits10 + 1 + 5
  12721. std::memmove(buf + 2, buf + 1, static_cast<size_t>(k) - 1);
  12722. buf[1] = '.';
  12723. buf += 1 + static_cast<size_t>(k);
  12724. }
  12725. *buf++ = 'e';
  12726. return append_exponent(buf, n - 1);
  12727. }
  12728. } // namespace dtoa_impl
  12729. /*!
  12730. @brief generates a decimal representation of the floating-point number value in [first, last).
  12731. The format of the resulting decimal representation is similar to printf's %g
  12732. format. Returns an iterator pointing past-the-end of the decimal representation.
  12733. @note The input number must be finite, i.e. NaN's and Inf's are not supported.
  12734. @note The buffer must be large enough.
  12735. @note The result is NOT null-terminated.
  12736. */
  12737. template <typename FloatType>
  12738. JSON_HEDLEY_NON_NULL(1, 2)
  12739. JSON_HEDLEY_RETURNS_NON_NULL
  12740. char* to_chars(char* first, const char* last, FloatType value)
  12741. {
  12742. static_cast<void>(last); // maybe unused - fix warning
  12743. assert(std::isfinite(value));
  12744. // Use signbit(value) instead of (value < 0) since signbit works for -0.
  12745. if (std::signbit(value))
  12746. {
  12747. value = -value;
  12748. *first++ = '-';
  12749. }
  12750. if (value == 0) // +-0
  12751. {
  12752. *first++ = '0';
  12753. // Make it look like a floating-point number (#362, #378)
  12754. *first++ = '.';
  12755. *first++ = '0';
  12756. return first;
  12757. }
  12758. assert(last - first >= std::numeric_limits<FloatType>::max_digits10);
  12759. // Compute v = buffer * 10^decimal_exponent.
  12760. // The decimal digits are stored in the buffer, which needs to be interpreted
  12761. // as an unsigned decimal integer.
  12762. // len is the length of the buffer, i.e. the number of decimal digits.
  12763. int len = 0;
  12764. int decimal_exponent = 0;
  12765. dtoa_impl::grisu2(first, len, decimal_exponent, value);
  12766. assert(len <= std::numeric_limits<FloatType>::max_digits10);
  12767. // Format the buffer like printf("%.*g", prec, value)
  12768. constexpr int kMinExp = -4;
  12769. // Use digits10 here to increase compatibility with version 2.
  12770. constexpr int kMaxExp = std::numeric_limits<FloatType>::digits10;
  12771. assert(last - first >= kMaxExp + 2);
  12772. assert(last - first >= 2 + (-kMinExp - 1) + std::numeric_limits<FloatType>::max_digits10);
  12773. assert(last - first >= std::numeric_limits<FloatType>::max_digits10 + 6);
  12774. return dtoa_impl::format_buffer(first, len, decimal_exponent, kMinExp, kMaxExp);
  12775. }
  12776. } // namespace detail
  12777. } // namespace nlohmann
  12778. // #include <nlohmann/detail/exceptions.hpp>
  12779. // #include <nlohmann/detail/macro_scope.hpp>
  12780. // #include <nlohmann/detail/meta/cpp_future.hpp>
  12781. // #include <nlohmann/detail/output/binary_writer.hpp>
  12782. // #include <nlohmann/detail/output/output_adapters.hpp>
  12783. // #include <nlohmann/detail/value_t.hpp>
  12784. namespace nlohmann
  12785. {
  12786. namespace detail
  12787. {
  12788. ///////////////////
  12789. // serialization //
  12790. ///////////////////
  12791. /// how to treat decoding errors
  12792. enum class error_handler_t
  12793. {
  12794. strict, ///< throw a type_error exception in case of invalid UTF-8
  12795. replace, ///< replace invalid UTF-8 sequences with U+FFFD
  12796. ignore ///< ignore invalid UTF-8 sequences
  12797. };
  12798. template<typename BasicJsonType>
  12799. class serializer
  12800. {
  12801. using string_t = typename BasicJsonType::string_t;
  12802. using number_float_t = typename BasicJsonType::number_float_t;
  12803. using number_integer_t = typename BasicJsonType::number_integer_t;
  12804. using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
  12805. using binary_t = typename BasicJsonType::binary_t;
  12806. static constexpr std::uint8_t UTF8_ACCEPT = 0;
  12807. static constexpr std::uint8_t UTF8_REJECT = 1;
  12808. public:
  12809. /*!
  12810. @param[in] s output stream to serialize to
  12811. @param[in] ichar indentation character to use
  12812. @param[in] error_handler_ how to react on decoding errors
  12813. */
  12814. serializer(output_adapter_t<char> s, const char ichar,
  12815. error_handler_t error_handler_ = error_handler_t::strict)
  12816. : o(std::move(s))
  12817. , loc(std::localeconv())
  12818. , thousands_sep(loc->thousands_sep == nullptr ? '\0' : * (loc->thousands_sep))
  12819. , decimal_point(loc->decimal_point == nullptr ? '\0' : * (loc->decimal_point))
  12820. , indent_char(ichar)
  12821. , indent_string(512, indent_char)
  12822. , error_handler(error_handler_)
  12823. {}
  12824. // delete because of pointer members
  12825. serializer(const serializer&) = delete;
  12826. serializer& operator=(const serializer&) = delete;
  12827. serializer(serializer&&) = delete;
  12828. serializer& operator=(serializer&&) = delete;
  12829. ~serializer() = default;
  12830. /*!
  12831. @brief internal implementation of the serialization function
  12832. This function is called by the public member function dump and organizes
  12833. the serialization internally. The indentation level is propagated as
  12834. additional parameter. In case of arrays and objects, the function is
  12835. called recursively.
  12836. - strings and object keys are escaped using `escape_string()`
  12837. - integer numbers are converted implicitly via `operator<<`
  12838. - floating-point numbers are converted to a string using `"%g"` format
  12839. - if specified to, binary values are output using the syntax `b[]`, otherwise an exception is thrown
  12840. @param[in] val value to serialize
  12841. @param[in] pretty_print whether the output shall be pretty-printed
  12842. @param[in] indent_step the indent level
  12843. @param[in] current_indent the current indent level (only used internally)
  12844. @param[in] serialize_binary whether the output shall include non-standard binary output
  12845. */
  12846. void dump(const BasicJsonType& val, const bool pretty_print,
  12847. const bool ensure_ascii,
  12848. const unsigned int indent_step,
  12849. const unsigned int current_indent = 0,
  12850. const bool serialize_binary = false)
  12851. {
  12852. switch (val.m_type)
  12853. {
  12854. case value_t::object:
  12855. {
  12856. if (val.m_value.object->empty())
  12857. {
  12858. o->write_characters("{}", 2);
  12859. return;
  12860. }
  12861. if (pretty_print)
  12862. {
  12863. o->write_characters("{\n", 2);
  12864. // variable to hold indentation for recursive calls
  12865. const auto new_indent = current_indent + indent_step;
  12866. if (JSON_HEDLEY_UNLIKELY(indent_string.size() < new_indent))
  12867. {
  12868. indent_string.resize(indent_string.size() * 2, ' ');
  12869. }
  12870. // first n-1 elements
  12871. auto i = val.m_value.object->cbegin();
  12872. for (std::size_t cnt = 0; cnt < val.m_value.object->size() - 1; ++cnt, ++i)
  12873. {
  12874. o->write_characters(indent_string.c_str(), new_indent);
  12875. o->write_character('\"');
  12876. dump_escaped(i->first, ensure_ascii);
  12877. o->write_characters("\": ", 3);
  12878. dump(i->second, true, ensure_ascii, indent_step, new_indent, serialize_binary);
  12879. o->write_characters(",\n", 2);
  12880. }
  12881. // last element
  12882. assert(i != val.m_value.object->cend());
  12883. assert(std::next(i) == val.m_value.object->cend());
  12884. o->write_characters(indent_string.c_str(), new_indent);
  12885. o->write_character('\"');
  12886. dump_escaped(i->first, ensure_ascii);
  12887. o->write_characters("\": ", 3);
  12888. dump(i->second, true, ensure_ascii, indent_step, new_indent, serialize_binary);
  12889. o->write_character('\n');
  12890. o->write_characters(indent_string.c_str(), current_indent);
  12891. o->write_character('}');
  12892. }
  12893. else
  12894. {
  12895. o->write_character('{');
  12896. // first n-1 elements
  12897. auto i = val.m_value.object->cbegin();
  12898. for (std::size_t cnt = 0; cnt < val.m_value.object->size() - 1; ++cnt, ++i)
  12899. {
  12900. o->write_character('\"');
  12901. dump_escaped(i->first, ensure_ascii);
  12902. o->write_characters("\":", 2);
  12903. dump(i->second, false, ensure_ascii, indent_step, current_indent, serialize_binary);
  12904. o->write_character(',');
  12905. }
  12906. // last element
  12907. assert(i != val.m_value.object->cend());
  12908. assert(std::next(i) == val.m_value.object->cend());
  12909. o->write_character('\"');
  12910. dump_escaped(i->first, ensure_ascii);
  12911. o->write_characters("\":", 2);
  12912. dump(i->second, false, ensure_ascii, indent_step, current_indent, serialize_binary);
  12913. o->write_character('}');
  12914. }
  12915. return;
  12916. }
  12917. case value_t::array:
  12918. {
  12919. if (val.m_value.array->empty())
  12920. {
  12921. o->write_characters("[]", 2);
  12922. return;
  12923. }
  12924. if (pretty_print)
  12925. {
  12926. o->write_characters("[\n", 2);
  12927. // variable to hold indentation for recursive calls
  12928. const auto new_indent = current_indent + indent_step;
  12929. if (JSON_HEDLEY_UNLIKELY(indent_string.size() < new_indent))
  12930. {
  12931. indent_string.resize(indent_string.size() * 2, ' ');
  12932. }
  12933. // first n-1 elements
  12934. for (auto i = val.m_value.array->cbegin();
  12935. i != val.m_value.array->cend() - 1; ++i)
  12936. {
  12937. o->write_characters(indent_string.c_str(), new_indent);
  12938. dump(*i, true, ensure_ascii, indent_step, new_indent, serialize_binary);
  12939. o->write_characters(",\n", 2);
  12940. }
  12941. // last element
  12942. assert(not val.m_value.array->empty());
  12943. o->write_characters(indent_string.c_str(), new_indent);
  12944. dump(val.m_value.array->back(), true, ensure_ascii, indent_step, new_indent, serialize_binary);
  12945. o->write_character('\n');
  12946. o->write_characters(indent_string.c_str(), current_indent);
  12947. o->write_character(']');
  12948. }
  12949. else
  12950. {
  12951. o->write_character('[');
  12952. // first n-1 elements
  12953. for (auto i = val.m_value.array->cbegin();
  12954. i != val.m_value.array->cend() - 1; ++i)
  12955. {
  12956. dump(*i, false, ensure_ascii, indent_step, current_indent, serialize_binary);
  12957. o->write_character(',');
  12958. }
  12959. // last element
  12960. assert(not val.m_value.array->empty());
  12961. dump(val.m_value.array->back(), false, ensure_ascii, indent_step, current_indent, serialize_binary);
  12962. o->write_character(']');
  12963. }
  12964. return;
  12965. }
  12966. case value_t::string:
  12967. {
  12968. o->write_character('\"');
  12969. dump_escaped(*val.m_value.string, ensure_ascii);
  12970. o->write_character('\"');
  12971. return;
  12972. }
  12973. case value_t::binary:
  12974. {
  12975. if (not serialize_binary)
  12976. {
  12977. JSON_THROW(type_error::create(317, "cannot serialize binary data to text JSON"));
  12978. }
  12979. if (val.m_value.binary->empty())
  12980. {
  12981. o->write_characters("b[]", 3);
  12982. }
  12983. else if (pretty_print)
  12984. {
  12985. o->write_characters("b[", 2);
  12986. for (auto i = val.m_value.binary->cbegin();
  12987. i != val.m_value.binary->cend() - 1; ++i)
  12988. {
  12989. dump_integer(*i);
  12990. o->write_character(',');
  12991. if (std::distance(val.m_value.binary->cbegin(), i) % 16 == 0)
  12992. {
  12993. o->write_character('\n');
  12994. }
  12995. else
  12996. {
  12997. o->write_character(' ');
  12998. }
  12999. }
  13000. dump_integer(val.m_value.binary->back());
  13001. o->write_character(']');
  13002. }
  13003. else
  13004. {
  13005. o->write_characters("b[", 2);
  13006. for (auto i = val.m_value.binary->cbegin();
  13007. i != val.m_value.binary->cend() - 1; ++i)
  13008. {
  13009. dump_integer(*i);
  13010. o->write_character(',');
  13011. }
  13012. dump_integer(val.m_value.binary->back());
  13013. o->write_character(']');
  13014. }
  13015. return;
  13016. }
  13017. case value_t::boolean:
  13018. {
  13019. if (val.m_value.boolean)
  13020. {
  13021. o->write_characters("true", 4);
  13022. }
  13023. else
  13024. {
  13025. o->write_characters("false", 5);
  13026. }
  13027. return;
  13028. }
  13029. case value_t::number_integer:
  13030. {
  13031. dump_integer(val.m_value.number_integer);
  13032. return;
  13033. }
  13034. case value_t::number_unsigned:
  13035. {
  13036. dump_integer(val.m_value.number_unsigned);
  13037. return;
  13038. }
  13039. case value_t::number_float:
  13040. {
  13041. dump_float(val.m_value.number_float);
  13042. return;
  13043. }
  13044. case value_t::discarded:
  13045. {
  13046. o->write_characters("<discarded>", 11);
  13047. return;
  13048. }
  13049. case value_t::null:
  13050. {
  13051. o->write_characters("null", 4);
  13052. return;
  13053. }
  13054. default: // LCOV_EXCL_LINE
  13055. assert(false); // LCOV_EXCL_LINE
  13056. }
  13057. }
  13058. private:
  13059. /*!
  13060. @brief dump escaped string
  13061. Escape a string by replacing certain special characters by a sequence of an
  13062. escape character (backslash) and another character and other control
  13063. characters by a sequence of "\u" followed by a four-digit hex
  13064. representation. The escaped string is written to output stream @a o.
  13065. @param[in] s the string to escape
  13066. @param[in] ensure_ascii whether to escape non-ASCII characters with
  13067. \uXXXX sequences
  13068. @complexity Linear in the length of string @a s.
  13069. */
  13070. void dump_escaped(const string_t& s, const bool ensure_ascii)
  13071. {
  13072. std::uint32_t codepoint;
  13073. std::uint8_t state = UTF8_ACCEPT;
  13074. std::size_t bytes = 0; // number of bytes written to string_buffer
  13075. // number of bytes written at the point of the last valid byte
  13076. std::size_t bytes_after_last_accept = 0;
  13077. std::size_t undumped_chars = 0;
  13078. for (std::size_t i = 0; i < s.size(); ++i)
  13079. {
  13080. const auto byte = static_cast<uint8_t>(s[i]);
  13081. switch (decode(state, codepoint, byte))
  13082. {
  13083. case UTF8_ACCEPT: // decode found a new code point
  13084. {
  13085. switch (codepoint)
  13086. {
  13087. case 0x08: // backspace
  13088. {
  13089. string_buffer[bytes++] = '\\';
  13090. string_buffer[bytes++] = 'b';
  13091. break;
  13092. }
  13093. case 0x09: // horizontal tab
  13094. {
  13095. string_buffer[bytes++] = '\\';
  13096. string_buffer[bytes++] = 't';
  13097. break;
  13098. }
  13099. case 0x0A: // newline
  13100. {
  13101. string_buffer[bytes++] = '\\';
  13102. string_buffer[bytes++] = 'n';
  13103. break;
  13104. }
  13105. case 0x0C: // formfeed
  13106. {
  13107. string_buffer[bytes++] = '\\';
  13108. string_buffer[bytes++] = 'f';
  13109. break;
  13110. }
  13111. case 0x0D: // carriage return
  13112. {
  13113. string_buffer[bytes++] = '\\';
  13114. string_buffer[bytes++] = 'r';
  13115. break;
  13116. }
  13117. case 0x22: // quotation mark
  13118. {
  13119. string_buffer[bytes++] = '\\';
  13120. string_buffer[bytes++] = '\"';
  13121. break;
  13122. }
  13123. case 0x5C: // reverse solidus
  13124. {
  13125. string_buffer[bytes++] = '\\';
  13126. string_buffer[bytes++] = '\\';
  13127. break;
  13128. }
  13129. default:
  13130. {
  13131. // escape control characters (0x00..0x1F) or, if
  13132. // ensure_ascii parameter is used, non-ASCII characters
  13133. if ((codepoint <= 0x1F) or (ensure_ascii and (codepoint >= 0x7F)))
  13134. {
  13135. if (codepoint <= 0xFFFF)
  13136. {
  13137. (std::snprintf)(string_buffer.data() + bytes, 7, "\\u%04x",
  13138. static_cast<std::uint16_t>(codepoint));
  13139. bytes += 6;
  13140. }
  13141. else
  13142. {
  13143. (std::snprintf)(string_buffer.data() + bytes, 13, "\\u%04x\\u%04x",
  13144. static_cast<std::uint16_t>(0xD7C0u + (codepoint >> 10u)),
  13145. static_cast<std::uint16_t>(0xDC00u + (codepoint & 0x3FFu)));
  13146. bytes += 12;
  13147. }
  13148. }
  13149. else
  13150. {
  13151. // copy byte to buffer (all previous bytes
  13152. // been copied have in default case above)
  13153. string_buffer[bytes++] = s[i];
  13154. }
  13155. break;
  13156. }
  13157. }
  13158. // write buffer and reset index; there must be 13 bytes
  13159. // left, as this is the maximal number of bytes to be
  13160. // written ("\uxxxx\uxxxx\0") for one code point
  13161. if (string_buffer.size() - bytes < 13)
  13162. {
  13163. o->write_characters(string_buffer.data(), bytes);
  13164. bytes = 0;
  13165. }
  13166. // remember the byte position of this accept
  13167. bytes_after_last_accept = bytes;
  13168. undumped_chars = 0;
  13169. break;
  13170. }
  13171. case UTF8_REJECT: // decode found invalid UTF-8 byte
  13172. {
  13173. switch (error_handler)
  13174. {
  13175. case error_handler_t::strict:
  13176. {
  13177. std::string sn(3, '\0');
  13178. (std::snprintf)(&sn[0], sn.size(), "%.2X", byte);
  13179. JSON_THROW(type_error::create(316, "invalid UTF-8 byte at index " + std::to_string(i) + ": 0x" + sn));
  13180. }
  13181. case error_handler_t::ignore:
  13182. case error_handler_t::replace:
  13183. {
  13184. // in case we saw this character the first time, we
  13185. // would like to read it again, because the byte
  13186. // may be OK for itself, but just not OK for the
  13187. // previous sequence
  13188. if (undumped_chars > 0)
  13189. {
  13190. --i;
  13191. }
  13192. // reset length buffer to the last accepted index;
  13193. // thus removing/ignoring the invalid characters
  13194. bytes = bytes_after_last_accept;
  13195. if (error_handler == error_handler_t::replace)
  13196. {
  13197. // add a replacement character
  13198. if (ensure_ascii)
  13199. {
  13200. string_buffer[bytes++] = '\\';
  13201. string_buffer[bytes++] = 'u';
  13202. string_buffer[bytes++] = 'f';
  13203. string_buffer[bytes++] = 'f';
  13204. string_buffer[bytes++] = 'f';
  13205. string_buffer[bytes++] = 'd';
  13206. }
  13207. else
  13208. {
  13209. string_buffer[bytes++] = detail::binary_writer<BasicJsonType, char>::to_char_type('\xEF');
  13210. string_buffer[bytes++] = detail::binary_writer<BasicJsonType, char>::to_char_type('\xBF');
  13211. string_buffer[bytes++] = detail::binary_writer<BasicJsonType, char>::to_char_type('\xBD');
  13212. }
  13213. // write buffer and reset index; there must be 13 bytes
  13214. // left, as this is the maximal number of bytes to be
  13215. // written ("\uxxxx\uxxxx\0") for one code point
  13216. if (string_buffer.size() - bytes < 13)
  13217. {
  13218. o->write_characters(string_buffer.data(), bytes);
  13219. bytes = 0;
  13220. }
  13221. bytes_after_last_accept = bytes;
  13222. }
  13223. undumped_chars = 0;
  13224. // continue processing the string
  13225. state = UTF8_ACCEPT;
  13226. break;
  13227. }
  13228. default: // LCOV_EXCL_LINE
  13229. assert(false); // LCOV_EXCL_LINE
  13230. }
  13231. break;
  13232. }
  13233. default: // decode found yet incomplete multi-byte code point
  13234. {
  13235. if (not ensure_ascii)
  13236. {
  13237. // code point will not be escaped - copy byte to buffer
  13238. string_buffer[bytes++] = s[i];
  13239. }
  13240. ++undumped_chars;
  13241. break;
  13242. }
  13243. }
  13244. }
  13245. // we finished processing the string
  13246. if (JSON_HEDLEY_LIKELY(state == UTF8_ACCEPT))
  13247. {
  13248. // write buffer
  13249. if (bytes > 0)
  13250. {
  13251. o->write_characters(string_buffer.data(), bytes);
  13252. }
  13253. }
  13254. else
  13255. {
  13256. // we finish reading, but do not accept: string was incomplete
  13257. switch (error_handler)
  13258. {
  13259. case error_handler_t::strict:
  13260. {
  13261. std::string sn(3, '\0');
  13262. (std::snprintf)(&sn[0], sn.size(), "%.2X", static_cast<std::uint8_t>(s.back()));
  13263. JSON_THROW(type_error::create(316, "incomplete UTF-8 string; last byte: 0x" + sn));
  13264. }
  13265. case error_handler_t::ignore:
  13266. {
  13267. // write all accepted bytes
  13268. o->write_characters(string_buffer.data(), bytes_after_last_accept);
  13269. break;
  13270. }
  13271. case error_handler_t::replace:
  13272. {
  13273. // write all accepted bytes
  13274. o->write_characters(string_buffer.data(), bytes_after_last_accept);
  13275. // add a replacement character
  13276. if (ensure_ascii)
  13277. {
  13278. o->write_characters("\\ufffd", 6);
  13279. }
  13280. else
  13281. {
  13282. o->write_characters("\xEF\xBF\xBD", 3);
  13283. }
  13284. break;
  13285. }
  13286. default: // LCOV_EXCL_LINE
  13287. assert(false); // LCOV_EXCL_LINE
  13288. }
  13289. }
  13290. }
  13291. /*!
  13292. @brief count digits
  13293. Count the number of decimal (base 10) digits for an input unsigned integer.
  13294. @param[in] x unsigned integer number to count its digits
  13295. @return number of decimal digits
  13296. */
  13297. inline unsigned int count_digits(number_unsigned_t x) noexcept
  13298. {
  13299. unsigned int n_digits = 1;
  13300. for (;;)
  13301. {
  13302. if (x < 10)
  13303. {
  13304. return n_digits;
  13305. }
  13306. if (x < 100)
  13307. {
  13308. return n_digits + 1;
  13309. }
  13310. if (x < 1000)
  13311. {
  13312. return n_digits + 2;
  13313. }
  13314. if (x < 10000)
  13315. {
  13316. return n_digits + 3;
  13317. }
  13318. x = x / 10000u;
  13319. n_digits += 4;
  13320. }
  13321. }
  13322. /*!
  13323. @brief dump an integer
  13324. Dump a given integer to output stream @a o. Works internally with
  13325. @a number_buffer.
  13326. @param[in] x integer number (signed or unsigned) to dump
  13327. @tparam NumberType either @a number_integer_t or @a number_unsigned_t
  13328. */
  13329. template<typename NumberType, detail::enable_if_t<
  13330. std::is_same<NumberType, number_unsigned_t>::value or
  13331. std::is_same<NumberType, number_integer_t>::value or
  13332. std::is_same<NumberType, typename binary_t::value_type>::value,
  13333. int> = 0>
  13334. void dump_integer(NumberType x)
  13335. {
  13336. static constexpr std::array<std::array<char, 2>, 100> digits_to_99
  13337. {
  13338. {
  13339. {{'0', '0'}}, {{'0', '1'}}, {{'0', '2'}}, {{'0', '3'}}, {{'0', '4'}}, {{'0', '5'}}, {{'0', '6'}}, {{'0', '7'}}, {{'0', '8'}}, {{'0', '9'}},
  13340. {{'1', '0'}}, {{'1', '1'}}, {{'1', '2'}}, {{'1', '3'}}, {{'1', '4'}}, {{'1', '5'}}, {{'1', '6'}}, {{'1', '7'}}, {{'1', '8'}}, {{'1', '9'}},
  13341. {{'2', '0'}}, {{'2', '1'}}, {{'2', '2'}}, {{'2', '3'}}, {{'2', '4'}}, {{'2', '5'}}, {{'2', '6'}}, {{'2', '7'}}, {{'2', '8'}}, {{'2', '9'}},
  13342. {{'3', '0'}}, {{'3', '1'}}, {{'3', '2'}}, {{'3', '3'}}, {{'3', '4'}}, {{'3', '5'}}, {{'3', '6'}}, {{'3', '7'}}, {{'3', '8'}}, {{'3', '9'}},
  13343. {{'4', '0'}}, {{'4', '1'}}, {{'4', '2'}}, {{'4', '3'}}, {{'4', '4'}}, {{'4', '5'}}, {{'4', '6'}}, {{'4', '7'}}, {{'4', '8'}}, {{'4', '9'}},
  13344. {{'5', '0'}}, {{'5', '1'}}, {{'5', '2'}}, {{'5', '3'}}, {{'5', '4'}}, {{'5', '5'}}, {{'5', '6'}}, {{'5', '7'}}, {{'5', '8'}}, {{'5', '9'}},
  13345. {{'6', '0'}}, {{'6', '1'}}, {{'6', '2'}}, {{'6', '3'}}, {{'6', '4'}}, {{'6', '5'}}, {{'6', '6'}}, {{'6', '7'}}, {{'6', '8'}}, {{'6', '9'}},
  13346. {{'7', '0'}}, {{'7', '1'}}, {{'7', '2'}}, {{'7', '3'}}, {{'7', '4'}}, {{'7', '5'}}, {{'7', '6'}}, {{'7', '7'}}, {{'7', '8'}}, {{'7', '9'}},
  13347. {{'8', '0'}}, {{'8', '1'}}, {{'8', '2'}}, {{'8', '3'}}, {{'8', '4'}}, {{'8', '5'}}, {{'8', '6'}}, {{'8', '7'}}, {{'8', '8'}}, {{'8', '9'}},
  13348. {{'9', '0'}}, {{'9', '1'}}, {{'9', '2'}}, {{'9', '3'}}, {{'9', '4'}}, {{'9', '5'}}, {{'9', '6'}}, {{'9', '7'}}, {{'9', '8'}}, {{'9', '9'}},
  13349. }
  13350. };
  13351. // special case for "0"
  13352. if (x == 0)
  13353. {
  13354. o->write_character('0');
  13355. return;
  13356. }
  13357. // use a pointer to fill the buffer
  13358. auto buffer_ptr = number_buffer.begin();
  13359. const bool is_negative = std::is_same<NumberType, number_integer_t>::value and not(x >= 0); // see issue #755
  13360. number_unsigned_t abs_value;
  13361. unsigned int n_chars;
  13362. if (is_negative)
  13363. {
  13364. *buffer_ptr = '-';
  13365. abs_value = remove_sign(static_cast<number_integer_t>(x));
  13366. // account one more byte for the minus sign
  13367. n_chars = 1 + count_digits(abs_value);
  13368. }
  13369. else
  13370. {
  13371. abs_value = static_cast<number_unsigned_t>(x);
  13372. n_chars = count_digits(abs_value);
  13373. }
  13374. // spare 1 byte for '\0'
  13375. assert(n_chars < number_buffer.size() - 1);
  13376. // jump to the end to generate the string from backward
  13377. // so we later avoid reversing the result
  13378. buffer_ptr += n_chars;
  13379. // Fast int2ascii implementation inspired by "Fastware" talk by Andrei Alexandrescu
  13380. // See: https://www.youtube.com/watch?v=o4-CwDo2zpg
  13381. while (abs_value >= 100)
  13382. {
  13383. const auto digits_index = static_cast<unsigned>((abs_value % 100));
  13384. abs_value /= 100;
  13385. *(--buffer_ptr) = digits_to_99[digits_index][1];
  13386. *(--buffer_ptr) = digits_to_99[digits_index][0];
  13387. }
  13388. if (abs_value >= 10)
  13389. {
  13390. const auto digits_index = static_cast<unsigned>(abs_value);
  13391. *(--buffer_ptr) = digits_to_99[digits_index][1];
  13392. *(--buffer_ptr) = digits_to_99[digits_index][0];
  13393. }
  13394. else
  13395. {
  13396. *(--buffer_ptr) = static_cast<char>('0' + abs_value);
  13397. }
  13398. o->write_characters(number_buffer.data(), n_chars);
  13399. }
  13400. /*!
  13401. @brief dump a floating-point number
  13402. Dump a given floating-point number to output stream @a o. Works internally
  13403. with @a number_buffer.
  13404. @param[in] x floating-point number to dump
  13405. */
  13406. void dump_float(number_float_t x)
  13407. {
  13408. // NaN / inf
  13409. if (not std::isfinite(x))
  13410. {
  13411. o->write_characters("null", 4);
  13412. return;
  13413. }
  13414. // If number_float_t is an IEEE-754 single or double precision number,
  13415. // use the Grisu2 algorithm to produce short numbers which are
  13416. // guaranteed to round-trip, using strtof and strtod, resp.
  13417. //
  13418. // NB: The test below works if <long double> == <double>.
  13419. static constexpr bool is_ieee_single_or_double
  13420. = (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
  13421. (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);
  13422. dump_float(x, std::integral_constant<bool, is_ieee_single_or_double>());
  13423. }
  13424. void dump_float(number_float_t x, std::true_type /*is_ieee_single_or_double*/)
  13425. {
  13426. char* begin = number_buffer.data();
  13427. char* end = ::nlohmann::detail::to_chars(begin, begin + number_buffer.size(), x);
  13428. o->write_characters(begin, static_cast<size_t>(end - begin));
  13429. }
  13430. void dump_float(number_float_t x, std::false_type /*is_ieee_single_or_double*/)
  13431. {
  13432. // get number of digits for a float -> text -> float round-trip
  13433. static constexpr auto d = std::numeric_limits<number_float_t>::max_digits10;
  13434. // the actual conversion
  13435. std::ptrdiff_t len = (std::snprintf)(number_buffer.data(), number_buffer.size(), "%.*g", d, x);
  13436. // negative value indicates an error
  13437. assert(len > 0);
  13438. // check if buffer was large enough
  13439. assert(static_cast<std::size_t>(len) < number_buffer.size());
  13440. // erase thousands separator
  13441. if (thousands_sep != '\0')
  13442. {
  13443. const auto end = std::remove(number_buffer.begin(),
  13444. number_buffer.begin() + len, thousands_sep);
  13445. std::fill(end, number_buffer.end(), '\0');
  13446. assert((end - number_buffer.begin()) <= len);
  13447. len = (end - number_buffer.begin());
  13448. }
  13449. // convert decimal point to '.'
  13450. if (decimal_point != '\0' and decimal_point != '.')
  13451. {
  13452. const auto dec_pos = std::find(number_buffer.begin(), number_buffer.end(), decimal_point);
  13453. if (dec_pos != number_buffer.end())
  13454. {
  13455. *dec_pos = '.';
  13456. }
  13457. }
  13458. o->write_characters(number_buffer.data(), static_cast<std::size_t>(len));
  13459. // determine if need to append ".0"
  13460. const bool value_is_int_like =
  13461. std::none_of(number_buffer.begin(), number_buffer.begin() + len + 1,
  13462. [](char c)
  13463. {
  13464. return c == '.' or c == 'e';
  13465. });
  13466. if (value_is_int_like)
  13467. {
  13468. o->write_characters(".0", 2);
  13469. }
  13470. }
  13471. /*!
  13472. @brief check whether a string is UTF-8 encoded
  13473. The function checks each byte of a string whether it is UTF-8 encoded. The
  13474. result of the check is stored in the @a state parameter. The function must
  13475. be called initially with state 0 (accept). State 1 means the string must
  13476. be rejected, because the current byte is not allowed. If the string is
  13477. completely processed, but the state is non-zero, the string ended
  13478. prematurely; that is, the last byte indicated more bytes should have
  13479. followed.
  13480. @param[in,out] state the state of the decoding
  13481. @param[in,out] codep codepoint (valid only if resulting state is UTF8_ACCEPT)
  13482. @param[in] byte next byte to decode
  13483. @return new state
  13484. @note The function has been edited: a std::array is used.
  13485. @copyright Copyright (c) 2008-2009 Bjoern Hoehrmann <bjoern@hoehrmann.de>
  13486. @sa http://bjoern.hoehrmann.de/utf-8/decoder/dfa/
  13487. */
  13488. static std::uint8_t decode(std::uint8_t& state, std::uint32_t& codep, const std::uint8_t byte) noexcept
  13489. {
  13490. static const std::array<std::uint8_t, 400> utf8d =
  13491. {
  13492. {
  13493. 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
  13494. 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
  13495. 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
  13496. 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
  13497. 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
  13498. 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
  13499. 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
  13500. 0xA, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x4, 0x3, 0x3, // E0..EF
  13501. 0xB, 0x6, 0x6, 0x6, 0x5, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, // F0..FF
  13502. 0x0, 0x1, 0x2, 0x3, 0x5, 0x8, 0x7, 0x1, 0x1, 0x1, 0x4, 0x6, 0x1, 0x1, 0x1, 0x1, // s0..s0
  13503. 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
  13504. 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
  13505. 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
  13506. 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
  13507. }
  13508. };
  13509. const std::uint8_t type = utf8d[byte];
  13510. codep = (state != UTF8_ACCEPT)
  13511. ? (byte & 0x3fu) | (codep << 6u)
  13512. : (0xFFu >> type) & (byte);
  13513. std::size_t index = 256u + static_cast<size_t>(state) * 16u + static_cast<size_t>(type);
  13514. assert(index < 400);
  13515. state = utf8d[index];
  13516. return state;
  13517. }
  13518. /*
  13519. * Overload to make the compiler happy while it is instantiating
  13520. * dump_integer for number_unsigned_t.
  13521. * Must never be called.
  13522. */
  13523. number_unsigned_t remove_sign(number_unsigned_t x)
  13524. {
  13525. assert(false); // LCOV_EXCL_LINE
  13526. return x; // LCOV_EXCL_LINE
  13527. }
  13528. /*
  13529. * Helper function for dump_integer
  13530. *
  13531. * This function takes a negative signed integer and returns its absolute
  13532. * value as unsigned integer. The plus/minus shuffling is necessary as we can
  13533. * not directly remove the sign of an arbitrary signed integer as the
  13534. * absolute values of INT_MIN and INT_MAX are usually not the same. See
  13535. * #1708 for details.
  13536. */
  13537. inline number_unsigned_t remove_sign(number_integer_t x) noexcept
  13538. {
  13539. assert(x < 0 and x < (std::numeric_limits<number_integer_t>::max)());
  13540. return static_cast<number_unsigned_t>(-(x + 1)) + 1;
  13541. }
  13542. private:
  13543. /// the output of the serializer
  13544. output_adapter_t<char> o = nullptr;
  13545. /// a (hopefully) large enough character buffer
  13546. std::array<char, 64> number_buffer{{}};
  13547. /// the locale
  13548. const std::lconv* loc = nullptr;
  13549. /// the locale's thousand separator character
  13550. const char thousands_sep = '\0';
  13551. /// the locale's decimal point character
  13552. const char decimal_point = '\0';
  13553. /// string buffer
  13554. std::array<char, 512> string_buffer{{}};
  13555. /// the indentation character
  13556. const char indent_char;
  13557. /// the indentation string
  13558. string_t indent_string;
  13559. /// error_handler how to react on decoding errors
  13560. const error_handler_t error_handler;
  13561. };
  13562. } // namespace detail
  13563. } // namespace nlohmann
  13564. // #include <nlohmann/detail/value_t.hpp>
  13565. // #include <nlohmann/json_fwd.hpp>
  13566. /*!
  13567. @brief namespace for Niels Lohmann
  13568. @see https://github.com/nlohmann
  13569. @since version 1.0.0
  13570. */
  13571. namespace nlohmann
  13572. {
  13573. /*!
  13574. @brief a class to store JSON values
  13575. @tparam ObjectType type for JSON objects (`std::map` by default; will be used
  13576. in @ref object_t)
  13577. @tparam ArrayType type for JSON arrays (`std::vector` by default; will be used
  13578. in @ref array_t)
  13579. @tparam StringType type for JSON strings and object keys (`std::string` by
  13580. default; will be used in @ref string_t)
  13581. @tparam BooleanType type for JSON booleans (`bool` by default; will be used
  13582. in @ref boolean_t)
  13583. @tparam NumberIntegerType type for JSON integer numbers (`int64_t` by
  13584. default; will be used in @ref number_integer_t)
  13585. @tparam NumberUnsignedType type for JSON unsigned integer numbers (@c
  13586. `uint64_t` by default; will be used in @ref number_unsigned_t)
  13587. @tparam NumberFloatType type for JSON floating-point numbers (`double` by
  13588. default; will be used in @ref number_float_t)
  13589. @tparam BinaryType type for packed binary data for compatibility with binary
  13590. serialization formats (`std::vector<std::uint8_t>` by default; will be used in
  13591. @ref binary_t)
  13592. @tparam AllocatorType type of the allocator to use (`std::allocator` by
  13593. default)
  13594. @tparam JSONSerializer the serializer to resolve internal calls to `to_json()`
  13595. and `from_json()` (@ref adl_serializer by default)
  13596. @requirement The class satisfies the following concept requirements:
  13597. - Basic
  13598. - [DefaultConstructible](https://en.cppreference.com/w/cpp/named_req/DefaultConstructible):
  13599. JSON values can be default constructed. The result will be a JSON null
  13600. value.
  13601. - [MoveConstructible](https://en.cppreference.com/w/cpp/named_req/MoveConstructible):
  13602. A JSON value can be constructed from an rvalue argument.
  13603. - [CopyConstructible](https://en.cppreference.com/w/cpp/named_req/CopyConstructible):
  13604. A JSON value can be copy-constructed from an lvalue expression.
  13605. - [MoveAssignable](https://en.cppreference.com/w/cpp/named_req/MoveAssignable):
  13606. A JSON value van be assigned from an rvalue argument.
  13607. - [CopyAssignable](https://en.cppreference.com/w/cpp/named_req/CopyAssignable):
  13608. A JSON value can be copy-assigned from an lvalue expression.
  13609. - [Destructible](https://en.cppreference.com/w/cpp/named_req/Destructible):
  13610. JSON values can be destructed.
  13611. - Layout
  13612. - [StandardLayoutType](https://en.cppreference.com/w/cpp/named_req/StandardLayoutType):
  13613. JSON values have
  13614. [standard layout](https://en.cppreference.com/w/cpp/language/data_members#Standard_layout):
  13615. All non-static data members are private and standard layout types, the
  13616. class has no virtual functions or (virtual) base classes.
  13617. - Library-wide
  13618. - [EqualityComparable](https://en.cppreference.com/w/cpp/named_req/EqualityComparable):
  13619. JSON values can be compared with `==`, see @ref
  13620. operator==(const_reference,const_reference).
  13621. - [LessThanComparable](https://en.cppreference.com/w/cpp/named_req/LessThanComparable):
  13622. JSON values can be compared with `<`, see @ref
  13623. operator<(const_reference,const_reference).
  13624. - [Swappable](https://en.cppreference.com/w/cpp/named_req/Swappable):
  13625. Any JSON lvalue or rvalue of can be swapped with any lvalue or rvalue of
  13626. other compatible types, using unqualified function call @ref swap().
  13627. - [NullablePointer](https://en.cppreference.com/w/cpp/named_req/NullablePointer):
  13628. JSON values can be compared against `std::nullptr_t` objects which are used
  13629. to model the `null` value.
  13630. - Container
  13631. - [Container](https://en.cppreference.com/w/cpp/named_req/Container):
  13632. JSON values can be used like STL containers and provide iterator access.
  13633. - [ReversibleContainer](https://en.cppreference.com/w/cpp/named_req/ReversibleContainer);
  13634. JSON values can be used like STL containers and provide reverse iterator
  13635. access.
  13636. @invariant The member variables @a m_value and @a m_type have the following
  13637. relationship:
  13638. - If `m_type == value_t::object`, then `m_value.object != nullptr`.
  13639. - If `m_type == value_t::array`, then `m_value.array != nullptr`.
  13640. - If `m_type == value_t::string`, then `m_value.string != nullptr`.
  13641. The invariants are checked by member function assert_invariant().
  13642. @internal
  13643. @note ObjectType trick from https://stackoverflow.com/a/9860911
  13644. @endinternal
  13645. @see [RFC 7159: The JavaScript Object Notation (JSON) Data Interchange
  13646. Format](http://rfc7159.net/rfc7159)
  13647. @since version 1.0.0
  13648. @nosubgrouping
  13649. */
  13650. NLOHMANN_BASIC_JSON_TPL_DECLARATION
  13651. class basic_json
  13652. {
  13653. private:
  13654. template<detail::value_t> friend struct detail::external_constructor;
  13655. friend ::nlohmann::json_pointer<basic_json>;
  13656. friend ::nlohmann::detail::parser<basic_json>;
  13657. friend ::nlohmann::detail::serializer<basic_json>;
  13658. template<typename BasicJsonType>
  13659. friend class ::nlohmann::detail::iter_impl;
  13660. template<typename BasicJsonType, typename CharType>
  13661. friend class ::nlohmann::detail::binary_writer;
  13662. template<typename BasicJsonType, typename SAX>
  13663. friend class ::nlohmann::detail::binary_reader;
  13664. template<typename BasicJsonType>
  13665. friend class ::nlohmann::detail::json_sax_dom_parser;
  13666. template<typename BasicJsonType>
  13667. friend class ::nlohmann::detail::json_sax_dom_callback_parser;
  13668. /// workaround type for MSVC
  13669. using basic_json_t = NLOHMANN_BASIC_JSON_TPL;
  13670. // convenience aliases for types residing in namespace detail;
  13671. using lexer = ::nlohmann::detail::lexer<basic_json>;
  13672. using parser = ::nlohmann::detail::parser<basic_json>;
  13673. using primitive_iterator_t = ::nlohmann::detail::primitive_iterator_t;
  13674. template<typename BasicJsonType>
  13675. using internal_iterator = ::nlohmann::detail::internal_iterator<BasicJsonType>;
  13676. template<typename BasicJsonType>
  13677. using iter_impl = ::nlohmann::detail::iter_impl<BasicJsonType>;
  13678. template<typename Iterator>
  13679. using iteration_proxy = ::nlohmann::detail::iteration_proxy<Iterator>;
  13680. template<typename Base> using json_reverse_iterator = ::nlohmann::detail::json_reverse_iterator<Base>;
  13681. template<typename CharType>
  13682. using output_adapter_t = ::nlohmann::detail::output_adapter_t<CharType>;
  13683. using binary_reader = ::nlohmann::detail::binary_reader<basic_json>;
  13684. template<typename CharType> using binary_writer = ::nlohmann::detail::binary_writer<basic_json, CharType>;
  13685. using serializer = ::nlohmann::detail::serializer<basic_json>;
  13686. public:
  13687. using value_t = detail::value_t;
  13688. /// JSON Pointer, see @ref nlohmann::json_pointer
  13689. using json_pointer = ::nlohmann::json_pointer<basic_json>;
  13690. template<typename T, typename SFINAE>
  13691. using json_serializer = JSONSerializer<T, SFINAE>;
  13692. /// how to treat decoding errors
  13693. using error_handler_t = detail::error_handler_t;
  13694. /// helper type for initializer lists of basic_json values
  13695. using initializer_list_t = std::initializer_list<detail::json_ref<basic_json>>;
  13696. using input_format_t = detail::input_format_t;
  13697. /// SAX interface type, see @ref nlohmann::json_sax
  13698. using json_sax_t = json_sax<basic_json>;
  13699. ////////////////
  13700. // exceptions //
  13701. ////////////////
  13702. /// @name exceptions
  13703. /// Classes to implement user-defined exceptions.
  13704. /// @{
  13705. /// @copydoc detail::exception
  13706. using exception = detail::exception;
  13707. /// @copydoc detail::parse_error
  13708. using parse_error = detail::parse_error;
  13709. /// @copydoc detail::invalid_iterator
  13710. using invalid_iterator = detail::invalid_iterator;
  13711. /// @copydoc detail::type_error
  13712. using type_error = detail::type_error;
  13713. /// @copydoc detail::out_of_range
  13714. using out_of_range = detail::out_of_range;
  13715. /// @copydoc detail::other_error
  13716. using other_error = detail::other_error;
  13717. /// @}
  13718. /////////////////////
  13719. // container types //
  13720. /////////////////////
  13721. /// @name container types
  13722. /// The canonic container types to use @ref basic_json like any other STL
  13723. /// container.
  13724. /// @{
  13725. /// the type of elements in a basic_json container
  13726. using value_type = basic_json;
  13727. /// the type of an element reference
  13728. using reference = value_type&;
  13729. /// the type of an element const reference
  13730. using const_reference = const value_type&;
  13731. /// a type to represent differences between iterators
  13732. using difference_type = std::ptrdiff_t;
  13733. /// a type to represent container sizes
  13734. using size_type = std::size_t;
  13735. /// the allocator type
  13736. using allocator_type = AllocatorType<basic_json>;
  13737. /// the type of an element pointer
  13738. using pointer = typename std::allocator_traits<allocator_type>::pointer;
  13739. /// the type of an element const pointer
  13740. using const_pointer = typename std::allocator_traits<allocator_type>::const_pointer;
  13741. /// an iterator for a basic_json container
  13742. using iterator = iter_impl<basic_json>;
  13743. /// a const iterator for a basic_json container
  13744. using const_iterator = iter_impl<const basic_json>;
  13745. /// a reverse iterator for a basic_json container
  13746. using reverse_iterator = json_reverse_iterator<typename basic_json::iterator>;
  13747. /// a const reverse iterator for a basic_json container
  13748. using const_reverse_iterator = json_reverse_iterator<typename basic_json::const_iterator>;
  13749. /// @}
  13750. /*!
  13751. @brief returns the allocator associated with the container
  13752. */
  13753. static allocator_type get_allocator()
  13754. {
  13755. return allocator_type();
  13756. }
  13757. /*!
  13758. @brief returns version information on the library
  13759. This function returns a JSON object with information about the library,
  13760. including the version number and information on the platform and compiler.
  13761. @return JSON object holding version information
  13762. key | description
  13763. ----------- | ---------------
  13764. `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).
  13765. `copyright` | The copyright line for the library as string.
  13766. `name` | The name of the library as string.
  13767. `platform` | The used platform as string. Possible values are `win32`, `linux`, `apple`, `unix`, and `unknown`.
  13768. `url` | The URL of the project as string.
  13769. `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).
  13770. @liveexample{The following code shows an example output of the `meta()`
  13771. function.,meta}
  13772. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  13773. changes to any JSON value.
  13774. @complexity Constant.
  13775. @since 2.1.0
  13776. */
  13777. JSON_HEDLEY_WARN_UNUSED_RESULT
  13778. static basic_json meta()
  13779. {
  13780. basic_json result;
  13781. result["copyright"] = "(C) 2013-2017 Niels Lohmann";
  13782. result["name"] = "JSON for Modern C++";
  13783. result["url"] = "https://github.com/nlohmann/json";
  13784. result["version"]["string"] =
  13785. std::to_string(NLOHMANN_JSON_VERSION_MAJOR) + "." +
  13786. std::to_string(NLOHMANN_JSON_VERSION_MINOR) + "." +
  13787. std::to_string(NLOHMANN_JSON_VERSION_PATCH);
  13788. result["version"]["major"] = NLOHMANN_JSON_VERSION_MAJOR;
  13789. result["version"]["minor"] = NLOHMANN_JSON_VERSION_MINOR;
  13790. result["version"]["patch"] = NLOHMANN_JSON_VERSION_PATCH;
  13791. #ifdef _WIN32
  13792. result["platform"] = "win32";
  13793. #elif defined __linux__
  13794. result["platform"] = "linux";
  13795. #elif defined __APPLE__
  13796. result["platform"] = "apple";
  13797. #elif defined __unix__
  13798. result["platform"] = "unix";
  13799. #else
  13800. result["platform"] = "unknown";
  13801. #endif
  13802. #if defined(__ICC) || defined(__INTEL_COMPILER)
  13803. result["compiler"] = {{"family", "icc"}, {"version", __INTEL_COMPILER}};
  13804. #elif defined(__clang__)
  13805. result["compiler"] = {{"family", "clang"}, {"version", __clang_version__}};
  13806. #elif defined(__GNUC__) || defined(__GNUG__)
  13807. result["compiler"] = {{"family", "gcc"}, {"version", std::to_string(__GNUC__) + "." + std::to_string(__GNUC_MINOR__) + "." + std::to_string(__GNUC_PATCHLEVEL__)}};
  13808. #elif defined(__HP_cc) || defined(__HP_aCC)
  13809. result["compiler"] = "hp"
  13810. #elif defined(__IBMCPP__)
  13811. result["compiler"] = {{"family", "ilecpp"}, {"version", __IBMCPP__}};
  13812. #elif defined(_MSC_VER)
  13813. result["compiler"] = {{"family", "msvc"}, {"version", _MSC_VER}};
  13814. #elif defined(__PGI)
  13815. result["compiler"] = {{"family", "pgcpp"}, {"version", __PGI}};
  13816. #elif defined(__SUNPRO_CC)
  13817. result["compiler"] = {{"family", "sunpro"}, {"version", __SUNPRO_CC}};
  13818. #else
  13819. result["compiler"] = {{"family", "unknown"}, {"version", "unknown"}};
  13820. #endif
  13821. #ifdef __cplusplus
  13822. result["compiler"]["c++"] = std::to_string(__cplusplus);
  13823. #else
  13824. result["compiler"]["c++"] = "unknown";
  13825. #endif
  13826. return result;
  13827. }
  13828. ///////////////////////////
  13829. // JSON value data types //
  13830. ///////////////////////////
  13831. /// @name JSON value data types
  13832. /// The data types to store a JSON value. These types are derived from
  13833. /// the template arguments passed to class @ref basic_json.
  13834. /// @{
  13835. #if defined(JSON_HAS_CPP_14)
  13836. // Use transparent comparator if possible, combined with perfect forwarding
  13837. // on find() and count() calls prevents unnecessary string construction.
  13838. using object_comparator_t = std::less<>;
  13839. #else
  13840. using object_comparator_t = std::less<StringType>;
  13841. #endif
  13842. /*!
  13843. @brief a type for an object
  13844. [RFC 7159](http://rfc7159.net/rfc7159) describes JSON objects as follows:
  13845. > An object is an unordered collection of zero or more name/value pairs,
  13846. > where a name is a string and a value is a string, number, boolean, null,
  13847. > object, or array.
  13848. To store objects in C++, a type is defined by the template parameters
  13849. described below.
  13850. @tparam ObjectType the container to store objects (e.g., `std::map` or
  13851. `std::unordered_map`)
  13852. @tparam StringType the type of the keys or names (e.g., `std::string`).
  13853. The comparison function `std::less<StringType>` is used to order elements
  13854. inside the container.
  13855. @tparam AllocatorType the allocator to use for objects (e.g.,
  13856. `std::allocator`)
  13857. #### Default type
  13858. With the default values for @a ObjectType (`std::map`), @a StringType
  13859. (`std::string`), and @a AllocatorType (`std::allocator`), the default
  13860. value for @a object_t is:
  13861. @code {.cpp}
  13862. std::map<
  13863. std::string, // key_type
  13864. basic_json, // value_type
  13865. std::less<std::string>, // key_compare
  13866. std::allocator<std::pair<const std::string, basic_json>> // allocator_type
  13867. >
  13868. @endcode
  13869. #### Behavior
  13870. The choice of @a object_t influences the behavior of the JSON class. With
  13871. the default type, objects have the following behavior:
  13872. - When all names are unique, objects will be interoperable in the sense
  13873. that all software implementations receiving that object will agree on
  13874. the name-value mappings.
  13875. - When the names within an object are not unique, it is unspecified which
  13876. one of the values for a given key will be chosen. For instance,
  13877. `{"key": 2, "key": 1}` could be equal to either `{"key": 1}` or
  13878. `{"key": 2}`.
  13879. - Internally, name/value pairs are stored in lexicographical order of the
  13880. names. Objects will also be serialized (see @ref dump) in this order.
  13881. For instance, `{"b": 1, "a": 2}` and `{"a": 2, "b": 1}` will be stored
  13882. and serialized as `{"a": 2, "b": 1}`.
  13883. - When comparing objects, the order of the name/value pairs is irrelevant.
  13884. This makes objects interoperable in the sense that they will not be
  13885. affected by these differences. For instance, `{"b": 1, "a": 2}` and
  13886. `{"a": 2, "b": 1}` will be treated as equal.
  13887. #### Limits
  13888. [RFC 7159](http://rfc7159.net/rfc7159) specifies:
  13889. > An implementation may set limits on the maximum depth of nesting.
  13890. In this class, the object's limit of nesting is not explicitly constrained.
  13891. However, a maximum depth of nesting may be introduced by the compiler or
  13892. runtime environment. A theoretical limit can be queried by calling the
  13893. @ref max_size function of a JSON object.
  13894. #### Storage
  13895. Objects are stored as pointers in a @ref basic_json type. That is, for any
  13896. access to object values, a pointer of type `object_t*` must be
  13897. dereferenced.
  13898. @sa @ref array_t -- type for an array value
  13899. @since version 1.0.0
  13900. @note The order name/value pairs are added to the object is *not*
  13901. preserved by the library. Therefore, iterating an object may return
  13902. name/value pairs in a different order than they were originally stored. In
  13903. fact, keys will be traversed in alphabetical order as `std::map` with
  13904. `std::less` is used by default. Please note this behavior conforms to [RFC
  13905. 7159](http://rfc7159.net/rfc7159), because any order implements the
  13906. specified "unordered" nature of JSON objects.
  13907. */
  13908. using object_t = ObjectType<StringType,
  13909. basic_json,
  13910. object_comparator_t,
  13911. AllocatorType<std::pair<const StringType,
  13912. basic_json>>>;
  13913. /*!
  13914. @brief a type for an array
  13915. [RFC 7159](http://rfc7159.net/rfc7159) describes JSON arrays as follows:
  13916. > An array is an ordered sequence of zero or more values.
  13917. To store objects in C++, a type is defined by the template parameters
  13918. explained below.
  13919. @tparam ArrayType container type to store arrays (e.g., `std::vector` or
  13920. `std::list`)
  13921. @tparam AllocatorType allocator to use for arrays (e.g., `std::allocator`)
  13922. #### Default type
  13923. With the default values for @a ArrayType (`std::vector`) and @a
  13924. AllocatorType (`std::allocator`), the default value for @a array_t is:
  13925. @code {.cpp}
  13926. std::vector<
  13927. basic_json, // value_type
  13928. std::allocator<basic_json> // allocator_type
  13929. >
  13930. @endcode
  13931. #### Limits
  13932. [RFC 7159](http://rfc7159.net/rfc7159) specifies:
  13933. > An implementation may set limits on the maximum depth of nesting.
  13934. In this class, the array's limit of nesting is not explicitly constrained.
  13935. However, a maximum depth of nesting may be introduced by the compiler or
  13936. runtime environment. A theoretical limit can be queried by calling the
  13937. @ref max_size function of a JSON array.
  13938. #### Storage
  13939. Arrays are stored as pointers in a @ref basic_json type. That is, for any
  13940. access to array values, a pointer of type `array_t*` must be dereferenced.
  13941. @sa @ref object_t -- type for an object value
  13942. @since version 1.0.0
  13943. */
  13944. using array_t = ArrayType<basic_json, AllocatorType<basic_json>>;
  13945. /*!
  13946. @brief a type for a string
  13947. [RFC 7159](http://rfc7159.net/rfc7159) describes JSON strings as follows:
  13948. > A string is a sequence of zero or more Unicode characters.
  13949. To store objects in C++, a type is defined by the template parameter
  13950. described below. Unicode values are split by the JSON class into
  13951. byte-sized characters during deserialization.
  13952. @tparam StringType the container to store strings (e.g., `std::string`).
  13953. Note this container is used for keys/names in objects, see @ref object_t.
  13954. #### Default type
  13955. With the default values for @a StringType (`std::string`), the default
  13956. value for @a string_t is:
  13957. @code {.cpp}
  13958. std::string
  13959. @endcode
  13960. #### Encoding
  13961. Strings are stored in UTF-8 encoding. Therefore, functions like
  13962. `std::string::size()` or `std::string::length()` return the number of
  13963. bytes in the string rather than the number of characters or glyphs.
  13964. #### String comparison
  13965. [RFC 7159](http://rfc7159.net/rfc7159) states:
  13966. > Software implementations are typically required to test names of object
  13967. > members for equality. Implementations that transform the textual
  13968. > representation into sequences of Unicode code units and then perform the
  13969. > comparison numerically, code unit by code unit, are interoperable in the
  13970. > sense that implementations will agree in all cases on equality or
  13971. > inequality of two strings. For example, implementations that compare
  13972. > strings with escaped characters unconverted may incorrectly find that
  13973. > `"a\\b"` and `"a\u005Cb"` are not equal.
  13974. This implementation is interoperable as it does compare strings code unit
  13975. by code unit.
  13976. #### Storage
  13977. String values are stored as pointers in a @ref basic_json type. That is,
  13978. for any access to string values, a pointer of type `string_t*` must be
  13979. dereferenced.
  13980. @since version 1.0.0
  13981. */
  13982. using string_t = StringType;
  13983. /*!
  13984. @brief a type for a boolean
  13985. [RFC 7159](http://rfc7159.net/rfc7159) implicitly describes a boolean as a
  13986. type which differentiates the two literals `true` and `false`.
  13987. To store objects in C++, a type is defined by the template parameter @a
  13988. BooleanType which chooses the type to use.
  13989. #### Default type
  13990. With the default values for @a BooleanType (`bool`), the default value for
  13991. @a boolean_t is:
  13992. @code {.cpp}
  13993. bool
  13994. @endcode
  13995. #### Storage
  13996. Boolean values are stored directly inside a @ref basic_json type.
  13997. @since version 1.0.0
  13998. */
  13999. using boolean_t = BooleanType;
  14000. /*!
  14001. @brief a type for a number (integer)
  14002. [RFC 7159](http://rfc7159.net/rfc7159) describes numbers as follows:
  14003. > The representation of numbers is similar to that used in most
  14004. > programming languages. A number is represented in base 10 using decimal
  14005. > digits. It contains an integer component that may be prefixed with an
  14006. > optional minus sign, which may be followed by a fraction part and/or an
  14007. > exponent part. Leading zeros are not allowed. (...) Numeric values that
  14008. > cannot be represented in the grammar below (such as Infinity and NaN)
  14009. > are not permitted.
  14010. This description includes both integer and floating-point numbers.
  14011. However, C++ allows more precise storage if it is known whether the number
  14012. is a signed integer, an unsigned integer or a floating-point number.
  14013. Therefore, three different types, @ref number_integer_t, @ref
  14014. number_unsigned_t and @ref number_float_t are used.
  14015. To store integer numbers in C++, a type is defined by the template
  14016. parameter @a NumberIntegerType which chooses the type to use.
  14017. #### Default type
  14018. With the default values for @a NumberIntegerType (`int64_t`), the default
  14019. value for @a number_integer_t is:
  14020. @code {.cpp}
  14021. int64_t
  14022. @endcode
  14023. #### Default behavior
  14024. - The restrictions about leading zeros is not enforced in C++. Instead,
  14025. leading zeros in integer literals lead to an interpretation as octal
  14026. number. Internally, the value will be stored as decimal number. For
  14027. instance, the C++ integer literal `010` will be serialized to `8`.
  14028. During deserialization, leading zeros yield an error.
  14029. - Not-a-number (NaN) values will be serialized to `null`.
  14030. #### Limits
  14031. [RFC 7159](http://rfc7159.net/rfc7159) specifies:
  14032. > An implementation may set limits on the range and precision of numbers.
  14033. When the default type is used, the maximal integer number that can be
  14034. stored is `9223372036854775807` (INT64_MAX) and the minimal integer number
  14035. that can be stored is `-9223372036854775808` (INT64_MIN). Integer numbers
  14036. that are out of range will yield over/underflow when used in a
  14037. constructor. During deserialization, too large or small integer numbers
  14038. will be automatically be stored as @ref number_unsigned_t or @ref
  14039. number_float_t.
  14040. [RFC 7159](http://rfc7159.net/rfc7159) further states:
  14041. > Note that when such software is used, numbers that are integers and are
  14042. > in the range \f$[-2^{53}+1, 2^{53}-1]\f$ are interoperable in the sense
  14043. > that implementations will agree exactly on their numeric values.
  14044. As this range is a subrange of the exactly supported range [INT64_MIN,
  14045. INT64_MAX], this class's integer type is interoperable.
  14046. #### Storage
  14047. Integer number values are stored directly inside a @ref basic_json type.
  14048. @sa @ref number_float_t -- type for number values (floating-point)
  14049. @sa @ref number_unsigned_t -- type for number values (unsigned integer)
  14050. @since version 1.0.0
  14051. */
  14052. using number_integer_t = NumberIntegerType;
  14053. /*!
  14054. @brief a type for a number (unsigned)
  14055. [RFC 7159](http://rfc7159.net/rfc7159) describes numbers as follows:
  14056. > The representation of numbers is similar to that used in most
  14057. > programming languages. A number is represented in base 10 using decimal
  14058. > digits. It contains an integer component that may be prefixed with an
  14059. > optional minus sign, which may be followed by a fraction part and/or an
  14060. > exponent part. Leading zeros are not allowed. (...) Numeric values that
  14061. > cannot be represented in the grammar below (such as Infinity and NaN)
  14062. > are not permitted.
  14063. This description includes both integer and floating-point numbers.
  14064. However, C++ allows more precise storage if it is known whether the number
  14065. is a signed integer, an unsigned integer or a floating-point number.
  14066. Therefore, three different types, @ref number_integer_t, @ref
  14067. number_unsigned_t and @ref number_float_t are used.
  14068. To store unsigned integer numbers in C++, a type is defined by the
  14069. template parameter @a NumberUnsignedType which chooses the type to use.
  14070. #### Default type
  14071. With the default values for @a NumberUnsignedType (`uint64_t`), the
  14072. default value for @a number_unsigned_t is:
  14073. @code {.cpp}
  14074. uint64_t
  14075. @endcode
  14076. #### Default behavior
  14077. - The restrictions about leading zeros is not enforced in C++. Instead,
  14078. leading zeros in integer literals lead to an interpretation as octal
  14079. number. Internally, the value will be stored as decimal number. For
  14080. instance, the C++ integer literal `010` will be serialized to `8`.
  14081. During deserialization, leading zeros yield an error.
  14082. - Not-a-number (NaN) values will be serialized to `null`.
  14083. #### Limits
  14084. [RFC 7159](http://rfc7159.net/rfc7159) specifies:
  14085. > An implementation may set limits on the range and precision of numbers.
  14086. When the default type is used, the maximal integer number that can be
  14087. stored is `18446744073709551615` (UINT64_MAX) and the minimal integer
  14088. number that can be stored is `0`. Integer numbers that are out of range
  14089. will yield over/underflow when used in a constructor. During
  14090. deserialization, too large or small integer numbers will be automatically
  14091. be stored as @ref number_integer_t or @ref number_float_t.
  14092. [RFC 7159](http://rfc7159.net/rfc7159) further states:
  14093. > Note that when such software is used, numbers that are integers and are
  14094. > in the range \f$[-2^{53}+1, 2^{53}-1]\f$ are interoperable in the sense
  14095. > that implementations will agree exactly on their numeric values.
  14096. As this range is a subrange (when considered in conjunction with the
  14097. number_integer_t type) of the exactly supported range [0, UINT64_MAX],
  14098. this class's integer type is interoperable.
  14099. #### Storage
  14100. Integer number values are stored directly inside a @ref basic_json type.
  14101. @sa @ref number_float_t -- type for number values (floating-point)
  14102. @sa @ref number_integer_t -- type for number values (integer)
  14103. @since version 2.0.0
  14104. */
  14105. using number_unsigned_t = NumberUnsignedType;
  14106. /*!
  14107. @brief a type for a number (floating-point)
  14108. [RFC 7159](http://rfc7159.net/rfc7159) describes numbers as follows:
  14109. > The representation of numbers is similar to that used in most
  14110. > programming languages. A number is represented in base 10 using decimal
  14111. > digits. It contains an integer component that may be prefixed with an
  14112. > optional minus sign, which may be followed by a fraction part and/or an
  14113. > exponent part. Leading zeros are not allowed. (...) Numeric values that
  14114. > cannot be represented in the grammar below (such as Infinity and NaN)
  14115. > are not permitted.
  14116. This description includes both integer and floating-point numbers.
  14117. However, C++ allows more precise storage if it is known whether the number
  14118. is a signed integer, an unsigned integer or a floating-point number.
  14119. Therefore, three different types, @ref number_integer_t, @ref
  14120. number_unsigned_t and @ref number_float_t are used.
  14121. To store floating-point numbers in C++, a type is defined by the template
  14122. parameter @a NumberFloatType which chooses the type to use.
  14123. #### Default type
  14124. With the default values for @a NumberFloatType (`double`), the default
  14125. value for @a number_float_t is:
  14126. @code {.cpp}
  14127. double
  14128. @endcode
  14129. #### Default behavior
  14130. - The restrictions about leading zeros is not enforced in C++. Instead,
  14131. leading zeros in floating-point literals will be ignored. Internally,
  14132. the value will be stored as decimal number. For instance, the C++
  14133. floating-point literal `01.2` will be serialized to `1.2`. During
  14134. deserialization, leading zeros yield an error.
  14135. - Not-a-number (NaN) values will be serialized to `null`.
  14136. #### Limits
  14137. [RFC 7159](http://rfc7159.net/rfc7159) states:
  14138. > This specification allows implementations to set limits on the range and
  14139. > precision of numbers accepted. Since software that implements IEEE
  14140. > 754-2008 binary64 (double precision) numbers is generally available and
  14141. > widely used, good interoperability can be achieved by implementations
  14142. > that expect no more precision or range than these provide, in the sense
  14143. > that implementations will approximate JSON numbers within the expected
  14144. > precision.
  14145. This implementation does exactly follow this approach, as it uses double
  14146. precision floating-point numbers. Note values smaller than
  14147. `-1.79769313486232e+308` and values greater than `1.79769313486232e+308`
  14148. will be stored as NaN internally and be serialized to `null`.
  14149. #### Storage
  14150. Floating-point number values are stored directly inside a @ref basic_json
  14151. type.
  14152. @sa @ref number_integer_t -- type for number values (integer)
  14153. @sa @ref number_unsigned_t -- type for number values (unsigned integer)
  14154. @since version 1.0.0
  14155. */
  14156. using number_float_t = NumberFloatType;
  14157. /*!
  14158. @brief a type for a packed binary type
  14159. This type is a type designed to carry binary data that appears in various
  14160. serialized formats, such as CBOR's Major Type 2, MessagePack's bin, and
  14161. BSON's generic binary subtype. This type is NOT a part of standard JSON and
  14162. exists solely for compatibility with these binary types. As such, it is
  14163. simply defined as an ordered sequence of zero or more byte values.
  14164. Additionally, as an implementation detail, the subtype of the binary data is
  14165. carried around as a `unint8_t`, which is compatible with both of the binary
  14166. data formats that use binary subtyping, (though the specific numbering is
  14167. incompatible with each other, and it is up to the user to translate between
  14168. them).
  14169. [CBOR's RFC 7049](https://tools.ietf.org/html/rfc7049) describes this type
  14170. as:
  14171. > Major type 2: a byte string. The string's length in bytes is
  14172. > represented following the rules for positive integers (major type
  14173. > 0).
  14174. [MessagePack's documentation on the bin type
  14175. family](https://github.com/msgpack/msgpack/blob/master/spec.md#bin-format-family)
  14176. describes this type as:
  14177. > Bin format family stores an byte array in 2, 3, or 5 bytes of extra bytes
  14178. > in addition to the size of the byte array.
  14179. [BSON's specifications](http://bsonspec.org/spec.html) describe several
  14180. binary types; however, this type is intended to represent the generic binary
  14181. type which has the description:
  14182. > Generic binary subtype - This is the most commonly used binary subtype and
  14183. > should be the 'default' for drivers and tools.
  14184. None of these impose any limitations on the internal representation other
  14185. than the basic unit of storage be some type of array whose parts are
  14186. decomposible into bytes.
  14187. The default representation of this binary format is a
  14188. `std::vector<std::uint8_t>`, which is a very common way to represent a byte
  14189. array in modern C++.
  14190. #### Default type
  14191. The default values for @a BinaryType is `std::vector<std::uint8_t>`
  14192. #### Storage
  14193. Binary Arrays are stored as pointers in a @ref basic_json type. That is,
  14194. for any access to array values, a pointer of the type `binary_t*` must be
  14195. dereferenced.
  14196. @sa @ref array_t -- type for an array value
  14197. @since version 3.8.0
  14198. */
  14199. using binary_t = BinaryType;
  14200. /*!
  14201. @brief an internal type for a backed binary type
  14202. This type is designed to be `binary_t` but with the subtype implementation
  14203. detail. This type exists so that the user does not have to specify a struct
  14204. his- or herself with a specific naming scheme in order to override the
  14205. binary type. I.e. it's for ease of use.
  14206. */
  14207. struct internal_binary_t : public BinaryType
  14208. {
  14209. using BinaryType::BinaryType;
  14210. internal_binary_t() noexcept(noexcept(BinaryType())) : BinaryType() {}
  14211. internal_binary_t(BinaryType const& bint) noexcept(noexcept(BinaryType(bint))) : BinaryType(bint) {}
  14212. internal_binary_t(BinaryType&& bint) noexcept(noexcept(BinaryType(std::move(bint)))) : BinaryType(std::move(bint)) {}
  14213. // TOOD: If minimum C++ version is ever bumped to C++17, this field
  14214. // deserves to be a std::optional
  14215. std::uint8_t subtype = 0;
  14216. bool has_subtype = false;
  14217. };
  14218. /// @}
  14219. private:
  14220. /// helper for exception-safe object creation
  14221. template<typename T, typename... Args>
  14222. JSON_HEDLEY_RETURNS_NON_NULL
  14223. static T* create(Args&& ... args)
  14224. {
  14225. AllocatorType<T> alloc;
  14226. using AllocatorTraits = std::allocator_traits<AllocatorType<T>>;
  14227. auto deleter = [&](T * object)
  14228. {
  14229. AllocatorTraits::deallocate(alloc, object, 1);
  14230. };
  14231. std::unique_ptr<T, decltype(deleter)> object(AllocatorTraits::allocate(alloc, 1), deleter);
  14232. AllocatorTraits::construct(alloc, object.get(), std::forward<Args>(args)...);
  14233. assert(object != nullptr);
  14234. return object.release();
  14235. }
  14236. ////////////////////////
  14237. // JSON value storage //
  14238. ////////////////////////
  14239. /*!
  14240. @brief a JSON value
  14241. The actual storage for a JSON value of the @ref basic_json class. This
  14242. union combines the different storage types for the JSON value types
  14243. defined in @ref value_t.
  14244. JSON type | value_t type | used type
  14245. --------- | --------------- | ------------------------
  14246. object | object | pointer to @ref object_t
  14247. array | array | pointer to @ref array_t
  14248. string | string | pointer to @ref string_t
  14249. boolean | boolean | @ref boolean_t
  14250. number | number_integer | @ref number_integer_t
  14251. number | number_unsigned | @ref number_unsigned_t
  14252. number | number_float | @ref number_float_t
  14253. binary | binary | pointer to @ref internal_binary_t
  14254. null | null | *no value is stored*
  14255. @note Variable-length types (objects, arrays, and strings) are stored as
  14256. pointers. The size of the union should not exceed 64 bits if the default
  14257. value types are used.
  14258. @since version 1.0.0
  14259. */
  14260. union json_value
  14261. {
  14262. /// object (stored with pointer to save storage)
  14263. object_t* object;
  14264. /// array (stored with pointer to save storage)
  14265. array_t* array;
  14266. /// string (stored with pointer to save storage)
  14267. string_t* string;
  14268. /// binary (stored with pointer to save storage)
  14269. internal_binary_t* binary;
  14270. /// boolean
  14271. boolean_t boolean;
  14272. /// number (integer)
  14273. number_integer_t number_integer;
  14274. /// number (unsigned integer)
  14275. number_unsigned_t number_unsigned;
  14276. /// number (floating-point)
  14277. number_float_t number_float;
  14278. /// default constructor (for null values)
  14279. json_value() = default;
  14280. /// constructor for booleans
  14281. json_value(boolean_t v) noexcept : boolean(v) {}
  14282. /// constructor for numbers (integer)
  14283. json_value(number_integer_t v) noexcept : number_integer(v) {}
  14284. /// constructor for numbers (unsigned)
  14285. json_value(number_unsigned_t v) noexcept : number_unsigned(v) {}
  14286. /// constructor for numbers (floating-point)
  14287. json_value(number_float_t v) noexcept : number_float(v) {}
  14288. /// constructor for empty values of a given type
  14289. json_value(value_t t)
  14290. {
  14291. switch (t)
  14292. {
  14293. case value_t::object:
  14294. {
  14295. object = create<object_t>();
  14296. break;
  14297. }
  14298. case value_t::array:
  14299. {
  14300. array = create<array_t>();
  14301. break;
  14302. }
  14303. case value_t::string:
  14304. {
  14305. string = create<string_t>("");
  14306. break;
  14307. }
  14308. case value_t::binary:
  14309. {
  14310. binary = create<internal_binary_t>();
  14311. break;
  14312. }
  14313. case value_t::boolean:
  14314. {
  14315. boolean = boolean_t(false);
  14316. break;
  14317. }
  14318. case value_t::number_integer:
  14319. {
  14320. number_integer = number_integer_t(0);
  14321. break;
  14322. }
  14323. case value_t::number_unsigned:
  14324. {
  14325. number_unsigned = number_unsigned_t(0);
  14326. break;
  14327. }
  14328. case value_t::number_float:
  14329. {
  14330. number_float = number_float_t(0.0);
  14331. break;
  14332. }
  14333. case value_t::null:
  14334. {
  14335. object = nullptr; // silence warning, see #821
  14336. break;
  14337. }
  14338. default:
  14339. {
  14340. object = nullptr; // silence warning, see #821
  14341. if (JSON_HEDLEY_UNLIKELY(t == value_t::null))
  14342. {
  14343. JSON_THROW(other_error::create(500, "961c151d2e87f2686a955a9be24d316f1362bf21 3.7.3")); // LCOV_EXCL_LINE
  14344. }
  14345. break;
  14346. }
  14347. }
  14348. }
  14349. /// constructor for strings
  14350. json_value(const string_t& value)
  14351. {
  14352. string = create<string_t>(value);
  14353. }
  14354. /// constructor for rvalue strings
  14355. json_value(string_t&& value)
  14356. {
  14357. string = create<string_t>(std::move(value));
  14358. }
  14359. /// constructor for objects
  14360. json_value(const object_t& value)
  14361. {
  14362. object = create<object_t>(value);
  14363. }
  14364. /// constructor for rvalue objects
  14365. json_value(object_t&& value)
  14366. {
  14367. object = create<object_t>(std::move(value));
  14368. }
  14369. /// constructor for arrays
  14370. json_value(const array_t& value)
  14371. {
  14372. array = create<array_t>(value);
  14373. }
  14374. /// constructor for rvalue arrays
  14375. json_value(array_t&& value)
  14376. {
  14377. array = create<array_t>(std::move(value));
  14378. }
  14379. /// constructor for binary arrays
  14380. json_value(const binary_t& value)
  14381. {
  14382. binary = create<internal_binary_t>(value);
  14383. }
  14384. /// constructor for rvalue binary arrays
  14385. json_value(binary_t&& value)
  14386. {
  14387. binary = create<internal_binary_t>(std::move(value));
  14388. }
  14389. void destroy(value_t t) noexcept
  14390. {
  14391. // flatten the current json_value to a heap-allocated stack
  14392. std::vector<basic_json> stack;
  14393. // move the top-level items to stack
  14394. if (t == value_t::array)
  14395. {
  14396. stack.reserve(array->size());
  14397. std::move(array->begin(), array->end(), std::back_inserter(stack));
  14398. }
  14399. else if (t == value_t::object)
  14400. {
  14401. stack.reserve(object->size());
  14402. for (auto&& it : *object)
  14403. {
  14404. stack.push_back(std::move(it.second));
  14405. }
  14406. }
  14407. while (not stack.empty())
  14408. {
  14409. // move the last item to local variable to be processed
  14410. basic_json current_item(std::move(stack.back()));
  14411. stack.pop_back();
  14412. // if current_item is array/object, move
  14413. // its children to the stack to be processed later
  14414. if (current_item.is_array())
  14415. {
  14416. std::move(current_item.m_value.array->begin(), current_item.m_value.array->end(),
  14417. std::back_inserter(stack));
  14418. current_item.m_value.array->clear();
  14419. }
  14420. else if (current_item.is_object())
  14421. {
  14422. for (auto&& it : *current_item.m_value.object)
  14423. {
  14424. stack.push_back(std::move(it.second));
  14425. }
  14426. current_item.m_value.object->clear();
  14427. }
  14428. // it's now safe that current_item get destructed
  14429. // since it doesn't have any children
  14430. }
  14431. switch (t)
  14432. {
  14433. case value_t::object:
  14434. {
  14435. AllocatorType<object_t> alloc;
  14436. std::allocator_traits<decltype(alloc)>::destroy(alloc, object);
  14437. std::allocator_traits<decltype(alloc)>::deallocate(alloc, object, 1);
  14438. break;
  14439. }
  14440. case value_t::array:
  14441. {
  14442. AllocatorType<array_t> alloc;
  14443. std::allocator_traits<decltype(alloc)>::destroy(alloc, array);
  14444. std::allocator_traits<decltype(alloc)>::deallocate(alloc, array, 1);
  14445. break;
  14446. }
  14447. case value_t::string:
  14448. {
  14449. AllocatorType<string_t> alloc;
  14450. std::allocator_traits<decltype(alloc)>::destroy(alloc, string);
  14451. std::allocator_traits<decltype(alloc)>::deallocate(alloc, string, 1);
  14452. break;
  14453. }
  14454. case value_t::binary:
  14455. {
  14456. AllocatorType<internal_binary_t> alloc;
  14457. std::allocator_traits<decltype(alloc)>::destroy(alloc, binary);
  14458. std::allocator_traits<decltype(alloc)>::deallocate(alloc, binary, 1);
  14459. break;
  14460. }
  14461. default:
  14462. {
  14463. break;
  14464. }
  14465. }
  14466. }
  14467. };
  14468. /*!
  14469. @brief checks the class invariants
  14470. This function asserts the class invariants. It needs to be called at the
  14471. end of every constructor to make sure that created objects respect the
  14472. invariant. Furthermore, it has to be called each time the type of a JSON
  14473. value is changed, because the invariant expresses a relationship between
  14474. @a m_type and @a m_value.
  14475. */
  14476. void assert_invariant() const noexcept
  14477. {
  14478. assert(m_type != value_t::object or m_value.object != nullptr);
  14479. assert(m_type != value_t::array or m_value.array != nullptr);
  14480. assert(m_type != value_t::string or m_value.string != nullptr);
  14481. }
  14482. public:
  14483. //////////////////////////
  14484. // JSON parser callback //
  14485. //////////////////////////
  14486. /*!
  14487. @brief parser event types
  14488. The parser callback distinguishes the following events:
  14489. - `object_start`: the parser read `{` and started to process a JSON object
  14490. - `key`: the parser read a key of a value in an object
  14491. - `object_end`: the parser read `}` and finished processing a JSON object
  14492. - `array_start`: the parser read `[` and started to process a JSON array
  14493. - `array_end`: the parser read `]` and finished processing a JSON array
  14494. - `value`: the parser finished reading a JSON value
  14495. @image html callback_events.png "Example when certain parse events are triggered"
  14496. @sa @ref parser_callback_t for more information and examples
  14497. */
  14498. using parse_event_t = typename parser::parse_event_t;
  14499. /*!
  14500. @brief per-element parser callback type
  14501. With a parser callback function, the result of parsing a JSON text can be
  14502. influenced. When passed to @ref parse, it is called on certain events
  14503. (passed as @ref parse_event_t via parameter @a event) with a set recursion
  14504. depth @a depth and context JSON value @a parsed. The return value of the
  14505. callback function is a boolean indicating whether the element that emitted
  14506. the callback shall be kept or not.
  14507. We distinguish six scenarios (determined by the event type) in which the
  14508. callback function can be called. The following table describes the values
  14509. of the parameters @a depth, @a event, and @a parsed.
  14510. parameter @a event | description | parameter @a depth | parameter @a parsed
  14511. ------------------ | ----------- | ------------------ | -------------------
  14512. 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
  14513. 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
  14514. 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
  14515. 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
  14516. 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
  14517. parse_event_t::value | the parser finished reading a JSON value | depth of the value | the parsed JSON value
  14518. @image html callback_events.png "Example when certain parse events are triggered"
  14519. Discarding a value (i.e., returning `false`) has different effects
  14520. depending on the context in which function was called:
  14521. - Discarded values in structured types are skipped. That is, the parser
  14522. will behave as if the discarded value was never read.
  14523. - In case a value outside a structured type is skipped, it is replaced
  14524. with `null`. This case happens if the top-level element is skipped.
  14525. @param[in] depth the depth of the recursion during parsing
  14526. @param[in] event an event of type parse_event_t indicating the context in
  14527. the callback function has been called
  14528. @param[in,out] parsed the current intermediate parse result; note that
  14529. writing to this value has no effect for parse_event_t::key events
  14530. @return Whether the JSON value which called the function during parsing
  14531. should be kept (`true`) or not (`false`). In the latter case, it is either
  14532. skipped completely or replaced by an empty discarded object.
  14533. @sa @ref parse for examples
  14534. @since version 1.0.0
  14535. */
  14536. using parser_callback_t = typename parser::parser_callback_t;
  14537. //////////////////
  14538. // constructors //
  14539. //////////////////
  14540. /// @name constructors and destructors
  14541. /// Constructors of class @ref basic_json, copy/move constructor, copy
  14542. /// assignment, static functions creating objects, and the destructor.
  14543. /// @{
  14544. /*!
  14545. @brief create an empty value with a given type
  14546. Create an empty JSON value with a given type. The value will be default
  14547. initialized with an empty value which depends on the type:
  14548. Value type | initial value
  14549. ----------- | -------------
  14550. null | `null`
  14551. boolean | `false`
  14552. string | `""`
  14553. number | `0`
  14554. object | `{}`
  14555. array | `[]`
  14556. binary | empty array
  14557. @param[in] v the type of the value to create
  14558. @complexity Constant.
  14559. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  14560. changes to any JSON value.
  14561. @liveexample{The following code shows the constructor for different @ref
  14562. value_t values,basic_json__value_t}
  14563. @sa @ref clear() -- restores the postcondition of this constructor
  14564. @since version 1.0.0
  14565. */
  14566. basic_json(const value_t v)
  14567. : m_type(v), m_value(v)
  14568. {
  14569. assert_invariant();
  14570. }
  14571. /*!
  14572. @brief create a null object
  14573. Create a `null` JSON value. It either takes a null pointer as parameter
  14574. (explicitly creating `null`) or no parameter (implicitly creating `null`).
  14575. The passed null pointer itself is not read -- it is only used to choose
  14576. the right constructor.
  14577. @complexity Constant.
  14578. @exceptionsafety No-throw guarantee: this constructor never throws
  14579. exceptions.
  14580. @liveexample{The following code shows the constructor with and without a
  14581. null pointer parameter.,basic_json__nullptr_t}
  14582. @since version 1.0.0
  14583. */
  14584. basic_json(std::nullptr_t = nullptr) noexcept
  14585. : basic_json(value_t::null)
  14586. {
  14587. assert_invariant();
  14588. }
  14589. /*!
  14590. @brief create a JSON value
  14591. This is a "catch all" constructor for all compatible JSON types; that is,
  14592. types for which a `to_json()` method exists. The constructor forwards the
  14593. parameter @a val to that method (to `json_serializer<U>::to_json` method
  14594. with `U = uncvref_t<CompatibleType>`, to be exact).
  14595. Template type @a CompatibleType includes, but is not limited to, the
  14596. following types:
  14597. - **arrays**: @ref array_t and all kinds of compatible containers such as
  14598. `std::vector`, `std::deque`, `std::list`, `std::forward_list`,
  14599. `std::array`, `std::valarray`, `std::set`, `std::unordered_set`,
  14600. `std::multiset`, and `std::unordered_multiset` with a `value_type` from
  14601. which a @ref basic_json value can be constructed.
  14602. - **objects**: @ref object_t and all kinds of compatible associative
  14603. containers such as `std::map`, `std::unordered_map`, `std::multimap`,
  14604. and `std::unordered_multimap` with a `key_type` compatible to
  14605. @ref string_t and a `value_type` from which a @ref basic_json value can
  14606. be constructed.
  14607. - **strings**: @ref string_t, string literals, and all compatible string
  14608. containers can be used.
  14609. - **numbers**: @ref number_integer_t, @ref number_unsigned_t,
  14610. @ref number_float_t, and all convertible number types such as `int`,
  14611. `size_t`, `int64_t`, `float` or `double` can be used.
  14612. - **boolean**: @ref boolean_t / `bool` can be used.
  14613. - **binary**: @ref binary_t / `std::vector<uint8_t>` may be used,
  14614. unfortunately because string literals cannot be distinguished from binary
  14615. character arrays by the C++ type system, all types compatible with `const
  14616. char*` will be directed to the string constructor instead. This is both
  14617. for backwards compatibility, and due to the fact that a binary type is not
  14618. a standard JSON type.
  14619. See the examples below.
  14620. @tparam CompatibleType a type such that:
  14621. - @a CompatibleType is not derived from `std::istream`,
  14622. - @a CompatibleType is not @ref basic_json (to avoid hijacking copy/move
  14623. constructors),
  14624. - @a CompatibleType is not a different @ref basic_json type (i.e. with different template arguments)
  14625. - @a CompatibleType is not a @ref basic_json nested type (e.g.,
  14626. @ref json_pointer, @ref iterator, etc ...)
  14627. - @ref @ref json_serializer<U> has a
  14628. `to_json(basic_json_t&, CompatibleType&&)` method
  14629. @tparam U = `uncvref_t<CompatibleType>`
  14630. @param[in] val the value to be forwarded to the respective constructor
  14631. @complexity Usually linear in the size of the passed @a val, also
  14632. depending on the implementation of the called `to_json()`
  14633. method.
  14634. @exceptionsafety Depends on the called constructor. For types directly
  14635. supported by the library (i.e., all types for which no `to_json()` function
  14636. was provided), strong guarantee holds: if an exception is thrown, there are
  14637. no changes to any JSON value.
  14638. @liveexample{The following code shows the constructor with several
  14639. compatible types.,basic_json__CompatibleType}
  14640. @since version 2.1.0
  14641. */
  14642. template <typename CompatibleType,
  14643. typename U = detail::uncvref_t<CompatibleType>,
  14644. detail::enable_if_t<
  14645. not detail::is_basic_json<U>::value and detail::is_compatible_type<basic_json_t, U>::value, int> = 0>
  14646. basic_json(CompatibleType && val) noexcept(noexcept(
  14647. JSONSerializer<U>::to_json(std::declval<basic_json_t&>(),
  14648. std::forward<CompatibleType>(val))))
  14649. {
  14650. JSONSerializer<U>::to_json(*this, std::forward<CompatibleType>(val));
  14651. assert_invariant();
  14652. }
  14653. /*!
  14654. @brief create a JSON value from an existing one
  14655. This is a constructor for existing @ref basic_json types.
  14656. It does not hijack copy/move constructors, since the parameter has different
  14657. template arguments than the current ones.
  14658. The constructor tries to convert the internal @ref m_value of the parameter.
  14659. @tparam BasicJsonType a type such that:
  14660. - @a BasicJsonType is a @ref basic_json type.
  14661. - @a BasicJsonType has different template arguments than @ref basic_json_t.
  14662. @param[in] val the @ref basic_json value to be converted.
  14663. @complexity Usually linear in the size of the passed @a val, also
  14664. depending on the implementation of the called `to_json()`
  14665. method.
  14666. @exceptionsafety Depends on the called constructor. For types directly
  14667. supported by the library (i.e., all types for which no `to_json()` function
  14668. was provided), strong guarantee holds: if an exception is thrown, there are
  14669. no changes to any JSON value.
  14670. @since version 3.2.0
  14671. */
  14672. template <typename BasicJsonType,
  14673. detail::enable_if_t<
  14674. detail::is_basic_json<BasicJsonType>::value and not std::is_same<basic_json, BasicJsonType>::value, int> = 0>
  14675. basic_json(const BasicJsonType& val)
  14676. {
  14677. using other_boolean_t = typename BasicJsonType::boolean_t;
  14678. using other_number_float_t = typename BasicJsonType::number_float_t;
  14679. using other_number_integer_t = typename BasicJsonType::number_integer_t;
  14680. using other_number_unsigned_t = typename BasicJsonType::number_unsigned_t;
  14681. using other_string_t = typename BasicJsonType::string_t;
  14682. using other_object_t = typename BasicJsonType::object_t;
  14683. using other_array_t = typename BasicJsonType::array_t;
  14684. using other_binary_t = typename BasicJsonType::internal_binary_t;
  14685. switch (val.type())
  14686. {
  14687. case value_t::boolean:
  14688. JSONSerializer<other_boolean_t>::to_json(*this, val.template get<other_boolean_t>());
  14689. break;
  14690. case value_t::number_float:
  14691. JSONSerializer<other_number_float_t>::to_json(*this, val.template get<other_number_float_t>());
  14692. break;
  14693. case value_t::number_integer:
  14694. JSONSerializer<other_number_integer_t>::to_json(*this, val.template get<other_number_integer_t>());
  14695. break;
  14696. case value_t::number_unsigned:
  14697. JSONSerializer<other_number_unsigned_t>::to_json(*this, val.template get<other_number_unsigned_t>());
  14698. break;
  14699. case value_t::string:
  14700. JSONSerializer<other_string_t>::to_json(*this, val.template get_ref<const other_string_t&>());
  14701. break;
  14702. case value_t::object:
  14703. JSONSerializer<other_object_t>::to_json(*this, val.template get_ref<const other_object_t&>());
  14704. break;
  14705. case value_t::array:
  14706. JSONSerializer<other_array_t>::to_json(*this, val.template get_ref<const other_array_t&>());
  14707. break;
  14708. case value_t::binary:
  14709. JSONSerializer<other_binary_t>::to_json(*this, val.template get_ref<const other_binary_t&>());
  14710. break;
  14711. case value_t::null:
  14712. *this = nullptr;
  14713. break;
  14714. case value_t::discarded:
  14715. m_type = value_t::discarded;
  14716. break;
  14717. default: // LCOV_EXCL_LINE
  14718. assert(false); // LCOV_EXCL_LINE
  14719. }
  14720. assert_invariant();
  14721. }
  14722. /*!
  14723. @brief create a container (array or object) from an initializer list
  14724. Creates a JSON value of type array or object from the passed initializer
  14725. list @a init. In case @a type_deduction is `true` (default), the type of
  14726. the JSON value to be created is deducted from the initializer list @a init
  14727. according to the following rules:
  14728. 1. If the list is empty, an empty JSON object value `{}` is created.
  14729. 2. If the list consists of pairs whose first element is a string, a JSON
  14730. object value is created where the first elements of the pairs are
  14731. treated as keys and the second elements are as values.
  14732. 3. In all other cases, an array is created.
  14733. The rules aim to create the best fit between a C++ initializer list and
  14734. JSON values. The rationale is as follows:
  14735. 1. The empty initializer list is written as `{}` which is exactly an empty
  14736. JSON object.
  14737. 2. C++ has no way of describing mapped types other than to list a list of
  14738. pairs. As JSON requires that keys must be of type string, rule 2 is the
  14739. weakest constraint one can pose on initializer lists to interpret them
  14740. as an object.
  14741. 3. In all other cases, the initializer list could not be interpreted as
  14742. JSON object type, so interpreting it as JSON array type is safe.
  14743. With the rules described above, the following JSON values cannot be
  14744. expressed by an initializer list:
  14745. - the empty array (`[]`): use @ref array(initializer_list_t)
  14746. with an empty initializer list in this case
  14747. - arrays whose elements satisfy rule 2: use @ref
  14748. array(initializer_list_t) with the same initializer list
  14749. in this case
  14750. @note When used without parentheses around an empty initializer list, @ref
  14751. basic_json() is called instead of this function, yielding the JSON null
  14752. value.
  14753. @param[in] init initializer list with JSON values
  14754. @param[in] type_deduction internal parameter; when set to `true`, the type
  14755. of the JSON value is deducted from the initializer list @a init; when set
  14756. to `false`, the type provided via @a manual_type is forced. This mode is
  14757. used by the functions @ref array(initializer_list_t) and
  14758. @ref object(initializer_list_t).
  14759. @param[in] manual_type internal parameter; when @a type_deduction is set
  14760. to `false`, the created JSON value will use the provided type (only @ref
  14761. value_t::array and @ref value_t::object are valid); when @a type_deduction
  14762. is set to `true`, this parameter has no effect
  14763. @throw type_error.301 if @a type_deduction is `false`, @a manual_type is
  14764. `value_t::object`, but @a init contains an element which is not a pair
  14765. whose first element is a string. In this case, the constructor could not
  14766. create an object. If @a type_deduction would have be `true`, an array
  14767. would have been created. See @ref object(initializer_list_t)
  14768. for an example.
  14769. @complexity Linear in the size of the initializer list @a init.
  14770. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  14771. changes to any JSON value.
  14772. @liveexample{The example below shows how JSON values are created from
  14773. initializer lists.,basic_json__list_init_t}
  14774. @sa @ref array(initializer_list_t) -- create a JSON array
  14775. value from an initializer list
  14776. @sa @ref object(initializer_list_t) -- create a JSON object
  14777. value from an initializer list
  14778. @since version 1.0.0
  14779. */
  14780. basic_json(initializer_list_t init,
  14781. bool type_deduction = true,
  14782. value_t manual_type = value_t::array)
  14783. {
  14784. // check if each element is an array with two elements whose first
  14785. // element is a string
  14786. bool is_an_object = std::all_of(init.begin(), init.end(),
  14787. [](const detail::json_ref<basic_json>& element_ref)
  14788. {
  14789. return element_ref->is_array() and element_ref->size() == 2 and (*element_ref)[0].is_string();
  14790. });
  14791. // adjust type if type deduction is not wanted
  14792. if (not type_deduction)
  14793. {
  14794. // if array is wanted, do not create an object though possible
  14795. if (manual_type == value_t::array)
  14796. {
  14797. is_an_object = false;
  14798. }
  14799. // if object is wanted but impossible, throw an exception
  14800. if (JSON_HEDLEY_UNLIKELY(manual_type == value_t::object and not is_an_object))
  14801. {
  14802. JSON_THROW(type_error::create(301, "cannot create object from initializer list"));
  14803. }
  14804. }
  14805. if (is_an_object)
  14806. {
  14807. // the initializer list is a list of pairs -> create object
  14808. m_type = value_t::object;
  14809. m_value = value_t::object;
  14810. std::for_each(init.begin(), init.end(), [this](const detail::json_ref<basic_json>& element_ref)
  14811. {
  14812. auto element = element_ref.moved_or_copied();
  14813. m_value.object->emplace(
  14814. std::move(*((*element.m_value.array)[0].m_value.string)),
  14815. std::move((*element.m_value.array)[1]));
  14816. });
  14817. }
  14818. else
  14819. {
  14820. // the initializer list describes an array -> create array
  14821. m_type = value_t::array;
  14822. m_value.array = create<array_t>(init.begin(), init.end());
  14823. }
  14824. assert_invariant();
  14825. }
  14826. /*!
  14827. @brief explicitly create a binary array from an already constructed copy of
  14828. its base type
  14829. Creates a JSON binary array value from a given `binary_t`. Binary values are
  14830. part of various binary formats, such as CBOR, MsgPack, and BSON. And this
  14831. constructor is used to create a value for serialization to those formats.
  14832. @note Note, this function exists because of the difficulty in correctly
  14833. specifying the correct template overload in the standard value ctor, as both
  14834. JSON arrays and JSON binary arrays are backed with some form of a
  14835. `std::vector`. Because JSON binary arrays are a non-standard extension it
  14836. was decided that it would be best to prevent automatic initialization of a
  14837. binary array type, for backwards compatibility and so it does not happen on
  14838. accident.
  14839. @param[in] init `binary_t` with JSON values to create a binary array from
  14840. @return JSON binary array value
  14841. @complexity Linear in the size of @a init.
  14842. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  14843. changes to any JSON value.
  14844. @since version 3.8.0
  14845. */
  14846. JSON_HEDLEY_WARN_UNUSED_RESULT
  14847. static basic_json binary_array(binary_t const& init)
  14848. {
  14849. auto res = basic_json();
  14850. res.m_type = value_t::binary;
  14851. res.m_value = init;
  14852. return res;
  14853. }
  14854. /*!
  14855. @brief explicitly create a binary array from an already constructed rvalue
  14856. copy of its base type
  14857. Creates a JSON binary array value from a given `binary_t`. Binary values are
  14858. part of various binary formats, such as CBOR, MsgPack, and BSON. And this
  14859. constructor is used to create a value for serialization to those formats.
  14860. @note Note, this function exists because of the difficulty in correctly
  14861. specifying the correct template overload in the standard value ctor, as both
  14862. JSON arrays and JSON binary arrays are backed with some form of a
  14863. `std::vector`. Because JSON binary arrays are a non-standard extension it
  14864. was decided that it would be best to prevent automatic initialization of a
  14865. binary array type, for backwards compatibility and so it doesn't happen on
  14866. accident.
  14867. @param[in] init `binary_t` with JSON values to create a binary array from
  14868. @return JSON binary array value
  14869. @complexity Linear in the size of @a init.
  14870. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  14871. changes to any JSON value.
  14872. @since version 3.8.0
  14873. */
  14874. JSON_HEDLEY_WARN_UNUSED_RESULT
  14875. static basic_json binary_array(binary_t&& init)
  14876. {
  14877. auto res = basic_json();
  14878. res.m_type = value_t::binary;
  14879. res.m_value = std::move(init);
  14880. return res;
  14881. }
  14882. /*!
  14883. @brief explicitly create an array from an initializer list
  14884. Creates a JSON array value from a given initializer list. That is, given a
  14885. list of values `a, b, c`, creates the JSON value `[a, b, c]`. If the
  14886. initializer list is empty, the empty array `[]` is created.
  14887. @note This function is only needed to express two edge cases that cannot
  14888. be realized with the initializer list constructor (@ref
  14889. basic_json(initializer_list_t, bool, value_t)). These cases
  14890. are:
  14891. 1. creating an array whose elements are all pairs whose first element is a
  14892. string -- in this case, the initializer list constructor would create an
  14893. object, taking the first elements as keys
  14894. 2. creating an empty array -- passing the empty initializer list to the
  14895. initializer list constructor yields an empty object
  14896. @param[in] init initializer list with JSON values to create an array from
  14897. (optional)
  14898. @return JSON array value
  14899. @complexity Linear in the size of @a init.
  14900. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  14901. changes to any JSON value.
  14902. @liveexample{The following code shows an example for the `array`
  14903. function.,array}
  14904. @sa @ref basic_json(initializer_list_t, bool, value_t) --
  14905. create a JSON value from an initializer list
  14906. @sa @ref object(initializer_list_t) -- create a JSON object
  14907. value from an initializer list
  14908. @since version 1.0.0
  14909. */
  14910. JSON_HEDLEY_WARN_UNUSED_RESULT
  14911. static basic_json array(initializer_list_t init = {})
  14912. {
  14913. return basic_json(init, false, value_t::array);
  14914. }
  14915. /*!
  14916. @brief explicitly create an object from an initializer list
  14917. Creates a JSON object value from a given initializer list. The initializer
  14918. lists elements must be pairs, and their first elements must be strings. If
  14919. the initializer list is empty, the empty object `{}` is created.
  14920. @note This function is only added for symmetry reasons. In contrast to the
  14921. related function @ref array(initializer_list_t), there are
  14922. no cases which can only be expressed by this function. That is, any
  14923. initializer list @a init can also be passed to the initializer list
  14924. constructor @ref basic_json(initializer_list_t, bool, value_t).
  14925. @param[in] init initializer list to create an object from (optional)
  14926. @return JSON object value
  14927. @throw type_error.301 if @a init is not a list of pairs whose first
  14928. elements are strings. In this case, no object can be created. When such a
  14929. value is passed to @ref basic_json(initializer_list_t, bool, value_t),
  14930. an array would have been created from the passed initializer list @a init.
  14931. See example below.
  14932. @complexity Linear in the size of @a init.
  14933. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  14934. changes to any JSON value.
  14935. @liveexample{The following code shows an example for the `object`
  14936. function.,object}
  14937. @sa @ref basic_json(initializer_list_t, bool, value_t) --
  14938. create a JSON value from an initializer list
  14939. @sa @ref array(initializer_list_t) -- create a JSON array
  14940. value from an initializer list
  14941. @since version 1.0.0
  14942. */
  14943. JSON_HEDLEY_WARN_UNUSED_RESULT
  14944. static basic_json object(initializer_list_t init = {})
  14945. {
  14946. return basic_json(init, false, value_t::object);
  14947. }
  14948. /*!
  14949. @brief construct an array with count copies of given value
  14950. Constructs a JSON array value by creating @a cnt copies of a passed value.
  14951. In case @a cnt is `0`, an empty array is created.
  14952. @param[in] cnt the number of JSON copies of @a val to create
  14953. @param[in] val the JSON value to copy
  14954. @post `std::distance(begin(),end()) == cnt` holds.
  14955. @complexity Linear in @a cnt.
  14956. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  14957. changes to any JSON value.
  14958. @liveexample{The following code shows examples for the @ref
  14959. basic_json(size_type\, const basic_json&)
  14960. constructor.,basic_json__size_type_basic_json}
  14961. @since version 1.0.0
  14962. */
  14963. basic_json(size_type cnt, const basic_json& val)
  14964. : m_type(value_t::array)
  14965. {
  14966. m_value.array = create<array_t>(cnt, val);
  14967. assert_invariant();
  14968. }
  14969. /*!
  14970. @brief construct a JSON container given an iterator range
  14971. Constructs the JSON value with the contents of the range `[first, last)`.
  14972. The semantics depends on the different types a JSON value can have:
  14973. - In case of a null type, invalid_iterator.206 is thrown.
  14974. - In case of other primitive types (number, boolean, or string), @a first
  14975. must be `begin()` and @a last must be `end()`. In this case, the value is
  14976. copied. Otherwise, invalid_iterator.204 is thrown.
  14977. - In case of structured types (array, object), the constructor behaves as
  14978. similar versions for `std::vector` or `std::map`; that is, a JSON array
  14979. or object is constructed from the values in the range.
  14980. @tparam InputIT an input iterator type (@ref iterator or @ref
  14981. const_iterator)
  14982. @param[in] first begin of the range to copy from (included)
  14983. @param[in] last end of the range to copy from (excluded)
  14984. @pre Iterators @a first and @a last must be initialized. **This
  14985. precondition is enforced with an assertion (see warning).** If
  14986. assertions are switched off, a violation of this precondition yields
  14987. undefined behavior.
  14988. @pre Range `[first, last)` is valid. Usually, this precondition cannot be
  14989. checked efficiently. Only certain edge cases are detected; see the
  14990. description of the exceptions below. A violation of this precondition
  14991. yields undefined behavior.
  14992. @warning A precondition is enforced with a runtime assertion that will
  14993. result in calling `std::abort` if this precondition is not met.
  14994. Assertions can be disabled by defining `NDEBUG` at compile time.
  14995. See https://en.cppreference.com/w/cpp/error/assert for more
  14996. information.
  14997. @throw invalid_iterator.201 if iterators @a first and @a last are not
  14998. compatible (i.e., do not belong to the same JSON value). In this case,
  14999. the range `[first, last)` is undefined.
  15000. @throw invalid_iterator.204 if iterators @a first and @a last belong to a
  15001. primitive type (number, boolean, or string), but @a first does not point
  15002. to the first element any more. In this case, the range `[first, last)` is
  15003. undefined. See example code below.
  15004. @throw invalid_iterator.206 if iterators @a first and @a last belong to a
  15005. null value. In this case, the range `[first, last)` is undefined.
  15006. @complexity Linear in distance between @a first and @a last.
  15007. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  15008. changes to any JSON value.
  15009. @liveexample{The example below shows several ways to create JSON values by
  15010. specifying a subrange with iterators.,basic_json__InputIt_InputIt}
  15011. @since version 1.0.0
  15012. */
  15013. template<class InputIT, typename std::enable_if<
  15014. std::is_same<InputIT, typename basic_json_t::iterator>::value or
  15015. std::is_same<InputIT, typename basic_json_t::const_iterator>::value, int>::type = 0>
  15016. basic_json(InputIT first, InputIT last)
  15017. {
  15018. assert(first.m_object != nullptr);
  15019. assert(last.m_object != nullptr);
  15020. // make sure iterator fits the current value
  15021. if (JSON_HEDLEY_UNLIKELY(first.m_object != last.m_object))
  15022. {
  15023. JSON_THROW(invalid_iterator::create(201, "iterators are not compatible"));
  15024. }
  15025. // copy type from first iterator
  15026. m_type = first.m_object->m_type;
  15027. // check if iterator range is complete for primitive values
  15028. switch (m_type)
  15029. {
  15030. case value_t::boolean:
  15031. case value_t::number_float:
  15032. case value_t::number_integer:
  15033. case value_t::number_unsigned:
  15034. case value_t::string:
  15035. {
  15036. if (JSON_HEDLEY_UNLIKELY(not first.m_it.primitive_iterator.is_begin()
  15037. or not last.m_it.primitive_iterator.is_end()))
  15038. {
  15039. JSON_THROW(invalid_iterator::create(204, "iterators out of range"));
  15040. }
  15041. break;
  15042. }
  15043. default:
  15044. break;
  15045. }
  15046. switch (m_type)
  15047. {
  15048. case value_t::number_integer:
  15049. {
  15050. m_value.number_integer = first.m_object->m_value.number_integer;
  15051. break;
  15052. }
  15053. case value_t::number_unsigned:
  15054. {
  15055. m_value.number_unsigned = first.m_object->m_value.number_unsigned;
  15056. break;
  15057. }
  15058. case value_t::number_float:
  15059. {
  15060. m_value.number_float = first.m_object->m_value.number_float;
  15061. break;
  15062. }
  15063. case value_t::boolean:
  15064. {
  15065. m_value.boolean = first.m_object->m_value.boolean;
  15066. break;
  15067. }
  15068. case value_t::string:
  15069. {
  15070. m_value = *first.m_object->m_value.string;
  15071. break;
  15072. }
  15073. case value_t::object:
  15074. {
  15075. m_value.object = create<object_t>(first.m_it.object_iterator,
  15076. last.m_it.object_iterator);
  15077. break;
  15078. }
  15079. case value_t::array:
  15080. {
  15081. m_value.array = create<array_t>(first.m_it.array_iterator,
  15082. last.m_it.array_iterator);
  15083. break;
  15084. }
  15085. case value_t::binary:
  15086. {
  15087. m_value.binary = create<internal_binary_t>(first.m_it.binary_iterator,
  15088. last.m_it.binary_iterator);
  15089. break;
  15090. }
  15091. default:
  15092. JSON_THROW(invalid_iterator::create(206, "cannot construct with iterators from " +
  15093. std::string(first.m_object->type_name())));
  15094. }
  15095. assert_invariant();
  15096. }
  15097. ///////////////////////////////////////
  15098. // other constructors and destructor //
  15099. ///////////////////////////////////////
  15100. template <typename JsonRef,
  15101. detail::enable_if_t<detail::conjunction<detail::is_json_ref<JsonRef>,
  15102. std::is_same<typename JsonRef::value_type, basic_json>>::value, int> = 0 >
  15103. basic_json(const JsonRef& ref) : basic_json(ref.moved_or_copied()) {}
  15104. /*!
  15105. @brief copy constructor
  15106. Creates a copy of a given JSON value.
  15107. @param[in] other the JSON value to copy
  15108. @post `*this == other`
  15109. @complexity Linear in the size of @a other.
  15110. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  15111. changes to any JSON value.
  15112. @requirement This function helps `basic_json` satisfying the
  15113. [Container](https://en.cppreference.com/w/cpp/named_req/Container)
  15114. requirements:
  15115. - The complexity is linear.
  15116. - As postcondition, it holds: `other == basic_json(other)`.
  15117. @liveexample{The following code shows an example for the copy
  15118. constructor.,basic_json__basic_json}
  15119. @since version 1.0.0
  15120. */
  15121. basic_json(const basic_json& other)
  15122. : m_type(other.m_type)
  15123. {
  15124. // check of passed value is valid
  15125. other.assert_invariant();
  15126. switch (m_type)
  15127. {
  15128. case value_t::object:
  15129. {
  15130. m_value = *other.m_value.object;
  15131. break;
  15132. }
  15133. case value_t::array:
  15134. {
  15135. m_value = *other.m_value.array;
  15136. break;
  15137. }
  15138. case value_t::string:
  15139. {
  15140. m_value = *other.m_value.string;
  15141. break;
  15142. }
  15143. case value_t::boolean:
  15144. {
  15145. m_value = other.m_value.boolean;
  15146. break;
  15147. }
  15148. case value_t::number_integer:
  15149. {
  15150. m_value = other.m_value.number_integer;
  15151. break;
  15152. }
  15153. case value_t::number_unsigned:
  15154. {
  15155. m_value = other.m_value.number_unsigned;
  15156. break;
  15157. }
  15158. case value_t::number_float:
  15159. {
  15160. m_value = other.m_value.number_float;
  15161. break;
  15162. }
  15163. case value_t::binary:
  15164. {
  15165. m_value = *other.m_value.binary;
  15166. break;
  15167. }
  15168. default:
  15169. break;
  15170. }
  15171. assert_invariant();
  15172. }
  15173. /*!
  15174. @brief move constructor
  15175. Move constructor. Constructs a JSON value with the contents of the given
  15176. value @a other using move semantics. It "steals" the resources from @a
  15177. other and leaves it as JSON null value.
  15178. @param[in,out] other value to move to this object
  15179. @post `*this` has the same value as @a other before the call.
  15180. @post @a other is a JSON null value.
  15181. @complexity Constant.
  15182. @exceptionsafety No-throw guarantee: this constructor never throws
  15183. exceptions.
  15184. @requirement This function helps `basic_json` satisfying the
  15185. [MoveConstructible](https://en.cppreference.com/w/cpp/named_req/MoveConstructible)
  15186. requirements.
  15187. @liveexample{The code below shows the move constructor explicitly called
  15188. via std::move.,basic_json__moveconstructor}
  15189. @since version 1.0.0
  15190. */
  15191. basic_json(basic_json&& other) noexcept
  15192. : m_type(std::move(other.m_type)),
  15193. m_value(std::move(other.m_value))
  15194. {
  15195. // check that passed value is valid
  15196. other.assert_invariant();
  15197. // invalidate payload
  15198. other.m_type = value_t::null;
  15199. other.m_value = {};
  15200. assert_invariant();
  15201. }
  15202. /*!
  15203. @brief copy assignment
  15204. Copy assignment operator. Copies a JSON value via the "copy and swap"
  15205. strategy: It is expressed in terms of the copy constructor, destructor,
  15206. and the `swap()` member function.
  15207. @param[in] other value to copy from
  15208. @complexity Linear.
  15209. @requirement This function helps `basic_json` satisfying the
  15210. [Container](https://en.cppreference.com/w/cpp/named_req/Container)
  15211. requirements:
  15212. - The complexity is linear.
  15213. @liveexample{The code below shows and example for the copy assignment. It
  15214. creates a copy of value `a` which is then swapped with `b`. Finally\, the
  15215. copy of `a` (which is the null value after the swap) is
  15216. destroyed.,basic_json__copyassignment}
  15217. @since version 1.0.0
  15218. */
  15219. basic_json& operator=(basic_json other) noexcept (
  15220. std::is_nothrow_move_constructible<value_t>::value and
  15221. std::is_nothrow_move_assignable<value_t>::value and
  15222. std::is_nothrow_move_constructible<json_value>::value and
  15223. std::is_nothrow_move_assignable<json_value>::value
  15224. )
  15225. {
  15226. // check that passed value is valid
  15227. other.assert_invariant();
  15228. using std::swap;
  15229. swap(m_type, other.m_type);
  15230. swap(m_value, other.m_value);
  15231. assert_invariant();
  15232. return *this;
  15233. }
  15234. /*!
  15235. @brief destructor
  15236. Destroys the JSON value and frees all allocated memory.
  15237. @complexity Linear.
  15238. @requirement This function helps `basic_json` satisfying the
  15239. [Container](https://en.cppreference.com/w/cpp/named_req/Container)
  15240. requirements:
  15241. - The complexity is linear.
  15242. - All stored elements are destroyed and all memory is freed.
  15243. @since version 1.0.0
  15244. */
  15245. ~basic_json() noexcept
  15246. {
  15247. assert_invariant();
  15248. m_value.destroy(m_type);
  15249. }
  15250. /// @}
  15251. public:
  15252. ///////////////////////
  15253. // object inspection //
  15254. ///////////////////////
  15255. /// @name object inspection
  15256. /// Functions to inspect the type of a JSON value.
  15257. /// @{
  15258. /*!
  15259. @brief serialization
  15260. Serialization function for JSON values. The function tries to mimic
  15261. Python's `json.dumps()` function, and currently supports its @a indent
  15262. and @a ensure_ascii parameters.
  15263. @param[in] indent If indent is nonnegative, then array elements and object
  15264. members will be pretty-printed with that indent level. An indent level of
  15265. `0` will only insert newlines. `-1` (the default) selects the most compact
  15266. representation.
  15267. @param[in] indent_char The character to use for indentation if @a indent is
  15268. greater than `0`. The default is ` ` (space).
  15269. @param[in] ensure_ascii If @a ensure_ascii is true, all non-ASCII characters
  15270. in the output are escaped with `\uXXXX` sequences, and the result consists
  15271. of ASCII characters only.
  15272. @param[in] error_handler how to react on decoding errors; there are three
  15273. possible values: `strict` (throws and exception in case a decoding error
  15274. occurs; default), `replace` (replace invalid UTF-8 sequences with U+FFFD),
  15275. and `ignore` (ignore invalid UTF-8 sequences during serialization).
  15276. @param[in] serialize_binary Whether or not to allow serialization of binary
  15277. types to JSON. Because binary types are non-standard, this will produce
  15278. non-conformant JSON, and is disabled by default. This flag is primarily
  15279. useful for debugging. Will output the binary value as a list of 8-bit
  15280. numbers prefixed by "b" (e.g. "bindata" = b[3, 0, 42, 255]).
  15281. @return string containing the serialization of the JSON value
  15282. @throw type_error.316 if a string stored inside the JSON value is not
  15283. UTF-8 encoded
  15284. @complexity Linear.
  15285. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  15286. changes in the JSON value.
  15287. @liveexample{The following example shows the effect of different @a indent\,
  15288. @a indent_char\, and @a ensure_ascii parameters to the result of the
  15289. serialization.,dump}
  15290. @see https://docs.python.org/2/library/json.html#json.dump
  15291. @since version 1.0.0; indentation character @a indent_char, option
  15292. @a ensure_ascii and exceptions added in version 3.0.0; error
  15293. handlers added in version 3.4.0.
  15294. */
  15295. string_t dump(const int indent = -1,
  15296. const char indent_char = ' ',
  15297. const bool ensure_ascii = false,
  15298. const error_handler_t error_handler = error_handler_t::strict,
  15299. const bool serialize_binary = false) const
  15300. {
  15301. string_t result;
  15302. serializer s(detail::output_adapter<char, string_t>(result), indent_char, error_handler);
  15303. if (indent >= 0)
  15304. {
  15305. s.dump(*this, true, ensure_ascii, static_cast<unsigned int>(indent), 0, serialize_binary);
  15306. }
  15307. else
  15308. {
  15309. s.dump(*this, false, ensure_ascii, 0, 0, serialize_binary);
  15310. }
  15311. return result;
  15312. }
  15313. /*!
  15314. @brief return the type of the JSON value (explicit)
  15315. Return the type of the JSON value as a value from the @ref value_t
  15316. enumeration.
  15317. @return the type of the JSON value
  15318. Value type | return value
  15319. ------------------------- | -------------------------
  15320. null | value_t::null
  15321. boolean | value_t::boolean
  15322. string | value_t::string
  15323. number (integer) | value_t::number_integer
  15324. number (unsigned integer) | value_t::number_unsigned
  15325. number (floating-point) | value_t::number_float
  15326. object | value_t::object
  15327. array | value_t::array
  15328. binary | value_t::binary
  15329. discarded | value_t::discarded
  15330. @complexity Constant.
  15331. @exceptionsafety No-throw guarantee: this member function never throws
  15332. exceptions.
  15333. @liveexample{The following code exemplifies `type()` for all JSON
  15334. types.,type}
  15335. @sa @ref operator value_t() -- return the type of the JSON value (implicit)
  15336. @sa @ref type_name() -- return the type as string
  15337. @since version 1.0.0
  15338. */
  15339. constexpr value_t type() const noexcept
  15340. {
  15341. return m_type;
  15342. }
  15343. /*!
  15344. @brief return whether type is primitive
  15345. This function returns true if and only if the JSON type is primitive
  15346. (string, number, boolean, or null).
  15347. @return `true` if type is primitive (string, number, boolean, or null),
  15348. `false` otherwise.
  15349. @complexity Constant.
  15350. @exceptionsafety No-throw guarantee: this member function never throws
  15351. exceptions.
  15352. @liveexample{The following code exemplifies `is_primitive()` for all JSON
  15353. types.,is_primitive}
  15354. @sa @ref is_structured() -- returns whether JSON value is structured
  15355. @sa @ref is_null() -- returns whether JSON value is `null`
  15356. @sa @ref is_string() -- returns whether JSON value is a string
  15357. @sa @ref is_boolean() -- returns whether JSON value is a boolean
  15358. @sa @ref is_number() -- returns whether JSON value is a number
  15359. @sa @ref is_binary() -- returns whether JSON value is a binary array
  15360. @since version 1.0.0
  15361. */
  15362. constexpr bool is_primitive() const noexcept
  15363. {
  15364. return is_null() or is_string() or is_boolean() or is_number() or is_binary();
  15365. }
  15366. /*!
  15367. @brief return whether type is structured
  15368. This function returns true if and only if the JSON type is structured
  15369. (array or object).
  15370. @return `true` if type is structured (array or object), `false` otherwise.
  15371. @complexity Constant.
  15372. @exceptionsafety No-throw guarantee: this member function never throws
  15373. exceptions.
  15374. @liveexample{The following code exemplifies `is_structured()` for all JSON
  15375. types.,is_structured}
  15376. @sa @ref is_primitive() -- returns whether value is primitive
  15377. @sa @ref is_array() -- returns whether value is an array
  15378. @sa @ref is_object() -- returns whether value is an object
  15379. @since version 1.0.0
  15380. */
  15381. constexpr bool is_structured() const noexcept
  15382. {
  15383. return is_array() or is_object();
  15384. }
  15385. /*!
  15386. @brief return whether value is null
  15387. This function returns true if and only if the JSON value is null.
  15388. @return `true` if type is null, `false` otherwise.
  15389. @complexity Constant.
  15390. @exceptionsafety No-throw guarantee: this member function never throws
  15391. exceptions.
  15392. @liveexample{The following code exemplifies `is_null()` for all JSON
  15393. types.,is_null}
  15394. @since version 1.0.0
  15395. */
  15396. constexpr bool is_null() const noexcept
  15397. {
  15398. return m_type == value_t::null;
  15399. }
  15400. /*!
  15401. @brief return whether value is a boolean
  15402. This function returns true if and only if the JSON value is a boolean.
  15403. @return `true` if type is boolean, `false` otherwise.
  15404. @complexity Constant.
  15405. @exceptionsafety No-throw guarantee: this member function never throws
  15406. exceptions.
  15407. @liveexample{The following code exemplifies `is_boolean()` for all JSON
  15408. types.,is_boolean}
  15409. @since version 1.0.0
  15410. */
  15411. constexpr bool is_boolean() const noexcept
  15412. {
  15413. return m_type == value_t::boolean;
  15414. }
  15415. /*!
  15416. @brief return whether value is a number
  15417. This function returns true if and only if the JSON value is a number. This
  15418. includes both integer (signed and unsigned) and floating-point values.
  15419. @return `true` if type is number (regardless whether integer, unsigned
  15420. integer or floating-type), `false` otherwise.
  15421. @complexity Constant.
  15422. @exceptionsafety No-throw guarantee: this member function never throws
  15423. exceptions.
  15424. @liveexample{The following code exemplifies `is_number()` for all JSON
  15425. types.,is_number}
  15426. @sa @ref is_number_integer() -- check if value is an integer or unsigned
  15427. integer number
  15428. @sa @ref is_number_unsigned() -- check if value is an unsigned integer
  15429. number
  15430. @sa @ref is_number_float() -- check if value is a floating-point number
  15431. @since version 1.0.0
  15432. */
  15433. constexpr bool is_number() const noexcept
  15434. {
  15435. return is_number_integer() or is_number_float();
  15436. }
  15437. /*!
  15438. @brief return whether value is an integer number
  15439. This function returns true if and only if the JSON value is a signed or
  15440. unsigned integer number. This excludes floating-point values.
  15441. @return `true` if type is an integer or unsigned integer number, `false`
  15442. otherwise.
  15443. @complexity Constant.
  15444. @exceptionsafety No-throw guarantee: this member function never throws
  15445. exceptions.
  15446. @liveexample{The following code exemplifies `is_number_integer()` for all
  15447. JSON types.,is_number_integer}
  15448. @sa @ref is_number() -- check if value is a number
  15449. @sa @ref is_number_unsigned() -- check if value is an unsigned integer
  15450. number
  15451. @sa @ref is_number_float() -- check if value is a floating-point number
  15452. @since version 1.0.0
  15453. */
  15454. constexpr bool is_number_integer() const noexcept
  15455. {
  15456. return m_type == value_t::number_integer or m_type == value_t::number_unsigned;
  15457. }
  15458. /*!
  15459. @brief return whether value is an unsigned integer number
  15460. This function returns true if and only if the JSON value is an unsigned
  15461. integer number. This excludes floating-point and signed integer values.
  15462. @return `true` if type is an unsigned integer number, `false` otherwise.
  15463. @complexity Constant.
  15464. @exceptionsafety No-throw guarantee: this member function never throws
  15465. exceptions.
  15466. @liveexample{The following code exemplifies `is_number_unsigned()` for all
  15467. JSON types.,is_number_unsigned}
  15468. @sa @ref is_number() -- check if value is a number
  15469. @sa @ref is_number_integer() -- check if value is an integer or unsigned
  15470. integer number
  15471. @sa @ref is_number_float() -- check if value is a floating-point number
  15472. @since version 2.0.0
  15473. */
  15474. constexpr bool is_number_unsigned() const noexcept
  15475. {
  15476. return m_type == value_t::number_unsigned;
  15477. }
  15478. /*!
  15479. @brief return whether value is a floating-point number
  15480. This function returns true if and only if the JSON value is a
  15481. floating-point number. This excludes signed and unsigned integer values.
  15482. @return `true` if type is a floating-point number, `false` otherwise.
  15483. @complexity Constant.
  15484. @exceptionsafety No-throw guarantee: this member function never throws
  15485. exceptions.
  15486. @liveexample{The following code exemplifies `is_number_float()` for all
  15487. JSON types.,is_number_float}
  15488. @sa @ref is_number() -- check if value is number
  15489. @sa @ref is_number_integer() -- check if value is an integer number
  15490. @sa @ref is_number_unsigned() -- check if value is an unsigned integer
  15491. number
  15492. @since version 1.0.0
  15493. */
  15494. constexpr bool is_number_float() const noexcept
  15495. {
  15496. return m_type == value_t::number_float;
  15497. }
  15498. /*!
  15499. @brief return whether value is an object
  15500. This function returns true if and only if the JSON value is an object.
  15501. @return `true` if type is object, `false` otherwise.
  15502. @complexity Constant.
  15503. @exceptionsafety No-throw guarantee: this member function never throws
  15504. exceptions.
  15505. @liveexample{The following code exemplifies `is_object()` for all JSON
  15506. types.,is_object}
  15507. @since version 1.0.0
  15508. */
  15509. constexpr bool is_object() const noexcept
  15510. {
  15511. return m_type == value_t::object;
  15512. }
  15513. /*!
  15514. @brief return whether value is an array
  15515. This function returns true if and only if the JSON value is an array.
  15516. @return `true` if type is array, `false` otherwise.
  15517. @complexity Constant.
  15518. @exceptionsafety No-throw guarantee: this member function never throws
  15519. exceptions.
  15520. @liveexample{The following code exemplifies `is_array()` for all JSON
  15521. types.,is_array}
  15522. @since version 1.0.0
  15523. */
  15524. constexpr bool is_array() const noexcept
  15525. {
  15526. return m_type == value_t::array;
  15527. }
  15528. /*!
  15529. @brief return whether value is a string
  15530. This function returns true if and only if the JSON value is a string.
  15531. @return `true` if type is string, `false` otherwise.
  15532. @complexity Constant.
  15533. @exceptionsafety No-throw guarantee: this member function never throws
  15534. exceptions.
  15535. @liveexample{The following code exemplifies `is_string()` for all JSON
  15536. types.,is_string}
  15537. @since version 1.0.0
  15538. */
  15539. constexpr bool is_string() const noexcept
  15540. {
  15541. return m_type == value_t::string;
  15542. }
  15543. /*!
  15544. @brief return whether value is a binary array
  15545. This function returns true if and only if the JSON value is a binary array.
  15546. @return `true` if type is binary array, `false` otherwise.
  15547. @complexity Constant.
  15548. @exceptionsafety No-throw guarantee: this member function never throws
  15549. exceptions.
  15550. @liveexample{The following code exemplifies `is_binary()` for all JSON
  15551. types.,is_binary}
  15552. @since version 3.8.0
  15553. */
  15554. constexpr bool is_binary() const noexcept
  15555. {
  15556. return m_type == value_t::binary;
  15557. }
  15558. /*!
  15559. @brief return whether value is discarded
  15560. This function returns true if and only if the JSON value was discarded
  15561. during parsing with a callback function (see @ref parser_callback_t).
  15562. @note This function will always be `false` for JSON values after parsing.
  15563. That is, discarded values can only occur during parsing, but will be
  15564. removed when inside a structured value or replaced by null in other cases.
  15565. @return `true` if type is discarded, `false` otherwise.
  15566. @complexity Constant.
  15567. @exceptionsafety No-throw guarantee: this member function never throws
  15568. exceptions.
  15569. @liveexample{The following code exemplifies `is_discarded()` for all JSON
  15570. types.,is_discarded}
  15571. @since version 1.0.0
  15572. */
  15573. constexpr bool is_discarded() const noexcept
  15574. {
  15575. return m_type == value_t::discarded;
  15576. }
  15577. /*!
  15578. @brief return the type of the JSON value (implicit)
  15579. Implicitly return the type of the JSON value as a value from the @ref
  15580. value_t enumeration.
  15581. @return the type of the JSON value
  15582. @complexity Constant.
  15583. @exceptionsafety No-throw guarantee: this member function never throws
  15584. exceptions.
  15585. @liveexample{The following code exemplifies the @ref value_t operator for
  15586. all JSON types.,operator__value_t}
  15587. @sa @ref type() -- return the type of the JSON value (explicit)
  15588. @sa @ref type_name() -- return the type as string
  15589. @since version 1.0.0
  15590. */
  15591. constexpr operator value_t() const noexcept
  15592. {
  15593. return m_type;
  15594. }
  15595. /// @}
  15596. private:
  15597. //////////////////
  15598. // value access //
  15599. //////////////////
  15600. /// get a boolean (explicit)
  15601. boolean_t get_impl(boolean_t* /*unused*/) const
  15602. {
  15603. if (JSON_HEDLEY_LIKELY(is_boolean()))
  15604. {
  15605. return m_value.boolean;
  15606. }
  15607. JSON_THROW(type_error::create(302, "type must be boolean, but is " + std::string(type_name())));
  15608. }
  15609. /// get a pointer to the value (object)
  15610. object_t* get_impl_ptr(object_t* /*unused*/) noexcept
  15611. {
  15612. return is_object() ? m_value.object : nullptr;
  15613. }
  15614. /// get a pointer to the value (object)
  15615. constexpr const object_t* get_impl_ptr(const object_t* /*unused*/) const noexcept
  15616. {
  15617. return is_object() ? m_value.object : nullptr;
  15618. }
  15619. /// get a pointer to the value (array)
  15620. array_t* get_impl_ptr(array_t* /*unused*/) noexcept
  15621. {
  15622. return is_array() ? m_value.array : nullptr;
  15623. }
  15624. /// get a pointer to the value (array)
  15625. constexpr const array_t* get_impl_ptr(const array_t* /*unused*/) const noexcept
  15626. {
  15627. return is_array() ? m_value.array : nullptr;
  15628. }
  15629. /// get a pointer to the value (string)
  15630. string_t* get_impl_ptr(string_t* /*unused*/) noexcept
  15631. {
  15632. return is_string() ? m_value.string : nullptr;
  15633. }
  15634. /// get a pointer to the value (string)
  15635. constexpr const string_t* get_impl_ptr(const string_t* /*unused*/) const noexcept
  15636. {
  15637. return is_string() ? m_value.string : nullptr;
  15638. }
  15639. /// get a pointer to the value (boolean)
  15640. boolean_t* get_impl_ptr(boolean_t* /*unused*/) noexcept
  15641. {
  15642. return is_boolean() ? &m_value.boolean : nullptr;
  15643. }
  15644. /// get a pointer to the value (boolean)
  15645. constexpr const boolean_t* get_impl_ptr(const boolean_t* /*unused*/) const noexcept
  15646. {
  15647. return is_boolean() ? &m_value.boolean : nullptr;
  15648. }
  15649. /// get a pointer to the value (integer number)
  15650. number_integer_t* get_impl_ptr(number_integer_t* /*unused*/) noexcept
  15651. {
  15652. return is_number_integer() ? &m_value.number_integer : nullptr;
  15653. }
  15654. /// get a pointer to the value (integer number)
  15655. constexpr const number_integer_t* get_impl_ptr(const number_integer_t* /*unused*/) const noexcept
  15656. {
  15657. return is_number_integer() ? &m_value.number_integer : nullptr;
  15658. }
  15659. /// get a pointer to the value (unsigned number)
  15660. number_unsigned_t* get_impl_ptr(number_unsigned_t* /*unused*/) noexcept
  15661. {
  15662. return is_number_unsigned() ? &m_value.number_unsigned : nullptr;
  15663. }
  15664. /// get a pointer to the value (unsigned number)
  15665. constexpr const number_unsigned_t* get_impl_ptr(const number_unsigned_t* /*unused*/) const noexcept
  15666. {
  15667. return is_number_unsigned() ? &m_value.number_unsigned : nullptr;
  15668. }
  15669. /// get a pointer to the value (floating-point number)
  15670. number_float_t* get_impl_ptr(number_float_t* /*unused*/) noexcept
  15671. {
  15672. return is_number_float() ? &m_value.number_float : nullptr;
  15673. }
  15674. /// get a pointer to the value (floating-point number)
  15675. constexpr const number_float_t* get_impl_ptr(const number_float_t* /*unused*/) const noexcept
  15676. {
  15677. return is_number_float() ? &m_value.number_float : nullptr;
  15678. }
  15679. /// get a pointer to the value (binary)
  15680. binary_t* get_impl_ptr(binary_t* /*unused*/) noexcept
  15681. {
  15682. return is_binary() ? m_value.binary : nullptr;
  15683. }
  15684. /// get a pointer to the value (binary)
  15685. constexpr const binary_t* get_impl_ptr(const binary_t* /*unused*/) const noexcept
  15686. {
  15687. return is_binary() ? m_value.binary : nullptr;
  15688. }
  15689. /// get a pointer to the value (binary)
  15690. internal_binary_t* get_impl_ptr(internal_binary_t* /*unused*/) noexcept
  15691. {
  15692. return is_binary() ? m_value.binary : nullptr;
  15693. }
  15694. /// get a pointer to the value (binary)
  15695. constexpr const internal_binary_t* get_impl_ptr(const internal_binary_t* /*unused*/) const noexcept
  15696. {
  15697. return is_binary() ? m_value.binary : nullptr;
  15698. }
  15699. /*!
  15700. @brief helper function to implement get_ref()
  15701. This function helps to implement get_ref() without code duplication for
  15702. const and non-const overloads
  15703. @tparam ThisType will be deduced as `basic_json` or `const basic_json`
  15704. @throw type_error.303 if ReferenceType does not match underlying value
  15705. type of the current JSON
  15706. */
  15707. template<typename ReferenceType, typename ThisType>
  15708. static ReferenceType get_ref_impl(ThisType& obj)
  15709. {
  15710. // delegate the call to get_ptr<>()
  15711. auto ptr = obj.template get_ptr<typename std::add_pointer<ReferenceType>::type>();
  15712. if (JSON_HEDLEY_LIKELY(ptr != nullptr))
  15713. {
  15714. return *ptr;
  15715. }
  15716. JSON_THROW(type_error::create(303, "incompatible ReferenceType for get_ref, actual type is " + std::string(obj.type_name())));
  15717. }
  15718. public:
  15719. /// @name value access
  15720. /// Direct access to the stored value of a JSON value.
  15721. /// @{
  15722. /*!
  15723. @brief get special-case overload
  15724. This overloads avoids a lot of template boilerplate, it can be seen as the
  15725. identity method
  15726. @tparam BasicJsonType == @ref basic_json
  15727. @return a copy of *this
  15728. @complexity Constant.
  15729. @since version 2.1.0
  15730. */
  15731. template<typename BasicJsonType, detail::enable_if_t<
  15732. std::is_same<typename std::remove_const<BasicJsonType>::type, basic_json_t>::value,
  15733. int> = 0>
  15734. basic_json get() const
  15735. {
  15736. return *this;
  15737. }
  15738. /*!
  15739. @brief get special-case overload
  15740. This overloads converts the current @ref basic_json in a different
  15741. @ref basic_json type
  15742. @tparam BasicJsonType == @ref basic_json
  15743. @return a copy of *this, converted into @tparam BasicJsonType
  15744. @complexity Depending on the implementation of the called `from_json()`
  15745. method.
  15746. @since version 3.2.0
  15747. */
  15748. template<typename BasicJsonType, detail::enable_if_t<
  15749. not std::is_same<BasicJsonType, basic_json>::value and
  15750. detail::is_basic_json<BasicJsonType>::value, int> = 0>
  15751. BasicJsonType get() const
  15752. {
  15753. return *this;
  15754. }
  15755. /*!
  15756. @brief get a value (explicit)
  15757. Explicit type conversion between the JSON value and a compatible value
  15758. which is [CopyConstructible](https://en.cppreference.com/w/cpp/named_req/CopyConstructible)
  15759. and [DefaultConstructible](https://en.cppreference.com/w/cpp/named_req/DefaultConstructible).
  15760. The value is converted by calling the @ref json_serializer<ValueType>
  15761. `from_json()` method.
  15762. The function is equivalent to executing
  15763. @code {.cpp}
  15764. ValueType ret;
  15765. JSONSerializer<ValueType>::from_json(*this, ret);
  15766. return ret;
  15767. @endcode
  15768. This overloads is chosen if:
  15769. - @a ValueType is not @ref basic_json,
  15770. - @ref json_serializer<ValueType> has a `from_json()` method of the form
  15771. `void from_json(const basic_json&, ValueType&)`, and
  15772. - @ref json_serializer<ValueType> does not have a `from_json()` method of
  15773. the form `ValueType from_json(const basic_json&)`
  15774. @tparam ValueTypeCV the provided value type
  15775. @tparam ValueType the returned value type
  15776. @return copy of the JSON value, converted to @a ValueType
  15777. @throw what @ref json_serializer<ValueType> `from_json()` method throws
  15778. @liveexample{The example below shows several conversions from JSON values
  15779. to other types. There a few things to note: (1) Floating-point numbers can
  15780. be converted to integers\, (2) A JSON array can be converted to a standard
  15781. `std::vector<short>`\, (3) A JSON object can be converted to C++
  15782. associative containers such as `std::unordered_map<std::string\,
  15783. json>`.,get__ValueType_const}
  15784. @since version 2.1.0
  15785. */
  15786. template<typename ValueTypeCV, typename ValueType = detail::uncvref_t<ValueTypeCV>,
  15787. detail::enable_if_t <
  15788. not detail::is_basic_json<ValueType>::value and
  15789. detail::has_from_json<basic_json_t, ValueType>::value and
  15790. not detail::has_non_default_from_json<basic_json_t, ValueType>::value,
  15791. int> = 0>
  15792. ValueType get() const noexcept(noexcept(
  15793. JSONSerializer<ValueType>::from_json(std::declval<const basic_json_t&>(), std::declval<ValueType&>())))
  15794. {
  15795. // we cannot static_assert on ValueTypeCV being non-const, because
  15796. // there is support for get<const basic_json_t>(), which is why we
  15797. // still need the uncvref
  15798. static_assert(not std::is_reference<ValueTypeCV>::value,
  15799. "get() cannot be used with reference types, you might want to use get_ref()");
  15800. static_assert(std::is_default_constructible<ValueType>::value,
  15801. "types must be DefaultConstructible when used with get()");
  15802. ValueType ret;
  15803. JSONSerializer<ValueType>::from_json(*this, ret);
  15804. return ret;
  15805. }
  15806. /*!
  15807. @brief get a value (explicit); special case
  15808. Explicit type conversion between the JSON value and a compatible value
  15809. which is **not** [CopyConstructible](https://en.cppreference.com/w/cpp/named_req/CopyConstructible)
  15810. and **not** [DefaultConstructible](https://en.cppreference.com/w/cpp/named_req/DefaultConstructible).
  15811. The value is converted by calling the @ref json_serializer<ValueType>
  15812. `from_json()` method.
  15813. The function is equivalent to executing
  15814. @code {.cpp}
  15815. return JSONSerializer<ValueTypeCV>::from_json(*this);
  15816. @endcode
  15817. This overloads is chosen if:
  15818. - @a ValueType is not @ref basic_json and
  15819. - @ref json_serializer<ValueType> has a `from_json()` method of the form
  15820. `ValueType from_json(const basic_json&)`
  15821. @note If @ref json_serializer<ValueType> has both overloads of
  15822. `from_json()`, this one is chosen.
  15823. @tparam ValueTypeCV the provided value type
  15824. @tparam ValueType the returned value type
  15825. @return copy of the JSON value, converted to @a ValueType
  15826. @throw what @ref json_serializer<ValueType> `from_json()` method throws
  15827. @since version 2.1.0
  15828. */
  15829. template<typename ValueTypeCV, typename ValueType = detail::uncvref_t<ValueTypeCV>,
  15830. detail::enable_if_t<not std::is_same<basic_json_t, ValueType>::value and
  15831. detail::has_non_default_from_json<basic_json_t, ValueType>::value,
  15832. int> = 0>
  15833. ValueType get() const noexcept(noexcept(
  15834. JSONSerializer<ValueType>::from_json(std::declval<const basic_json_t&>())))
  15835. {
  15836. static_assert(not std::is_reference<ValueTypeCV>::value,
  15837. "get() cannot be used with reference types, you might want to use get_ref()");
  15838. return JSONSerializer<ValueType>::from_json(*this);
  15839. }
  15840. /*!
  15841. @brief get a value (explicit)
  15842. Explicit type conversion between the JSON value and a compatible value.
  15843. The value is filled into the input parameter by calling the @ref json_serializer<ValueType>
  15844. `from_json()` method.
  15845. The function is equivalent to executing
  15846. @code {.cpp}
  15847. ValueType v;
  15848. JSONSerializer<ValueType>::from_json(*this, v);
  15849. @endcode
  15850. This overloads is chosen if:
  15851. - @a ValueType is not @ref basic_json,
  15852. - @ref json_serializer<ValueType> has a `from_json()` method of the form
  15853. `void from_json(const basic_json&, ValueType&)`, and
  15854. @tparam ValueType the input parameter type.
  15855. @return the input parameter, allowing chaining calls.
  15856. @throw what @ref json_serializer<ValueType> `from_json()` method throws
  15857. @liveexample{The example below shows several conversions from JSON values
  15858. to other types. There a few things to note: (1) Floating-point numbers can
  15859. be converted to integers\, (2) A JSON array can be converted to a standard
  15860. `std::vector<short>`\, (3) A JSON object can be converted to C++
  15861. associative containers such as `std::unordered_map<std::string\,
  15862. json>`.,get_to}
  15863. @since version 3.3.0
  15864. */
  15865. template<typename ValueType,
  15866. detail::enable_if_t <
  15867. not detail::is_basic_json<ValueType>::value and
  15868. detail::has_from_json<basic_json_t, ValueType>::value,
  15869. int> = 0>
  15870. ValueType & get_to(ValueType& v) const noexcept(noexcept(
  15871. JSONSerializer<ValueType>::from_json(std::declval<const basic_json_t&>(), v)))
  15872. {
  15873. JSONSerializer<ValueType>::from_json(*this, v);
  15874. return v;
  15875. }
  15876. template <
  15877. typename T, std::size_t N,
  15878. typename Array = T (&)[N],
  15879. detail::enable_if_t <
  15880. detail::has_from_json<basic_json_t, Array>::value, int > = 0 >
  15881. Array get_to(T (&v)[N]) const
  15882. noexcept(noexcept(JSONSerializer<Array>::from_json(
  15883. std::declval<const basic_json_t&>(), v)))
  15884. {
  15885. JSONSerializer<Array>::from_json(*this, v);
  15886. return v;
  15887. }
  15888. /*!
  15889. @brief get a pointer value (implicit)
  15890. Implicit pointer access to the internally stored JSON value. No copies are
  15891. made.
  15892. @warning Writing data to the pointee of the result yields an undefined
  15893. state.
  15894. @tparam PointerType pointer type; must be a pointer to @ref array_t, @ref
  15895. object_t, @ref string_t, @ref boolean_t, @ref number_integer_t,
  15896. @ref number_unsigned_t, or @ref number_float_t. Enforced by a static
  15897. assertion.
  15898. @return pointer to the internally stored JSON value if the requested
  15899. pointer type @a PointerType fits to the JSON value; `nullptr` otherwise
  15900. @complexity Constant.
  15901. @liveexample{The example below shows how pointers to internal values of a
  15902. JSON value can be requested. Note that no type conversions are made and a
  15903. `nullptr` is returned if the value and the requested pointer type does not
  15904. match.,get_ptr}
  15905. @since version 1.0.0
  15906. */
  15907. template<typename PointerType, typename std::enable_if<
  15908. std::is_pointer<PointerType>::value, int>::type = 0>
  15909. auto get_ptr() noexcept -> decltype(std::declval<basic_json_t&>().get_impl_ptr(std::declval<PointerType>()))
  15910. {
  15911. // delegate the call to get_impl_ptr<>()
  15912. return get_impl_ptr(static_cast<PointerType>(nullptr));
  15913. }
  15914. /*!
  15915. @brief get a pointer value (implicit)
  15916. @copydoc get_ptr()
  15917. */
  15918. template<typename PointerType, typename std::enable_if<
  15919. std::is_pointer<PointerType>::value and
  15920. std::is_const<typename std::remove_pointer<PointerType>::type>::value, int>::type = 0>
  15921. constexpr auto get_ptr() const noexcept -> decltype(std::declval<const basic_json_t&>().get_impl_ptr(std::declval<PointerType>()))
  15922. {
  15923. // delegate the call to get_impl_ptr<>() const
  15924. return get_impl_ptr(static_cast<PointerType>(nullptr));
  15925. }
  15926. /*!
  15927. @brief get a pointer value (explicit)
  15928. Explicit pointer access to the internally stored JSON value. No copies are
  15929. made.
  15930. @warning The pointer becomes invalid if the underlying JSON object
  15931. changes.
  15932. @tparam PointerType pointer type; must be a pointer to @ref array_t, @ref
  15933. object_t, @ref string_t, @ref boolean_t, @ref number_integer_t,
  15934. @ref number_unsigned_t, or @ref number_float_t.
  15935. @return pointer to the internally stored JSON value if the requested
  15936. pointer type @a PointerType fits to the JSON value; `nullptr` otherwise
  15937. @complexity Constant.
  15938. @liveexample{The example below shows how pointers to internal values of a
  15939. JSON value can be requested. Note that no type conversions are made and a
  15940. `nullptr` is returned if the value and the requested pointer type does not
  15941. match.,get__PointerType}
  15942. @sa @ref get_ptr() for explicit pointer-member access
  15943. @since version 1.0.0
  15944. */
  15945. template<typename PointerType, typename std::enable_if<
  15946. std::is_pointer<PointerType>::value, int>::type = 0>
  15947. auto get() noexcept -> decltype(std::declval<basic_json_t&>().template get_ptr<PointerType>())
  15948. {
  15949. // delegate the call to get_ptr
  15950. return get_ptr<PointerType>();
  15951. }
  15952. /*!
  15953. @brief get a pointer value (explicit)
  15954. @copydoc get()
  15955. */
  15956. template<typename PointerType, typename std::enable_if<
  15957. std::is_pointer<PointerType>::value, int>::type = 0>
  15958. constexpr auto get() const noexcept -> decltype(std::declval<const basic_json_t&>().template get_ptr<PointerType>())
  15959. {
  15960. // delegate the call to get_ptr
  15961. return get_ptr<PointerType>();
  15962. }
  15963. /*!
  15964. @brief get a reference value (implicit)
  15965. Implicit reference access to the internally stored JSON value. No copies
  15966. are made.
  15967. @warning Writing data to the referee of the result yields an undefined
  15968. state.
  15969. @tparam ReferenceType reference type; must be a reference to @ref array_t,
  15970. @ref object_t, @ref string_t, @ref boolean_t, @ref number_integer_t, or
  15971. @ref number_float_t. Enforced by static assertion.
  15972. @return reference to the internally stored JSON value if the requested
  15973. reference type @a ReferenceType fits to the JSON value; throws
  15974. type_error.303 otherwise
  15975. @throw type_error.303 in case passed type @a ReferenceType is incompatible
  15976. with the stored JSON value; see example below
  15977. @complexity Constant.
  15978. @liveexample{The example shows several calls to `get_ref()`.,get_ref}
  15979. @since version 1.1.0
  15980. */
  15981. template<typename ReferenceType, typename std::enable_if<
  15982. std::is_reference<ReferenceType>::value, int>::type = 0>
  15983. ReferenceType get_ref()
  15984. {
  15985. // delegate call to get_ref_impl
  15986. return get_ref_impl<ReferenceType>(*this);
  15987. }
  15988. /*!
  15989. @brief get a reference value (implicit)
  15990. @copydoc get_ref()
  15991. */
  15992. template<typename ReferenceType, typename std::enable_if<
  15993. std::is_reference<ReferenceType>::value and
  15994. std::is_const<typename std::remove_reference<ReferenceType>::type>::value, int>::type = 0>
  15995. ReferenceType get_ref() const
  15996. {
  15997. // delegate call to get_ref_impl
  15998. return get_ref_impl<ReferenceType>(*this);
  15999. }
  16000. /*!
  16001. @brief get a value (implicit)
  16002. Implicit type conversion between the JSON value and a compatible value.
  16003. The call is realized by calling @ref get() const.
  16004. @tparam ValueType non-pointer type compatible to the JSON value, for
  16005. instance `int` for JSON integer numbers, `bool` for JSON booleans, or
  16006. `std::vector` types for JSON arrays. The character type of @ref string_t
  16007. as well as an initializer list of this type is excluded to avoid
  16008. ambiguities as these types implicitly convert to `std::string`.
  16009. @return copy of the JSON value, converted to type @a ValueType
  16010. @throw type_error.302 in case passed type @a ValueType is incompatible
  16011. to the JSON value type (e.g., the JSON value is of type boolean, but a
  16012. string is requested); see example below
  16013. @complexity Linear in the size of the JSON value.
  16014. @liveexample{The example below shows several conversions from JSON values
  16015. to other types. There a few things to note: (1) Floating-point numbers can
  16016. be converted to integers\, (2) A JSON array can be converted to a standard
  16017. `std::vector<short>`\, (3) A JSON object can be converted to C++
  16018. associative containers such as `std::unordered_map<std::string\,
  16019. json>`.,operator__ValueType}
  16020. @since version 1.0.0
  16021. */
  16022. template < typename ValueType, typename std::enable_if <
  16023. not std::is_pointer<ValueType>::value and
  16024. not std::is_same<ValueType, detail::json_ref<basic_json>>::value and
  16025. not std::is_same<ValueType, typename string_t::value_type>::value and
  16026. not detail::is_basic_json<ValueType>::value
  16027. and not std::is_same<ValueType, std::initializer_list<typename string_t::value_type>>::value
  16028. #if defined(JSON_HAS_CPP_17) && (defined(__GNUC__) || (defined(_MSC_VER) and _MSC_VER <= 1914))
  16029. and not std::is_same<ValueType, typename std::string_view>::value
  16030. #endif
  16031. and detail::is_detected<detail::get_template_function, const basic_json_t&, ValueType>::value
  16032. , int >::type = 0 >
  16033. operator ValueType() const
  16034. {
  16035. // delegate the call to get<>() const
  16036. return get<ValueType>();
  16037. }
  16038. /// @}
  16039. ////////////////////
  16040. // element access //
  16041. ////////////////////
  16042. /// @name element access
  16043. /// Access to the JSON value.
  16044. /// @{
  16045. /*!
  16046. @brief access specified array element with bounds checking
  16047. Returns a reference to the element at specified location @a idx, with
  16048. bounds checking.
  16049. @param[in] idx index of the element to access
  16050. @return reference to the element at index @a idx
  16051. @throw type_error.304 if the JSON value is not an array; in this case,
  16052. calling `at` with an index makes no sense. See example below.
  16053. @throw out_of_range.401 if the index @a idx is out of range of the array;
  16054. that is, `idx >= size()`. See example below.
  16055. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  16056. changes in the JSON value.
  16057. @complexity Constant.
  16058. @since version 1.0.0
  16059. @liveexample{The example below shows how array elements can be read and
  16060. written using `at()`. It also demonstrates the different exceptions that
  16061. can be thrown.,at__size_type}
  16062. */
  16063. reference at(size_type idx)
  16064. {
  16065. // at only works for arrays
  16066. if (JSON_HEDLEY_LIKELY(is_array()))
  16067. {
  16068. JSON_TRY
  16069. {
  16070. return m_value.array->at(idx);
  16071. }
  16072. JSON_CATCH (std::out_of_range&)
  16073. {
  16074. // create better exception explanation
  16075. JSON_THROW(out_of_range::create(401, "array index " + std::to_string(idx) + " is out of range"));
  16076. }
  16077. }
  16078. else
  16079. {
  16080. JSON_THROW(type_error::create(304, "cannot use at() with " + std::string(type_name())));
  16081. }
  16082. }
  16083. /*!
  16084. @brief access specified array element with bounds checking
  16085. Returns a const reference to the element at specified location @a idx,
  16086. with bounds checking.
  16087. @param[in] idx index of the element to access
  16088. @return const reference to the element at index @a idx
  16089. @throw type_error.304 if the JSON value is not an array; in this case,
  16090. calling `at` with an index makes no sense. See example below.
  16091. @throw out_of_range.401 if the index @a idx is out of range of the array;
  16092. that is, `idx >= size()`. See example below.
  16093. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  16094. changes in the JSON value.
  16095. @complexity Constant.
  16096. @since version 1.0.0
  16097. @liveexample{The example below shows how array elements can be read using
  16098. `at()`. It also demonstrates the different exceptions that can be thrown.,
  16099. at__size_type_const}
  16100. */
  16101. const_reference at(size_type idx) const
  16102. {
  16103. // at only works for arrays
  16104. if (JSON_HEDLEY_LIKELY(is_array()))
  16105. {
  16106. JSON_TRY
  16107. {
  16108. return m_value.array->at(idx);
  16109. }
  16110. JSON_CATCH (std::out_of_range&)
  16111. {
  16112. // create better exception explanation
  16113. JSON_THROW(out_of_range::create(401, "array index " + std::to_string(idx) + " is out of range"));
  16114. }
  16115. }
  16116. else
  16117. {
  16118. JSON_THROW(type_error::create(304, "cannot use at() with " + std::string(type_name())));
  16119. }
  16120. }
  16121. /*!
  16122. @brief access specified object element with bounds checking
  16123. Returns a reference to the element at with specified key @a key, with
  16124. bounds checking.
  16125. @param[in] key key of the element to access
  16126. @return reference to the element at key @a key
  16127. @throw type_error.304 if the JSON value is not an object; in this case,
  16128. calling `at` with a key makes no sense. See example below.
  16129. @throw out_of_range.403 if the key @a key is is not stored in the object;
  16130. that is, `find(key) == end()`. See example below.
  16131. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  16132. changes in the JSON value.
  16133. @complexity Logarithmic in the size of the container.
  16134. @sa @ref operator[](const typename object_t::key_type&) for unchecked
  16135. access by reference
  16136. @sa @ref value() for access by value with a default value
  16137. @since version 1.0.0
  16138. @liveexample{The example below shows how object elements can be read and
  16139. written using `at()`. It also demonstrates the different exceptions that
  16140. can be thrown.,at__object_t_key_type}
  16141. */
  16142. reference at(const typename object_t::key_type& key)
  16143. {
  16144. // at only works for objects
  16145. if (JSON_HEDLEY_LIKELY(is_object()))
  16146. {
  16147. JSON_TRY
  16148. {
  16149. return m_value.object->at(key);
  16150. }
  16151. JSON_CATCH (std::out_of_range&)
  16152. {
  16153. // create better exception explanation
  16154. JSON_THROW(out_of_range::create(403, "key '" + key + "' not found"));
  16155. }
  16156. }
  16157. else
  16158. {
  16159. JSON_THROW(type_error::create(304, "cannot use at() with " + std::string(type_name())));
  16160. }
  16161. }
  16162. /*!
  16163. @brief access specified object element with bounds checking
  16164. Returns a const reference to the element at with specified key @a key,
  16165. with bounds checking.
  16166. @param[in] key key of the element to access
  16167. @return const reference to the element at key @a key
  16168. @throw type_error.304 if the JSON value is not an object; in this case,
  16169. calling `at` with a key makes no sense. See example below.
  16170. @throw out_of_range.403 if the key @a key is is not stored in the object;
  16171. that is, `find(key) == end()`. See example below.
  16172. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  16173. changes in the JSON value.
  16174. @complexity Logarithmic in the size of the container.
  16175. @sa @ref operator[](const typename object_t::key_type&) for unchecked
  16176. access by reference
  16177. @sa @ref value() for access by value with a default value
  16178. @since version 1.0.0
  16179. @liveexample{The example below shows how object elements can be read using
  16180. `at()`. It also demonstrates the different exceptions that can be thrown.,
  16181. at__object_t_key_type_const}
  16182. */
  16183. const_reference at(const typename object_t::key_type& key) const
  16184. {
  16185. // at only works for objects
  16186. if (JSON_HEDLEY_LIKELY(is_object()))
  16187. {
  16188. JSON_TRY
  16189. {
  16190. return m_value.object->at(key);
  16191. }
  16192. JSON_CATCH (std::out_of_range&)
  16193. {
  16194. // create better exception explanation
  16195. JSON_THROW(out_of_range::create(403, "key '" + key + "' not found"));
  16196. }
  16197. }
  16198. else
  16199. {
  16200. JSON_THROW(type_error::create(304, "cannot use at() with " + std::string(type_name())));
  16201. }
  16202. }
  16203. /*!
  16204. @brief access specified array element
  16205. Returns a reference to the element at specified location @a idx.
  16206. @note If @a idx is beyond the range of the array (i.e., `idx >= size()`),
  16207. then the array is silently filled up with `null` values to make `idx` a
  16208. valid reference to the last stored element.
  16209. @param[in] idx index of the element to access
  16210. @return reference to the element at index @a idx
  16211. @throw type_error.305 if the JSON value is not an array or null; in that
  16212. cases, using the [] operator with an index makes no sense.
  16213. @complexity Constant if @a idx is in the range of the array. Otherwise
  16214. linear in `idx - size()`.
  16215. @liveexample{The example below shows how array elements can be read and
  16216. written using `[]` operator. Note the addition of `null`
  16217. values.,operatorarray__size_type}
  16218. @since version 1.0.0
  16219. */
  16220. reference operator[](size_type idx)
  16221. {
  16222. // implicitly convert null value to an empty array
  16223. if (is_null())
  16224. {
  16225. m_type = value_t::array;
  16226. m_value.array = create<array_t>();
  16227. assert_invariant();
  16228. }
  16229. // operator[] only works for arrays
  16230. if (JSON_HEDLEY_LIKELY(is_array()))
  16231. {
  16232. // fill up array with null values if given idx is outside range
  16233. if (idx >= m_value.array->size())
  16234. {
  16235. m_value.array->insert(m_value.array->end(),
  16236. idx - m_value.array->size() + 1,
  16237. basic_json());
  16238. }
  16239. return m_value.array->operator[](idx);
  16240. }
  16241. JSON_THROW(type_error::create(305, "cannot use operator[] with a numeric argument with " + std::string(type_name())));
  16242. }
  16243. /*!
  16244. @brief access specified array element
  16245. Returns a const reference to the element at specified location @a idx.
  16246. @param[in] idx index of the element to access
  16247. @return const reference to the element at index @a idx
  16248. @throw type_error.305 if the JSON value is not an array; in that case,
  16249. using the [] operator with an index makes no sense.
  16250. @complexity Constant.
  16251. @liveexample{The example below shows how array elements can be read using
  16252. the `[]` operator.,operatorarray__size_type_const}
  16253. @since version 1.0.0
  16254. */
  16255. const_reference operator[](size_type idx) const
  16256. {
  16257. // const operator[] only works for arrays
  16258. if (JSON_HEDLEY_LIKELY(is_array()))
  16259. {
  16260. return m_value.array->operator[](idx);
  16261. }
  16262. JSON_THROW(type_error::create(305, "cannot use operator[] with a numeric argument with " + std::string(type_name())));
  16263. }
  16264. /*!
  16265. @brief access specified object element
  16266. Returns a reference to the element at with specified key @a key.
  16267. @note If @a key is not found in the object, then it is silently added to
  16268. the object and filled with a `null` value to make `key` a valid reference.
  16269. In case the value was `null` before, it is converted to an object.
  16270. @param[in] key key of the element to access
  16271. @return reference to the element at key @a key
  16272. @throw type_error.305 if the JSON value is not an object or null; in that
  16273. cases, using the [] operator with a key makes no sense.
  16274. @complexity Logarithmic in the size of the container.
  16275. @liveexample{The example below shows how object elements can be read and
  16276. written using the `[]` operator.,operatorarray__key_type}
  16277. @sa @ref at(const typename object_t::key_type&) for access by reference
  16278. with range checking
  16279. @sa @ref value() for access by value with a default value
  16280. @since version 1.0.0
  16281. */
  16282. reference operator[](const typename object_t::key_type& key)
  16283. {
  16284. // implicitly convert null value to an empty object
  16285. if (is_null())
  16286. {
  16287. m_type = value_t::object;
  16288. m_value.object = create<object_t>();
  16289. assert_invariant();
  16290. }
  16291. // operator[] only works for objects
  16292. if (JSON_HEDLEY_LIKELY(is_object()))
  16293. {
  16294. return m_value.object->operator[](key);
  16295. }
  16296. JSON_THROW(type_error::create(305, "cannot use operator[] with a string argument with " + std::string(type_name())));
  16297. }
  16298. /*!
  16299. @brief read-only access specified object element
  16300. Returns a const reference to the element at with specified key @a key. No
  16301. bounds checking is performed.
  16302. @warning If the element with key @a key does not exist, the behavior is
  16303. undefined.
  16304. @param[in] key key of the element to access
  16305. @return const reference to the element at key @a key
  16306. @pre The element with key @a key must exist. **This precondition is
  16307. enforced with an assertion.**
  16308. @throw type_error.305 if the JSON value is not an object; in that case,
  16309. using the [] operator with a key makes no sense.
  16310. @complexity Logarithmic in the size of the container.
  16311. @liveexample{The example below shows how object elements can be read using
  16312. the `[]` operator.,operatorarray__key_type_const}
  16313. @sa @ref at(const typename object_t::key_type&) for access by reference
  16314. with range checking
  16315. @sa @ref value() for access by value with a default value
  16316. @since version 1.0.0
  16317. */
  16318. const_reference operator[](const typename object_t::key_type& key) const
  16319. {
  16320. // const operator[] only works for objects
  16321. if (JSON_HEDLEY_LIKELY(is_object()))
  16322. {
  16323. assert(m_value.object->find(key) != m_value.object->end());
  16324. return m_value.object->find(key)->second;
  16325. }
  16326. JSON_THROW(type_error::create(305, "cannot use operator[] with a string argument with " + std::string(type_name())));
  16327. }
  16328. /*!
  16329. @brief access specified object element
  16330. Returns a reference to the element at with specified key @a key.
  16331. @note If @a key is not found in the object, then it is silently added to
  16332. the object and filled with a `null` value to make `key` a valid reference.
  16333. In case the value was `null` before, it is converted to an object.
  16334. @param[in] key key of the element to access
  16335. @return reference to the element at key @a key
  16336. @throw type_error.305 if the JSON value is not an object or null; in that
  16337. cases, using the [] operator with a key makes no sense.
  16338. @complexity Logarithmic in the size of the container.
  16339. @liveexample{The example below shows how object elements can be read and
  16340. written using the `[]` operator.,operatorarray__key_type}
  16341. @sa @ref at(const typename object_t::key_type&) for access by reference
  16342. with range checking
  16343. @sa @ref value() for access by value with a default value
  16344. @since version 1.1.0
  16345. */
  16346. template<typename T>
  16347. JSON_HEDLEY_NON_NULL(2)
  16348. reference operator[](T* key)
  16349. {
  16350. // implicitly convert null to object
  16351. if (is_null())
  16352. {
  16353. m_type = value_t::object;
  16354. m_value = value_t::object;
  16355. assert_invariant();
  16356. }
  16357. // at only works for objects
  16358. if (JSON_HEDLEY_LIKELY(is_object()))
  16359. {
  16360. return m_value.object->operator[](key);
  16361. }
  16362. JSON_THROW(type_error::create(305, "cannot use operator[] with a string argument with " + std::string(type_name())));
  16363. }
  16364. /*!
  16365. @brief read-only access specified object element
  16366. Returns a const reference to the element at with specified key @a key. No
  16367. bounds checking is performed.
  16368. @warning If the element with key @a key does not exist, the behavior is
  16369. undefined.
  16370. @param[in] key key of the element to access
  16371. @return const reference to the element at key @a key
  16372. @pre The element with key @a key must exist. **This precondition is
  16373. enforced with an assertion.**
  16374. @throw type_error.305 if the JSON value is not an object; in that case,
  16375. using the [] operator with a key makes no sense.
  16376. @complexity Logarithmic in the size of the container.
  16377. @liveexample{The example below shows how object elements can be read using
  16378. the `[]` operator.,operatorarray__key_type_const}
  16379. @sa @ref at(const typename object_t::key_type&) for access by reference
  16380. with range checking
  16381. @sa @ref value() for access by value with a default value
  16382. @since version 1.1.0
  16383. */
  16384. template<typename T>
  16385. JSON_HEDLEY_NON_NULL(2)
  16386. const_reference operator[](T* key) const
  16387. {
  16388. // at only works for objects
  16389. if (JSON_HEDLEY_LIKELY(is_object()))
  16390. {
  16391. assert(m_value.object->find(key) != m_value.object->end());
  16392. return m_value.object->find(key)->second;
  16393. }
  16394. JSON_THROW(type_error::create(305, "cannot use operator[] with a string argument with " + std::string(type_name())));
  16395. }
  16396. /*!
  16397. @brief access specified object element with default value
  16398. Returns either a copy of an object's element at the specified key @a key
  16399. or a given default value if no element with key @a key exists.
  16400. The function is basically equivalent to executing
  16401. @code {.cpp}
  16402. try {
  16403. return at(key);
  16404. } catch(out_of_range) {
  16405. return default_value;
  16406. }
  16407. @endcode
  16408. @note Unlike @ref at(const typename object_t::key_type&), this function
  16409. does not throw if the given key @a key was not found.
  16410. @note Unlike @ref operator[](const typename object_t::key_type& key), this
  16411. function does not implicitly add an element to the position defined by @a
  16412. key. This function is furthermore also applicable to const objects.
  16413. @param[in] key key of the element to access
  16414. @param[in] default_value the value to return if @a key is not found
  16415. @tparam ValueType type compatible to JSON values, for instance `int` for
  16416. JSON integer numbers, `bool` for JSON booleans, or `std::vector` types for
  16417. JSON arrays. Note the type of the expected value at @a key and the default
  16418. value @a default_value must be compatible.
  16419. @return copy of the element at key @a key or @a default_value if @a key
  16420. is not found
  16421. @throw type_error.302 if @a default_value does not match the type of the
  16422. value at @a key
  16423. @throw type_error.306 if the JSON value is not an object; in that case,
  16424. using `value()` with a key makes no sense.
  16425. @complexity Logarithmic in the size of the container.
  16426. @liveexample{The example below shows how object elements can be queried
  16427. with a default value.,basic_json__value}
  16428. @sa @ref at(const typename object_t::key_type&) for access by reference
  16429. with range checking
  16430. @sa @ref operator[](const typename object_t::key_type&) for unchecked
  16431. access by reference
  16432. @since version 1.0.0
  16433. */
  16434. template<class ValueType, typename std::enable_if<
  16435. std::is_convertible<basic_json_t, ValueType>::value, int>::type = 0>
  16436. ValueType value(const typename object_t::key_type& key, const ValueType& default_value) const
  16437. {
  16438. // at only works for objects
  16439. if (JSON_HEDLEY_LIKELY(is_object()))
  16440. {
  16441. // if key is found, return value and given default value otherwise
  16442. const auto it = find(key);
  16443. if (it != end())
  16444. {
  16445. return *it;
  16446. }
  16447. return default_value;
  16448. }
  16449. JSON_THROW(type_error::create(306, "cannot use value() with " + std::string(type_name())));
  16450. }
  16451. /*!
  16452. @brief overload for a default value of type const char*
  16453. @copydoc basic_json::value(const typename object_t::key_type&, const ValueType&) const
  16454. */
  16455. string_t value(const typename object_t::key_type& key, const char* default_value) const
  16456. {
  16457. return value(key, string_t(default_value));
  16458. }
  16459. /*!
  16460. @brief access specified object element via JSON Pointer with default value
  16461. Returns either a copy of an object's element at the specified key @a key
  16462. or a given default value if no element with key @a key exists.
  16463. The function is basically equivalent to executing
  16464. @code {.cpp}
  16465. try {
  16466. return at(ptr);
  16467. } catch(out_of_range) {
  16468. return default_value;
  16469. }
  16470. @endcode
  16471. @note Unlike @ref at(const json_pointer&), this function does not throw
  16472. if the given key @a key was not found.
  16473. @param[in] ptr a JSON pointer to the element to access
  16474. @param[in] default_value the value to return if @a ptr found no value
  16475. @tparam ValueType type compatible to JSON values, for instance `int` for
  16476. JSON integer numbers, `bool` for JSON booleans, or `std::vector` types for
  16477. JSON arrays. Note the type of the expected value at @a key and the default
  16478. value @a default_value must be compatible.
  16479. @return copy of the element at key @a key or @a default_value if @a key
  16480. is not found
  16481. @throw type_error.302 if @a default_value does not match the type of the
  16482. value at @a ptr
  16483. @throw type_error.306 if the JSON value is not an object; in that case,
  16484. using `value()` with a key makes no sense.
  16485. @complexity Logarithmic in the size of the container.
  16486. @liveexample{The example below shows how object elements can be queried
  16487. with a default value.,basic_json__value_ptr}
  16488. @sa @ref operator[](const json_pointer&) for unchecked access by reference
  16489. @since version 2.0.2
  16490. */
  16491. template<class ValueType, typename std::enable_if<
  16492. std::is_convertible<basic_json_t, ValueType>::value, int>::type = 0>
  16493. ValueType value(const json_pointer& ptr, const ValueType& default_value) const
  16494. {
  16495. // at only works for objects
  16496. if (JSON_HEDLEY_LIKELY(is_object()))
  16497. {
  16498. // if pointer resolves a value, return it or use default value
  16499. JSON_TRY
  16500. {
  16501. return ptr.get_checked(this);
  16502. }
  16503. JSON_INTERNAL_CATCH (out_of_range&)
  16504. {
  16505. return default_value;
  16506. }
  16507. }
  16508. JSON_THROW(type_error::create(306, "cannot use value() with " + std::string(type_name())));
  16509. }
  16510. /*!
  16511. @brief overload for a default value of type const char*
  16512. @copydoc basic_json::value(const json_pointer&, ValueType) const
  16513. */
  16514. JSON_HEDLEY_NON_NULL(3)
  16515. string_t value(const json_pointer& ptr, const char* default_value) const
  16516. {
  16517. return value(ptr, string_t(default_value));
  16518. }
  16519. /*!
  16520. @brief return the binary subtype
  16521. Returns the numerical subtype of the JSON value, if the JSON value is of
  16522. type "binary", and it has a subtype. If it does not have a subtype (or the
  16523. object is not of type binary) this function will return size_t(-1) as a
  16524. sentinel value.
  16525. @return the numerical subtype of the binary JSON value
  16526. @complexity Constant.
  16527. @exceptionsafety No-throw guarantee: this member function never throws
  16528. exceptions.
  16529. @sa @ref set_subtype() -- sets the binary subtype
  16530. @sa @ref clear_subtype() -- clears the binary subtype
  16531. @sa @ref has_subtype() -- returns whether or not the binary value has a
  16532. subtype
  16533. @since version 3.8.0
  16534. */
  16535. std::size_t get_subtype() const noexcept
  16536. {
  16537. if (is_binary() and m_value.binary->has_subtype)
  16538. {
  16539. return m_value.binary->subtype;
  16540. }
  16541. return std::size_t(-1);
  16542. }
  16543. /*!
  16544. @brief sets the binary subtype
  16545. Sets the binary subtype of the JSON value, also flags a binary JSON value as
  16546. having a subtype, which has implications for serialization to msgpack (will
  16547. prefer ext file formats over bin). If the JSON value is not a binary value,
  16548. this function does nothing.
  16549. @complexity Constant.
  16550. @exceptionsafety No-throw guarantee: this member function never throws
  16551. exceptions.
  16552. @sa @ref get_subtype() -- return the binary subtype
  16553. @sa @ref clear_subtype() -- clears the binary subtype
  16554. @sa @ref has_subtype() -- returns whether or not the binary value has a
  16555. subtype
  16556. @since version 3.8.0
  16557. */
  16558. void set_subtype(std::uint8_t subtype) noexcept
  16559. {
  16560. if (is_binary())
  16561. {
  16562. m_value.binary->has_subtype = true;
  16563. m_value.binary->subtype = subtype;
  16564. }
  16565. }
  16566. /*!
  16567. @brief clears the binary subtype
  16568. Clears the binary subtype of the JSON value, also flags a binary JSON value
  16569. as not having a subtype, which has implications for serialization to msgpack
  16570. (will prefer bin file formats over ext). If the JSON value is not a binary
  16571. value, this function does nothing.
  16572. @complexity Constant.
  16573. @exceptionsafety No-throw guarantee: this member function never throws
  16574. exceptions.
  16575. @sa @ref get_subtype() -- return the binary subtype
  16576. @sa @ref set_subtype() -- sets the binary subtype
  16577. @sa @ref has_subtype() -- returns whether or not the binary value has a
  16578. subtype
  16579. @since version 3.8.0
  16580. */
  16581. void clear_subtype() noexcept
  16582. {
  16583. if (is_binary())
  16584. {
  16585. m_value.binary->has_subtype = false;
  16586. m_value.binary->subtype = 0;
  16587. }
  16588. }
  16589. /*!
  16590. @brief return whether or not the binary subtype has a value
  16591. Returns whether or not the binary subtype has a value.
  16592. @return whether or not the binary subtype has a value.
  16593. @complexity Constant.
  16594. @exceptionsafety No-throw guarantee: this member function never throws
  16595. exceptions.
  16596. @sa @ref get_subtype() -- return the binary subtype
  16597. @sa @ref set_subtype() -- sets the binary subtype
  16598. @sa @ref clear_subtype() -- clears the binary subtype
  16599. @since version 3.8.0
  16600. */
  16601. bool has_subtype() const noexcept
  16602. {
  16603. return is_binary() and m_value.binary->has_subtype;
  16604. }
  16605. /*!
  16606. @brief access the first element
  16607. Returns a reference to the first element in the container. For a JSON
  16608. container `c`, the expression `c.front()` is equivalent to `*c.begin()`.
  16609. @return In case of a structured type (array or object), a reference to the
  16610. first element is returned. In case of number, string, boolean, or binary
  16611. values, a reference to the value is returned.
  16612. @complexity Constant.
  16613. @pre The JSON value must not be `null` (would throw `std::out_of_range`)
  16614. or an empty array or object (undefined behavior, **guarded by
  16615. assertions**).
  16616. @post The JSON value remains unchanged.
  16617. @throw invalid_iterator.214 when called on `null` value
  16618. @liveexample{The following code shows an example for `front()`.,front}
  16619. @sa @ref back() -- access the last element
  16620. @since version 1.0.0
  16621. */
  16622. reference front()
  16623. {
  16624. return *begin();
  16625. }
  16626. /*!
  16627. @copydoc basic_json::front()
  16628. */
  16629. const_reference front() const
  16630. {
  16631. return *cbegin();
  16632. }
  16633. /*!
  16634. @brief access the last element
  16635. Returns a reference to the last element in the container. For a JSON
  16636. container `c`, the expression `c.back()` is equivalent to
  16637. @code {.cpp}
  16638. auto tmp = c.end();
  16639. --tmp;
  16640. return *tmp;
  16641. @endcode
  16642. @return In case of a structured type (array or object), a reference to the
  16643. last element is returned. In case of number, string, boolean, or binary
  16644. values, a reference to the value is returned.
  16645. @complexity Constant.
  16646. @pre The JSON value must not be `null` (would throw `std::out_of_range`)
  16647. or an empty array or object (undefined behavior, **guarded by
  16648. assertions**).
  16649. @post The JSON value remains unchanged.
  16650. @throw invalid_iterator.214 when called on a `null` value. See example
  16651. below.
  16652. @liveexample{The following code shows an example for `back()`.,back}
  16653. @sa @ref front() -- access the first element
  16654. @since version 1.0.0
  16655. */
  16656. reference back()
  16657. {
  16658. auto tmp = end();
  16659. --tmp;
  16660. return *tmp;
  16661. }
  16662. /*!
  16663. @copydoc basic_json::back()
  16664. */
  16665. const_reference back() const
  16666. {
  16667. auto tmp = cend();
  16668. --tmp;
  16669. return *tmp;
  16670. }
  16671. /*!
  16672. @brief remove element given an iterator
  16673. Removes the element specified by iterator @a pos. The iterator @a pos must
  16674. be valid and dereferenceable. Thus the `end()` iterator (which is valid,
  16675. but is not dereferenceable) cannot be used as a value for @a pos.
  16676. If called on a primitive type other than `null`, the resulting JSON value
  16677. will be `null`.
  16678. @param[in] pos iterator to the element to remove
  16679. @return Iterator following the last removed element. If the iterator @a
  16680. pos refers to the last element, the `end()` iterator is returned.
  16681. @tparam IteratorType an @ref iterator or @ref const_iterator
  16682. @post Invalidates iterators and references at or after the point of the
  16683. erase, including the `end()` iterator.
  16684. @throw type_error.307 if called on a `null` value; example: `"cannot use
  16685. erase() with null"`
  16686. @throw invalid_iterator.202 if called on an iterator which does not belong
  16687. to the current JSON value; example: `"iterator does not fit current
  16688. value"`
  16689. @throw invalid_iterator.205 if called on a primitive type with invalid
  16690. iterator (i.e., any iterator which is not `begin()`); example: `"iterator
  16691. out of range"`
  16692. @complexity The complexity depends on the type:
  16693. - objects: amortized constant
  16694. - arrays: linear in distance between @a pos and the end of the container
  16695. - strings and binary: linear in the length of the member
  16696. - other types: constant
  16697. @liveexample{The example shows the result of `erase()` for different JSON
  16698. types.,erase__IteratorType}
  16699. @sa @ref erase(IteratorType, IteratorType) -- removes the elements in
  16700. the given range
  16701. @sa @ref erase(const typename object_t::key_type&) -- removes the element
  16702. from an object at the given key
  16703. @sa @ref erase(const size_type) -- removes the element from an array at
  16704. the given index
  16705. @since version 1.0.0
  16706. */
  16707. template<class IteratorType, typename std::enable_if<
  16708. std::is_same<IteratorType, typename basic_json_t::iterator>::value or
  16709. std::is_same<IteratorType, typename basic_json_t::const_iterator>::value, int>::type
  16710. = 0>
  16711. IteratorType erase(IteratorType pos)
  16712. {
  16713. // make sure iterator fits the current value
  16714. if (JSON_HEDLEY_UNLIKELY(this != pos.m_object))
  16715. {
  16716. JSON_THROW(invalid_iterator::create(202, "iterator does not fit current value"));
  16717. }
  16718. IteratorType result = end();
  16719. switch (m_type)
  16720. {
  16721. case value_t::boolean:
  16722. case value_t::number_float:
  16723. case value_t::number_integer:
  16724. case value_t::number_unsigned:
  16725. case value_t::string:
  16726. case value_t::binary:
  16727. {
  16728. if (JSON_HEDLEY_UNLIKELY(not pos.m_it.primitive_iterator.is_begin()))
  16729. {
  16730. JSON_THROW(invalid_iterator::create(205, "iterator out of range"));
  16731. }
  16732. if (is_string())
  16733. {
  16734. AllocatorType<string_t> alloc;
  16735. std::allocator_traits<decltype(alloc)>::destroy(alloc, m_value.string);
  16736. std::allocator_traits<decltype(alloc)>::deallocate(alloc, m_value.string, 1);
  16737. m_value.string = nullptr;
  16738. }
  16739. else if (is_binary())
  16740. {
  16741. AllocatorType<internal_binary_t> alloc;
  16742. std::allocator_traits<decltype(alloc)>::destroy(alloc, m_value.binary);
  16743. std::allocator_traits<decltype(alloc)>::deallocate(alloc, m_value.binary, 1);
  16744. m_value.binary = nullptr;
  16745. }
  16746. m_type = value_t::null;
  16747. assert_invariant();
  16748. break;
  16749. }
  16750. case value_t::object:
  16751. {
  16752. result.m_it.object_iterator = m_value.object->erase(pos.m_it.object_iterator);
  16753. break;
  16754. }
  16755. case value_t::array:
  16756. {
  16757. result.m_it.array_iterator = m_value.array->erase(pos.m_it.array_iterator);
  16758. break;
  16759. }
  16760. default:
  16761. JSON_THROW(type_error::create(307, "cannot use erase() with " + std::string(type_name())));
  16762. }
  16763. return result;
  16764. }
  16765. /*!
  16766. @brief remove elements given an iterator range
  16767. Removes the element specified by the range `[first; last)`. The iterator
  16768. @a first does not need to be dereferenceable if `first == last`: erasing
  16769. an empty range is a no-op.
  16770. If called on a primitive type other than `null`, the resulting JSON value
  16771. will be `null`.
  16772. @param[in] first iterator to the beginning of the range to remove
  16773. @param[in] last iterator past the end of the range to remove
  16774. @return Iterator following the last removed element. If the iterator @a
  16775. second refers to the last element, the `end()` iterator is returned.
  16776. @tparam IteratorType an @ref iterator or @ref const_iterator
  16777. @post Invalidates iterators and references at or after the point of the
  16778. erase, including the `end()` iterator.
  16779. @throw type_error.307 if called on a `null` value; example: `"cannot use
  16780. erase() with null"`
  16781. @throw invalid_iterator.203 if called on iterators which does not belong
  16782. to the current JSON value; example: `"iterators do not fit current value"`
  16783. @throw invalid_iterator.204 if called on a primitive type with invalid
  16784. iterators (i.e., if `first != begin()` and `last != end()`); example:
  16785. `"iterators out of range"`
  16786. @complexity The complexity depends on the type:
  16787. - objects: `log(size()) + std::distance(first, last)`
  16788. - arrays: linear in the distance between @a first and @a last, plus linear
  16789. in the distance between @a last and end of the container
  16790. - strings and binary: linear in the length of the member
  16791. - other types: constant
  16792. @liveexample{The example shows the result of `erase()` for different JSON
  16793. types.,erase__IteratorType_IteratorType}
  16794. @sa @ref erase(IteratorType) -- removes the element at a given position
  16795. @sa @ref erase(const typename object_t::key_type&) -- removes the element
  16796. from an object at the given key
  16797. @sa @ref erase(const size_type) -- removes the element from an array at
  16798. the given index
  16799. @since version 1.0.0
  16800. */
  16801. template<class IteratorType, typename std::enable_if<
  16802. std::is_same<IteratorType, typename basic_json_t::iterator>::value or
  16803. std::is_same<IteratorType, typename basic_json_t::const_iterator>::value, int>::type
  16804. = 0>
  16805. IteratorType erase(IteratorType first, IteratorType last)
  16806. {
  16807. // make sure iterator fits the current value
  16808. if (JSON_HEDLEY_UNLIKELY(this != first.m_object or this != last.m_object))
  16809. {
  16810. JSON_THROW(invalid_iterator::create(203, "iterators do not fit current value"));
  16811. }
  16812. IteratorType result = end();
  16813. switch (m_type)
  16814. {
  16815. case value_t::boolean:
  16816. case value_t::number_float:
  16817. case value_t::number_integer:
  16818. case value_t::number_unsigned:
  16819. case value_t::string:
  16820. case value_t::binary:
  16821. {
  16822. if (JSON_HEDLEY_LIKELY(not first.m_it.primitive_iterator.is_begin()
  16823. or not last.m_it.primitive_iterator.is_end()))
  16824. {
  16825. JSON_THROW(invalid_iterator::create(204, "iterators out of range"));
  16826. }
  16827. if (is_string())
  16828. {
  16829. AllocatorType<string_t> alloc;
  16830. std::allocator_traits<decltype(alloc)>::destroy(alloc, m_value.string);
  16831. std::allocator_traits<decltype(alloc)>::deallocate(alloc, m_value.string, 1);
  16832. m_value.string = nullptr;
  16833. }
  16834. else if (is_binary())
  16835. {
  16836. AllocatorType<internal_binary_t> alloc;
  16837. std::allocator_traits<decltype(alloc)>::destroy(alloc, m_value.binary);
  16838. std::allocator_traits<decltype(alloc)>::deallocate(alloc, m_value.binary, 1);
  16839. m_value.binary = nullptr;
  16840. }
  16841. m_type = value_t::null;
  16842. assert_invariant();
  16843. break;
  16844. }
  16845. case value_t::object:
  16846. {
  16847. result.m_it.object_iterator = m_value.object->erase(first.m_it.object_iterator,
  16848. last.m_it.object_iterator);
  16849. break;
  16850. }
  16851. case value_t::array:
  16852. {
  16853. result.m_it.array_iterator = m_value.array->erase(first.m_it.array_iterator,
  16854. last.m_it.array_iterator);
  16855. break;
  16856. }
  16857. default:
  16858. JSON_THROW(type_error::create(307, "cannot use erase() with " + std::string(type_name())));
  16859. }
  16860. return result;
  16861. }
  16862. /*!
  16863. @brief remove element from a JSON object given a key
  16864. Removes elements from a JSON object with the key value @a key.
  16865. @param[in] key value of the elements to remove
  16866. @return Number of elements removed. If @a ObjectType is the default
  16867. `std::map` type, the return value will always be `0` (@a key was not
  16868. found) or `1` (@a key was found).
  16869. @post References and iterators to the erased elements are invalidated.
  16870. Other references and iterators are not affected.
  16871. @throw type_error.307 when called on a type other than JSON object;
  16872. example: `"cannot use erase() with null"`
  16873. @complexity `log(size()) + count(key)`
  16874. @liveexample{The example shows the effect of `erase()`.,erase__key_type}
  16875. @sa @ref erase(IteratorType) -- removes the element at a given position
  16876. @sa @ref erase(IteratorType, IteratorType) -- removes the elements in
  16877. the given range
  16878. @sa @ref erase(const size_type) -- removes the element from an array at
  16879. the given index
  16880. @since version 1.0.0
  16881. */
  16882. size_type erase(const typename object_t::key_type& key)
  16883. {
  16884. // this erase only works for objects
  16885. if (JSON_HEDLEY_LIKELY(is_object()))
  16886. {
  16887. return m_value.object->erase(key);
  16888. }
  16889. JSON_THROW(type_error::create(307, "cannot use erase() with " + std::string(type_name())));
  16890. }
  16891. /*!
  16892. @brief remove element from a JSON array given an index
  16893. Removes element from a JSON array at the index @a idx.
  16894. @param[in] idx index of the element to remove
  16895. @throw type_error.307 when called on a type other than JSON object;
  16896. example: `"cannot use erase() with null"`
  16897. @throw out_of_range.401 when `idx >= size()`; example: `"array index 17
  16898. is out of range"`
  16899. @complexity Linear in distance between @a idx and the end of the container.
  16900. @liveexample{The example shows the effect of `erase()`.,erase__size_type}
  16901. @sa @ref erase(IteratorType) -- removes the element at a given position
  16902. @sa @ref erase(IteratorType, IteratorType) -- removes the elements in
  16903. the given range
  16904. @sa @ref erase(const typename object_t::key_type&) -- removes the element
  16905. from an object at the given key
  16906. @since version 1.0.0
  16907. */
  16908. void erase(const size_type idx)
  16909. {
  16910. // this erase only works for arrays
  16911. if (JSON_HEDLEY_LIKELY(is_array()))
  16912. {
  16913. if (JSON_HEDLEY_UNLIKELY(idx >= size()))
  16914. {
  16915. JSON_THROW(out_of_range::create(401, "array index " + std::to_string(idx) + " is out of range"));
  16916. }
  16917. m_value.array->erase(m_value.array->begin() + static_cast<difference_type>(idx));
  16918. }
  16919. else
  16920. {
  16921. JSON_THROW(type_error::create(307, "cannot use erase() with " + std::string(type_name())));
  16922. }
  16923. }
  16924. /// @}
  16925. ////////////
  16926. // lookup //
  16927. ////////////
  16928. /// @name lookup
  16929. /// @{
  16930. /*!
  16931. @brief find an element in a JSON object
  16932. Finds an element in a JSON object with key equivalent to @a key. If the
  16933. element is not found or the JSON value is not an object, end() is
  16934. returned.
  16935. @note This method always returns @ref end() when executed on a JSON type
  16936. that is not an object.
  16937. @param[in] key key value of the element to search for.
  16938. @return Iterator to an element with key equivalent to @a key. If no such
  16939. element is found or the JSON value is not an object, past-the-end (see
  16940. @ref end()) iterator is returned.
  16941. @complexity Logarithmic in the size of the JSON object.
  16942. @liveexample{The example shows how `find()` is used.,find__key_type}
  16943. @sa @ref contains(KeyT&&) const -- checks whether a key exists
  16944. @since version 1.0.0
  16945. */
  16946. template<typename KeyT>
  16947. iterator find(KeyT&& key)
  16948. {
  16949. auto result = end();
  16950. if (is_object())
  16951. {
  16952. result.m_it.object_iterator = m_value.object->find(std::forward<KeyT>(key));
  16953. }
  16954. return result;
  16955. }
  16956. /*!
  16957. @brief find an element in a JSON object
  16958. @copydoc find(KeyT&&)
  16959. */
  16960. template<typename KeyT>
  16961. const_iterator find(KeyT&& key) const
  16962. {
  16963. auto result = cend();
  16964. if (is_object())
  16965. {
  16966. result.m_it.object_iterator = m_value.object->find(std::forward<KeyT>(key));
  16967. }
  16968. return result;
  16969. }
  16970. /*!
  16971. @brief returns the number of occurrences of a key in a JSON object
  16972. Returns the number of elements with key @a key. If ObjectType is the
  16973. default `std::map` type, the return value will always be `0` (@a key was
  16974. not found) or `1` (@a key was found).
  16975. @note This method always returns `0` when executed on a JSON type that is
  16976. not an object.
  16977. @param[in] key key value of the element to count
  16978. @return Number of elements with key @a key. If the JSON value is not an
  16979. object, the return value will be `0`.
  16980. @complexity Logarithmic in the size of the JSON object.
  16981. @liveexample{The example shows how `count()` is used.,count}
  16982. @since version 1.0.0
  16983. */
  16984. template<typename KeyT>
  16985. size_type count(KeyT&& key) const
  16986. {
  16987. // return 0 for all nonobject types
  16988. return is_object() ? m_value.object->count(std::forward<KeyT>(key)) : 0;
  16989. }
  16990. /*!
  16991. @brief check the existence of an element in a JSON object
  16992. Check whether an element exists in a JSON object with key equivalent to
  16993. @a key. If the element is not found or the JSON value is not an object,
  16994. false is returned.
  16995. @note This method always returns false when executed on a JSON type
  16996. that is not an object.
  16997. @param[in] key key value to check its existence.
  16998. @return true if an element with specified @a key exists. If no such
  16999. element with such key is found or the JSON value is not an object,
  17000. false is returned.
  17001. @complexity Logarithmic in the size of the JSON object.
  17002. @liveexample{The following code shows an example for `contains()`.,contains}
  17003. @sa @ref find(KeyT&&) -- returns an iterator to an object element
  17004. @sa @ref contains(const json_pointer&) const -- checks the existence for a JSON pointer
  17005. @since version 3.6.0
  17006. */
  17007. template<typename KeyT, typename std::enable_if<
  17008. not std::is_same<typename std::decay<KeyT>::type, json_pointer>::value, int>::type = 0>
  17009. bool contains(KeyT && key) const
  17010. {
  17011. return is_object() and m_value.object->find(std::forward<KeyT>(key)) != m_value.object->end();
  17012. }
  17013. /*!
  17014. @brief check the existence of an element in a JSON object given a JSON pointer
  17015. Check whether the given JSON pointer @a ptr can be resolved in the current
  17016. JSON value.
  17017. @note This method can be executed on any JSON value type.
  17018. @param[in] ptr JSON pointer to check its existence.
  17019. @return true if the JSON pointer can be resolved to a stored value, false
  17020. otherwise.
  17021. @post If `j.contains(ptr)` returns true, it is safe to call `j[ptr]`.
  17022. @throw parse_error.106 if an array index begins with '0'
  17023. @throw parse_error.109 if an array index was not a number
  17024. @complexity Logarithmic in the size of the JSON object.
  17025. @liveexample{The following code shows an example for `contains()`.,contains_json_pointer}
  17026. @sa @ref contains(KeyT &&) const -- checks the existence of a key
  17027. @since version 3.7.0
  17028. */
  17029. bool contains(const json_pointer& ptr) const
  17030. {
  17031. return ptr.contains(this);
  17032. }
  17033. /// @}
  17034. ///////////////
  17035. // iterators //
  17036. ///////////////
  17037. /// @name iterators
  17038. /// @{
  17039. /*!
  17040. @brief returns an iterator to the first element
  17041. Returns an iterator to the first element.
  17042. @image html range-begin-end.svg "Illustration from cppreference.com"
  17043. @return iterator to the first element
  17044. @complexity Constant.
  17045. @requirement This function helps `basic_json` satisfying the
  17046. [Container](https://en.cppreference.com/w/cpp/named_req/Container)
  17047. requirements:
  17048. - The complexity is constant.
  17049. @liveexample{The following code shows an example for `begin()`.,begin}
  17050. @sa @ref cbegin() -- returns a const iterator to the beginning
  17051. @sa @ref end() -- returns an iterator to the end
  17052. @sa @ref cend() -- returns a const iterator to the end
  17053. @since version 1.0.0
  17054. */
  17055. iterator begin() noexcept
  17056. {
  17057. iterator result(this);
  17058. result.set_begin();
  17059. return result;
  17060. }
  17061. /*!
  17062. @copydoc basic_json::cbegin()
  17063. */
  17064. const_iterator begin() const noexcept
  17065. {
  17066. return cbegin();
  17067. }
  17068. /*!
  17069. @brief returns a const iterator to the first element
  17070. Returns a const iterator to the first element.
  17071. @image html range-begin-end.svg "Illustration from cppreference.com"
  17072. @return const iterator to the first element
  17073. @complexity Constant.
  17074. @requirement This function helps `basic_json` satisfying the
  17075. [Container](https://en.cppreference.com/w/cpp/named_req/Container)
  17076. requirements:
  17077. - The complexity is constant.
  17078. - Has the semantics of `const_cast<const basic_json&>(*this).begin()`.
  17079. @liveexample{The following code shows an example for `cbegin()`.,cbegin}
  17080. @sa @ref begin() -- returns an iterator to the beginning
  17081. @sa @ref end() -- returns an iterator to the end
  17082. @sa @ref cend() -- returns a const iterator to the end
  17083. @since version 1.0.0
  17084. */
  17085. const_iterator cbegin() const noexcept
  17086. {
  17087. const_iterator result(this);
  17088. result.set_begin();
  17089. return result;
  17090. }
  17091. /*!
  17092. @brief returns an iterator to one past the last element
  17093. Returns an iterator to one past the last element.
  17094. @image html range-begin-end.svg "Illustration from cppreference.com"
  17095. @return iterator one past the last element
  17096. @complexity Constant.
  17097. @requirement This function helps `basic_json` satisfying the
  17098. [Container](https://en.cppreference.com/w/cpp/named_req/Container)
  17099. requirements:
  17100. - The complexity is constant.
  17101. @liveexample{The following code shows an example for `end()`.,end}
  17102. @sa @ref cend() -- returns a const iterator to the end
  17103. @sa @ref begin() -- returns an iterator to the beginning
  17104. @sa @ref cbegin() -- returns a const iterator to the beginning
  17105. @since version 1.0.0
  17106. */
  17107. iterator end() noexcept
  17108. {
  17109. iterator result(this);
  17110. result.set_end();
  17111. return result;
  17112. }
  17113. /*!
  17114. @copydoc basic_json::cend()
  17115. */
  17116. const_iterator end() const noexcept
  17117. {
  17118. return cend();
  17119. }
  17120. /*!
  17121. @brief returns a const iterator to one past the last element
  17122. Returns a const iterator to one past the last element.
  17123. @image html range-begin-end.svg "Illustration from cppreference.com"
  17124. @return const iterator one past the last element
  17125. @complexity Constant.
  17126. @requirement This function helps `basic_json` satisfying the
  17127. [Container](https://en.cppreference.com/w/cpp/named_req/Container)
  17128. requirements:
  17129. - The complexity is constant.
  17130. - Has the semantics of `const_cast<const basic_json&>(*this).end()`.
  17131. @liveexample{The following code shows an example for `cend()`.,cend}
  17132. @sa @ref end() -- returns an iterator to the end
  17133. @sa @ref begin() -- returns an iterator to the beginning
  17134. @sa @ref cbegin() -- returns a const iterator to the beginning
  17135. @since version 1.0.0
  17136. */
  17137. const_iterator cend() const noexcept
  17138. {
  17139. const_iterator result(this);
  17140. result.set_end();
  17141. return result;
  17142. }
  17143. /*!
  17144. @brief returns an iterator to the reverse-beginning
  17145. Returns an iterator to the reverse-beginning; that is, the last element.
  17146. @image html range-rbegin-rend.svg "Illustration from cppreference.com"
  17147. @complexity Constant.
  17148. @requirement This function helps `basic_json` satisfying the
  17149. [ReversibleContainer](https://en.cppreference.com/w/cpp/named_req/ReversibleContainer)
  17150. requirements:
  17151. - The complexity is constant.
  17152. - Has the semantics of `reverse_iterator(end())`.
  17153. @liveexample{The following code shows an example for `rbegin()`.,rbegin}
  17154. @sa @ref crbegin() -- returns a const reverse iterator to the beginning
  17155. @sa @ref rend() -- returns a reverse iterator to the end
  17156. @sa @ref crend() -- returns a const reverse iterator to the end
  17157. @since version 1.0.0
  17158. */
  17159. reverse_iterator rbegin() noexcept
  17160. {
  17161. return reverse_iterator(end());
  17162. }
  17163. /*!
  17164. @copydoc basic_json::crbegin()
  17165. */
  17166. const_reverse_iterator rbegin() const noexcept
  17167. {
  17168. return crbegin();
  17169. }
  17170. /*!
  17171. @brief returns an iterator to the reverse-end
  17172. Returns an iterator to the reverse-end; that is, one before the first
  17173. element.
  17174. @image html range-rbegin-rend.svg "Illustration from cppreference.com"
  17175. @complexity Constant.
  17176. @requirement This function helps `basic_json` satisfying the
  17177. [ReversibleContainer](https://en.cppreference.com/w/cpp/named_req/ReversibleContainer)
  17178. requirements:
  17179. - The complexity is constant.
  17180. - Has the semantics of `reverse_iterator(begin())`.
  17181. @liveexample{The following code shows an example for `rend()`.,rend}
  17182. @sa @ref crend() -- returns a const reverse iterator to the end
  17183. @sa @ref rbegin() -- returns a reverse iterator to the beginning
  17184. @sa @ref crbegin() -- returns a const reverse iterator to the beginning
  17185. @since version 1.0.0
  17186. */
  17187. reverse_iterator rend() noexcept
  17188. {
  17189. return reverse_iterator(begin());
  17190. }
  17191. /*!
  17192. @copydoc basic_json::crend()
  17193. */
  17194. const_reverse_iterator rend() const noexcept
  17195. {
  17196. return crend();
  17197. }
  17198. /*!
  17199. @brief returns a const reverse iterator to the last element
  17200. Returns a const iterator to the reverse-beginning; that is, the last
  17201. element.
  17202. @image html range-rbegin-rend.svg "Illustration from cppreference.com"
  17203. @complexity Constant.
  17204. @requirement This function helps `basic_json` satisfying the
  17205. [ReversibleContainer](https://en.cppreference.com/w/cpp/named_req/ReversibleContainer)
  17206. requirements:
  17207. - The complexity is constant.
  17208. - Has the semantics of `const_cast<const basic_json&>(*this).rbegin()`.
  17209. @liveexample{The following code shows an example for `crbegin()`.,crbegin}
  17210. @sa @ref rbegin() -- returns a reverse iterator to the beginning
  17211. @sa @ref rend() -- returns a reverse iterator to the end
  17212. @sa @ref crend() -- returns a const reverse iterator to the end
  17213. @since version 1.0.0
  17214. */
  17215. const_reverse_iterator crbegin() const noexcept
  17216. {
  17217. return const_reverse_iterator(cend());
  17218. }
  17219. /*!
  17220. @brief returns a const reverse iterator to one before the first
  17221. Returns a const reverse iterator to the reverse-end; that is, one before
  17222. the first element.
  17223. @image html range-rbegin-rend.svg "Illustration from cppreference.com"
  17224. @complexity Constant.
  17225. @requirement This function helps `basic_json` satisfying the
  17226. [ReversibleContainer](https://en.cppreference.com/w/cpp/named_req/ReversibleContainer)
  17227. requirements:
  17228. - The complexity is constant.
  17229. - Has the semantics of `const_cast<const basic_json&>(*this).rend()`.
  17230. @liveexample{The following code shows an example for `crend()`.,crend}
  17231. @sa @ref rend() -- returns a reverse iterator to the end
  17232. @sa @ref rbegin() -- returns a reverse iterator to the beginning
  17233. @sa @ref crbegin() -- returns a const reverse iterator to the beginning
  17234. @since version 1.0.0
  17235. */
  17236. const_reverse_iterator crend() const noexcept
  17237. {
  17238. return const_reverse_iterator(cbegin());
  17239. }
  17240. public:
  17241. /*!
  17242. @brief wrapper to access iterator member functions in range-based for
  17243. This function allows to access @ref iterator::key() and @ref
  17244. iterator::value() during range-based for loops. In these loops, a
  17245. reference to the JSON values is returned, so there is no access to the
  17246. underlying iterator.
  17247. For loop without iterator_wrapper:
  17248. @code{cpp}
  17249. for (auto it = j_object.begin(); it != j_object.end(); ++it)
  17250. {
  17251. std::cout << "key: " << it.key() << ", value:" << it.value() << '\n';
  17252. }
  17253. @endcode
  17254. Range-based for loop without iterator proxy:
  17255. @code{cpp}
  17256. for (auto it : j_object)
  17257. {
  17258. // "it" is of type json::reference and has no key() member
  17259. std::cout << "value: " << it << '\n';
  17260. }
  17261. @endcode
  17262. Range-based for loop with iterator proxy:
  17263. @code{cpp}
  17264. for (auto it : json::iterator_wrapper(j_object))
  17265. {
  17266. std::cout << "key: " << it.key() << ", value:" << it.value() << '\n';
  17267. }
  17268. @endcode
  17269. @note When iterating over an array, `key()` will return the index of the
  17270. element as string (see example).
  17271. @param[in] ref reference to a JSON value
  17272. @return iteration proxy object wrapping @a ref with an interface to use in
  17273. range-based for loops
  17274. @liveexample{The following code shows how the wrapper is used,iterator_wrapper}
  17275. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  17276. changes in the JSON value.
  17277. @complexity Constant.
  17278. @note The name of this function is not yet final and may change in the
  17279. future.
  17280. @deprecated This stream operator is deprecated and will be removed in
  17281. future 4.0.0 of the library. Please use @ref items() instead;
  17282. that is, replace `json::iterator_wrapper(j)` with `j.items()`.
  17283. */
  17284. JSON_HEDLEY_DEPRECATED(3.1.0)
  17285. static iteration_proxy<iterator> iterator_wrapper(reference ref) noexcept
  17286. {
  17287. return ref.items();
  17288. }
  17289. /*!
  17290. @copydoc iterator_wrapper(reference)
  17291. */
  17292. JSON_HEDLEY_DEPRECATED(3.1.0)
  17293. static iteration_proxy<const_iterator> iterator_wrapper(const_reference ref) noexcept
  17294. {
  17295. return ref.items();
  17296. }
  17297. /*!
  17298. @brief helper to access iterator member functions in range-based for
  17299. This function allows to access @ref iterator::key() and @ref
  17300. iterator::value() during range-based for loops. In these loops, a
  17301. reference to the JSON values is returned, so there is no access to the
  17302. underlying iterator.
  17303. For loop without `items()` function:
  17304. @code{cpp}
  17305. for (auto it = j_object.begin(); it != j_object.end(); ++it)
  17306. {
  17307. std::cout << "key: " << it.key() << ", value:" << it.value() << '\n';
  17308. }
  17309. @endcode
  17310. Range-based for loop without `items()` function:
  17311. @code{cpp}
  17312. for (auto it : j_object)
  17313. {
  17314. // "it" is of type json::reference and has no key() member
  17315. std::cout << "value: " << it << '\n';
  17316. }
  17317. @endcode
  17318. Range-based for loop with `items()` function:
  17319. @code{cpp}
  17320. for (auto& el : j_object.items())
  17321. {
  17322. std::cout << "key: " << el.key() << ", value:" << el.value() << '\n';
  17323. }
  17324. @endcode
  17325. The `items()` function also allows to use
  17326. [structured bindings](https://en.cppreference.com/w/cpp/language/structured_binding)
  17327. (C++17):
  17328. @code{cpp}
  17329. for (auto& [key, val] : j_object.items())
  17330. {
  17331. std::cout << "key: " << key << ", value:" << val << '\n';
  17332. }
  17333. @endcode
  17334. @note When iterating over an array, `key()` will return the index of the
  17335. element as string (see example). For primitive types (e.g., numbers),
  17336. `key()` returns an empty string.
  17337. @return iteration proxy object wrapping @a ref with an interface to use in
  17338. range-based for loops
  17339. @liveexample{The following code shows how the function is used.,items}
  17340. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  17341. changes in the JSON value.
  17342. @complexity Constant.
  17343. @since version 3.1.0, structured bindings support since 3.5.0.
  17344. */
  17345. iteration_proxy<iterator> items() noexcept
  17346. {
  17347. return iteration_proxy<iterator>(*this);
  17348. }
  17349. /*!
  17350. @copydoc items()
  17351. */
  17352. iteration_proxy<const_iterator> items() const noexcept
  17353. {
  17354. return iteration_proxy<const_iterator>(*this);
  17355. }
  17356. /// @}
  17357. //////////////
  17358. // capacity //
  17359. //////////////
  17360. /// @name capacity
  17361. /// @{
  17362. /*!
  17363. @brief checks whether the container is empty.
  17364. Checks if a JSON value has no elements (i.e. whether its @ref size is `0`).
  17365. @return The return value depends on the different types and is
  17366. defined as follows:
  17367. Value type | return value
  17368. ----------- | -------------
  17369. null | `true`
  17370. boolean | `false`
  17371. string | `false`
  17372. number | `false`
  17373. binary | `false`
  17374. object | result of function `object_t::empty()`
  17375. array | result of function `array_t::empty()`
  17376. @liveexample{The following code uses `empty()` to check if a JSON
  17377. object contains any elements.,empty}
  17378. @complexity Constant, as long as @ref array_t and @ref object_t satisfy
  17379. the Container concept; that is, their `empty()` functions have constant
  17380. complexity.
  17381. @iterators No changes.
  17382. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  17383. @note This function does not return whether a string stored as JSON value
  17384. is empty - it returns whether the JSON container itself is empty which is
  17385. false in the case of a string.
  17386. @requirement This function helps `basic_json` satisfying the
  17387. [Container](https://en.cppreference.com/w/cpp/named_req/Container)
  17388. requirements:
  17389. - The complexity is constant.
  17390. - Has the semantics of `begin() == end()`.
  17391. @sa @ref size() -- returns the number of elements
  17392. @since version 1.0.0
  17393. */
  17394. bool empty() const noexcept
  17395. {
  17396. switch (m_type)
  17397. {
  17398. case value_t::null:
  17399. {
  17400. // null values are empty
  17401. return true;
  17402. }
  17403. case value_t::array:
  17404. {
  17405. // delegate call to array_t::empty()
  17406. return m_value.array->empty();
  17407. }
  17408. case value_t::object:
  17409. {
  17410. // delegate call to object_t::empty()
  17411. return m_value.object->empty();
  17412. }
  17413. default:
  17414. {
  17415. // all other types are nonempty
  17416. return false;
  17417. }
  17418. }
  17419. }
  17420. /*!
  17421. @brief returns the number of elements
  17422. Returns the number of elements in a JSON value.
  17423. @return The return value depends on the different types and is
  17424. defined as follows:
  17425. Value type | return value
  17426. ----------- | -------------
  17427. null | `0`
  17428. boolean | `1`
  17429. string | `1`
  17430. number | `1`
  17431. binary | `1`
  17432. object | result of function object_t::size()
  17433. array | result of function array_t::size()
  17434. @liveexample{The following code calls `size()` on the different value
  17435. types.,size}
  17436. @complexity Constant, as long as @ref array_t and @ref object_t satisfy
  17437. the Container concept; that is, their size() functions have constant
  17438. complexity.
  17439. @iterators No changes.
  17440. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  17441. @note This function does not return the length of a string stored as JSON
  17442. value - it returns the number of elements in the JSON value which is 1 in
  17443. the case of a string.
  17444. @requirement This function helps `basic_json` satisfying the
  17445. [Container](https://en.cppreference.com/w/cpp/named_req/Container)
  17446. requirements:
  17447. - The complexity is constant.
  17448. - Has the semantics of `std::distance(begin(), end())`.
  17449. @sa @ref empty() -- checks whether the container is empty
  17450. @sa @ref max_size() -- returns the maximal number of elements
  17451. @since version 1.0.0
  17452. */
  17453. size_type size() const noexcept
  17454. {
  17455. switch (m_type)
  17456. {
  17457. case value_t::null:
  17458. {
  17459. // null values are empty
  17460. return 0;
  17461. }
  17462. case value_t::array:
  17463. {
  17464. // delegate call to array_t::size()
  17465. return m_value.array->size();
  17466. }
  17467. case value_t::object:
  17468. {
  17469. // delegate call to object_t::size()
  17470. return m_value.object->size();
  17471. }
  17472. default:
  17473. {
  17474. // all other types have size 1
  17475. return 1;
  17476. }
  17477. }
  17478. }
  17479. /*!
  17480. @brief returns the maximum possible number of elements
  17481. Returns the maximum number of elements a JSON value is able to hold due to
  17482. system or library implementation limitations, i.e. `std::distance(begin(),
  17483. end())` for the JSON value.
  17484. @return The return value depends on the different types and is
  17485. defined as follows:
  17486. Value type | return value
  17487. ----------- | -------------
  17488. null | `0` (same as `size()`)
  17489. boolean | `1` (same as `size()`)
  17490. string | `1` (same as `size()`)
  17491. number | `1` (same as `size()`)
  17492. binary | `1` (same as `size()`)
  17493. object | result of function `object_t::max_size()`
  17494. array | result of function `array_t::max_size()`
  17495. @liveexample{The following code calls `max_size()` on the different value
  17496. types. Note the output is implementation specific.,max_size}
  17497. @complexity Constant, as long as @ref array_t and @ref object_t satisfy
  17498. the Container concept; that is, their `max_size()` functions have constant
  17499. complexity.
  17500. @iterators No changes.
  17501. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  17502. @requirement This function helps `basic_json` satisfying the
  17503. [Container](https://en.cppreference.com/w/cpp/named_req/Container)
  17504. requirements:
  17505. - The complexity is constant.
  17506. - Has the semantics of returning `b.size()` where `b` is the largest
  17507. possible JSON value.
  17508. @sa @ref size() -- returns the number of elements
  17509. @since version 1.0.0
  17510. */
  17511. size_type max_size() const noexcept
  17512. {
  17513. switch (m_type)
  17514. {
  17515. case value_t::array:
  17516. {
  17517. // delegate call to array_t::max_size()
  17518. return m_value.array->max_size();
  17519. }
  17520. case value_t::object:
  17521. {
  17522. // delegate call to object_t::max_size()
  17523. return m_value.object->max_size();
  17524. }
  17525. default:
  17526. {
  17527. // all other types have max_size() == size()
  17528. return size();
  17529. }
  17530. }
  17531. }
  17532. /// @}
  17533. ///////////////
  17534. // modifiers //
  17535. ///////////////
  17536. /// @name modifiers
  17537. /// @{
  17538. /*!
  17539. @brief clears the contents
  17540. Clears the content of a JSON value and resets it to the default value as
  17541. if @ref basic_json(value_t) would have been called with the current value
  17542. type from @ref type():
  17543. Value type | initial value
  17544. ----------- | -------------
  17545. null | `null`
  17546. boolean | `false`
  17547. string | `""`
  17548. number | `0`
  17549. binary | An empty byte vector
  17550. object | `{}`
  17551. array | `[]`
  17552. @post Has the same effect as calling
  17553. @code {.cpp}
  17554. *this = basic_json(type());
  17555. @endcode
  17556. @liveexample{The example below shows the effect of `clear()` to different
  17557. JSON types.,clear}
  17558. @complexity Linear in the size of the JSON value.
  17559. @iterators All iterators, pointers and references related to this container
  17560. are invalidated.
  17561. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  17562. @sa @ref basic_json(value_t) -- constructor that creates an object with the
  17563. same value than calling `clear()`
  17564. @since version 1.0.0
  17565. */
  17566. void clear() noexcept
  17567. {
  17568. switch (m_type)
  17569. {
  17570. case value_t::number_integer:
  17571. {
  17572. m_value.number_integer = 0;
  17573. break;
  17574. }
  17575. case value_t::number_unsigned:
  17576. {
  17577. m_value.number_unsigned = 0;
  17578. break;
  17579. }
  17580. case value_t::number_float:
  17581. {
  17582. m_value.number_float = 0.0;
  17583. break;
  17584. }
  17585. case value_t::boolean:
  17586. {
  17587. m_value.boolean = false;
  17588. break;
  17589. }
  17590. case value_t::string:
  17591. {
  17592. m_value.string->clear();
  17593. break;
  17594. }
  17595. case value_t::binary:
  17596. {
  17597. m_value.binary->clear();
  17598. break;
  17599. }
  17600. case value_t::array:
  17601. {
  17602. m_value.array->clear();
  17603. break;
  17604. }
  17605. case value_t::object:
  17606. {
  17607. m_value.object->clear();
  17608. break;
  17609. }
  17610. default:
  17611. break;
  17612. }
  17613. }
  17614. /*!
  17615. @brief add an object to an array
  17616. Appends the given element @a val to the end of the JSON value. If the
  17617. function is called on a JSON null value, an empty array is created before
  17618. appending @a val.
  17619. @param[in] val the value to add to the JSON array
  17620. @throw type_error.308 when called on a type other than JSON array or
  17621. null; example: `"cannot use push_back() with number"`
  17622. @complexity Amortized constant.
  17623. @liveexample{The example shows how `push_back()` and `+=` can be used to
  17624. add elements to a JSON array. Note how the `null` value was silently
  17625. converted to a JSON array.,push_back}
  17626. @since version 1.0.0
  17627. */
  17628. void push_back(basic_json&& val)
  17629. {
  17630. // push_back only works for null objects or arrays
  17631. if (JSON_HEDLEY_UNLIKELY(not(is_null() or is_array())))
  17632. {
  17633. JSON_THROW(type_error::create(308, "cannot use push_back() with " + std::string(type_name())));
  17634. }
  17635. // transform null object into an array
  17636. if (is_null())
  17637. {
  17638. m_type = value_t::array;
  17639. m_value = value_t::array;
  17640. assert_invariant();
  17641. }
  17642. // add element to array (move semantics)
  17643. m_value.array->push_back(std::move(val));
  17644. // if val is moved from, basic_json move constructor marks it null so we do not call the destructor
  17645. }
  17646. /*!
  17647. @brief add an object to an array
  17648. @copydoc push_back(basic_json&&)
  17649. */
  17650. reference operator+=(basic_json&& val)
  17651. {
  17652. push_back(std::move(val));
  17653. return *this;
  17654. }
  17655. /*!
  17656. @brief add an object to an array
  17657. @copydoc push_back(basic_json&&)
  17658. */
  17659. void push_back(const basic_json& val)
  17660. {
  17661. // push_back only works for null objects or arrays
  17662. if (JSON_HEDLEY_UNLIKELY(not(is_null() or is_array())))
  17663. {
  17664. JSON_THROW(type_error::create(308, "cannot use push_back() with " + std::string(type_name())));
  17665. }
  17666. // transform null object into an array
  17667. if (is_null())
  17668. {
  17669. m_type = value_t::array;
  17670. m_value = value_t::array;
  17671. assert_invariant();
  17672. }
  17673. // add element to array
  17674. m_value.array->push_back(val);
  17675. }
  17676. /*!
  17677. @brief add an object to an array
  17678. @copydoc push_back(basic_json&&)
  17679. */
  17680. reference operator+=(const basic_json& val)
  17681. {
  17682. push_back(val);
  17683. return *this;
  17684. }
  17685. /*!
  17686. @brief add an object to an object
  17687. Inserts the given element @a val to the JSON object. If the function is
  17688. called on a JSON null value, an empty object is created before inserting
  17689. @a val.
  17690. @param[in] val the value to add to the JSON object
  17691. @throw type_error.308 when called on a type other than JSON object or
  17692. null; example: `"cannot use push_back() with number"`
  17693. @complexity Logarithmic in the size of the container, O(log(`size()`)).
  17694. @liveexample{The example shows how `push_back()` and `+=` can be used to
  17695. add elements to a JSON object. Note how the `null` value was silently
  17696. converted to a JSON object.,push_back__object_t__value}
  17697. @since version 1.0.0
  17698. */
  17699. void push_back(const typename object_t::value_type& val)
  17700. {
  17701. // push_back only works for null objects or objects
  17702. if (JSON_HEDLEY_UNLIKELY(not(is_null() or is_object())))
  17703. {
  17704. JSON_THROW(type_error::create(308, "cannot use push_back() with " + std::string(type_name())));
  17705. }
  17706. // transform null object into an object
  17707. if (is_null())
  17708. {
  17709. m_type = value_t::object;
  17710. m_value = value_t::object;
  17711. assert_invariant();
  17712. }
  17713. // add element to array
  17714. m_value.object->insert(val);
  17715. }
  17716. /*!
  17717. @brief add an object to an object
  17718. @copydoc push_back(const typename object_t::value_type&)
  17719. */
  17720. reference operator+=(const typename object_t::value_type& val)
  17721. {
  17722. push_back(val);
  17723. return *this;
  17724. }
  17725. /*!
  17726. @brief add an object to an object
  17727. This function allows to use `push_back` with an initializer list. In case
  17728. 1. the current value is an object,
  17729. 2. the initializer list @a init contains only two elements, and
  17730. 3. the first element of @a init is a string,
  17731. @a init is converted into an object element and added using
  17732. @ref push_back(const typename object_t::value_type&). Otherwise, @a init
  17733. is converted to a JSON value and added using @ref push_back(basic_json&&).
  17734. @param[in] init an initializer list
  17735. @complexity Linear in the size of the initializer list @a init.
  17736. @note This function is required to resolve an ambiguous overload error,
  17737. because pairs like `{"key", "value"}` can be both interpreted as
  17738. `object_t::value_type` or `std::initializer_list<basic_json>`, see
  17739. https://github.com/nlohmann/json/issues/235 for more information.
  17740. @liveexample{The example shows how initializer lists are treated as
  17741. objects when possible.,push_back__initializer_list}
  17742. */
  17743. void push_back(initializer_list_t init)
  17744. {
  17745. if (is_object() and init.size() == 2 and (*init.begin())->is_string())
  17746. {
  17747. basic_json&& key = init.begin()->moved_or_copied();
  17748. push_back(typename object_t::value_type(
  17749. std::move(key.get_ref<string_t&>()), (init.begin() + 1)->moved_or_copied()));
  17750. }
  17751. else
  17752. {
  17753. push_back(basic_json(init));
  17754. }
  17755. }
  17756. /*!
  17757. @brief add an object to an object
  17758. @copydoc push_back(initializer_list_t)
  17759. */
  17760. reference operator+=(initializer_list_t init)
  17761. {
  17762. push_back(init);
  17763. return *this;
  17764. }
  17765. /*!
  17766. @brief add an object to an array
  17767. Creates a JSON value from the passed parameters @a args to the end of the
  17768. JSON value. If the function is called on a JSON null value, an empty array
  17769. is created before appending the value created from @a args.
  17770. @param[in] args arguments to forward to a constructor of @ref basic_json
  17771. @tparam Args compatible types to create a @ref basic_json object
  17772. @return reference to the inserted element
  17773. @throw type_error.311 when called on a type other than JSON array or
  17774. null; example: `"cannot use emplace_back() with number"`
  17775. @complexity Amortized constant.
  17776. @liveexample{The example shows how `push_back()` can be used to add
  17777. elements to a JSON array. Note how the `null` value was silently converted
  17778. to a JSON array.,emplace_back}
  17779. @since version 2.0.8, returns reference since 3.7.0
  17780. */
  17781. template<class... Args>
  17782. reference emplace_back(Args&& ... args)
  17783. {
  17784. // emplace_back only works for null objects or arrays
  17785. if (JSON_HEDLEY_UNLIKELY(not(is_null() or is_array())))
  17786. {
  17787. JSON_THROW(type_error::create(311, "cannot use emplace_back() with " + std::string(type_name())));
  17788. }
  17789. // transform null object into an array
  17790. if (is_null())
  17791. {
  17792. m_type = value_t::array;
  17793. m_value = value_t::array;
  17794. assert_invariant();
  17795. }
  17796. // add element to array (perfect forwarding)
  17797. #ifdef JSON_HAS_CPP_17
  17798. return m_value.array->emplace_back(std::forward<Args>(args)...);
  17799. #else
  17800. m_value.array->emplace_back(std::forward<Args>(args)...);
  17801. return m_value.array->back();
  17802. #endif
  17803. }
  17804. /*!
  17805. @brief add an object to an object if key does not exist
  17806. Inserts a new element into a JSON object constructed in-place with the
  17807. given @a args if there is no element with the key in the container. If the
  17808. function is called on a JSON null value, an empty object is created before
  17809. appending the value created from @a args.
  17810. @param[in] args arguments to forward to a constructor of @ref basic_json
  17811. @tparam Args compatible types to create a @ref basic_json object
  17812. @return a pair consisting of an iterator to the inserted element, or the
  17813. already-existing element if no insertion happened, and a bool
  17814. denoting whether the insertion took place.
  17815. @throw type_error.311 when called on a type other than JSON object or
  17816. null; example: `"cannot use emplace() with number"`
  17817. @complexity Logarithmic in the size of the container, O(log(`size()`)).
  17818. @liveexample{The example shows how `emplace()` can be used to add elements
  17819. to a JSON object. Note how the `null` value was silently converted to a
  17820. JSON object. Further note how no value is added if there was already one
  17821. value stored with the same key.,emplace}
  17822. @since version 2.0.8
  17823. */
  17824. template<class... Args>
  17825. std::pair<iterator, bool> emplace(Args&& ... args)
  17826. {
  17827. // emplace only works for null objects or arrays
  17828. if (JSON_HEDLEY_UNLIKELY(not(is_null() or is_object())))
  17829. {
  17830. JSON_THROW(type_error::create(311, "cannot use emplace() with " + std::string(type_name())));
  17831. }
  17832. // transform null object into an object
  17833. if (is_null())
  17834. {
  17835. m_type = value_t::object;
  17836. m_value = value_t::object;
  17837. assert_invariant();
  17838. }
  17839. // add element to array (perfect forwarding)
  17840. auto res = m_value.object->emplace(std::forward<Args>(args)...);
  17841. // create result iterator and set iterator to the result of emplace
  17842. auto it = begin();
  17843. it.m_it.object_iterator = res.first;
  17844. // return pair of iterator and boolean
  17845. return {it, res.second};
  17846. }
  17847. /// Helper for insertion of an iterator
  17848. /// @note: This uses std::distance to support GCC 4.8,
  17849. /// see https://github.com/nlohmann/json/pull/1257
  17850. template<typename... Args>
  17851. iterator insert_iterator(const_iterator pos, Args&& ... args)
  17852. {
  17853. iterator result(this);
  17854. assert(m_value.array != nullptr);
  17855. auto insert_pos = std::distance(m_value.array->begin(), pos.m_it.array_iterator);
  17856. m_value.array->insert(pos.m_it.array_iterator, std::forward<Args>(args)...);
  17857. result.m_it.array_iterator = m_value.array->begin() + insert_pos;
  17858. // This could have been written as:
  17859. // result.m_it.array_iterator = m_value.array->insert(pos.m_it.array_iterator, cnt, val);
  17860. // but the return value of insert is missing in GCC 4.8, so it is written this way instead.
  17861. return result;
  17862. }
  17863. /*!
  17864. @brief inserts element
  17865. Inserts element @a val before iterator @a pos.
  17866. @param[in] pos iterator before which the content will be inserted; may be
  17867. the end() iterator
  17868. @param[in] val element to insert
  17869. @return iterator pointing to the inserted @a val.
  17870. @throw type_error.309 if called on JSON values other than arrays;
  17871. example: `"cannot use insert() with string"`
  17872. @throw invalid_iterator.202 if @a pos is not an iterator of *this;
  17873. example: `"iterator does not fit current value"`
  17874. @complexity Constant plus linear in the distance between @a pos and end of
  17875. the container.
  17876. @liveexample{The example shows how `insert()` is used.,insert}
  17877. @since version 1.0.0
  17878. */
  17879. iterator insert(const_iterator pos, const basic_json& val)
  17880. {
  17881. // insert only works for arrays
  17882. if (JSON_HEDLEY_LIKELY(is_array()))
  17883. {
  17884. // check if iterator pos fits to this JSON value
  17885. if (JSON_HEDLEY_UNLIKELY(pos.m_object != this))
  17886. {
  17887. JSON_THROW(invalid_iterator::create(202, "iterator does not fit current value"));
  17888. }
  17889. // insert to array and return iterator
  17890. return insert_iterator(pos, val);
  17891. }
  17892. JSON_THROW(type_error::create(309, "cannot use insert() with " + std::string(type_name())));
  17893. }
  17894. /*!
  17895. @brief inserts element
  17896. @copydoc insert(const_iterator, const basic_json&)
  17897. */
  17898. iterator insert(const_iterator pos, basic_json&& val)
  17899. {
  17900. return insert(pos, val);
  17901. }
  17902. /*!
  17903. @brief inserts elements
  17904. Inserts @a cnt copies of @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] cnt number of copies of @a val to insert
  17908. @param[in] val element to insert
  17909. @return iterator pointing to the first element inserted, or @a pos if
  17910. `cnt==0`
  17911. @throw type_error.309 if called on JSON values other than arrays; example:
  17912. `"cannot use insert() with string"`
  17913. @throw invalid_iterator.202 if @a pos is not an iterator of *this;
  17914. example: `"iterator does not fit current value"`
  17915. @complexity Linear in @a cnt plus linear in the distance between @a pos
  17916. and end of the container.
  17917. @liveexample{The example shows how `insert()` is used.,insert__count}
  17918. @since version 1.0.0
  17919. */
  17920. iterator insert(const_iterator pos, size_type cnt, const basic_json& val)
  17921. {
  17922. // insert only works for arrays
  17923. if (JSON_HEDLEY_LIKELY(is_array()))
  17924. {
  17925. // check if iterator pos fits to this JSON value
  17926. if (JSON_HEDLEY_UNLIKELY(pos.m_object != this))
  17927. {
  17928. JSON_THROW(invalid_iterator::create(202, "iterator does not fit current value"));
  17929. }
  17930. // insert to array and return iterator
  17931. return insert_iterator(pos, cnt, val);
  17932. }
  17933. JSON_THROW(type_error::create(309, "cannot use insert() with " + std::string(type_name())));
  17934. }
  17935. /*!
  17936. @brief inserts elements
  17937. Inserts elements from range `[first, last)` before iterator @a pos.
  17938. @param[in] pos iterator before which the content will be inserted; may be
  17939. the end() iterator
  17940. @param[in] first begin of the range of elements to insert
  17941. @param[in] last end of the range of elements to insert
  17942. @throw type_error.309 if called on JSON values other than arrays; example:
  17943. `"cannot use insert() with string"`
  17944. @throw invalid_iterator.202 if @a pos is not an iterator of *this;
  17945. example: `"iterator does not fit current value"`
  17946. @throw invalid_iterator.210 if @a first and @a last do not belong to the
  17947. same JSON value; example: `"iterators do not fit"`
  17948. @throw invalid_iterator.211 if @a first or @a last are iterators into
  17949. container for which insert is called; example: `"passed iterators may not
  17950. belong to container"`
  17951. @return iterator pointing to the first element inserted, or @a pos if
  17952. `first==last`
  17953. @complexity Linear in `std::distance(first, last)` plus linear in the
  17954. distance between @a pos and end of the container.
  17955. @liveexample{The example shows how `insert()` is used.,insert__range}
  17956. @since version 1.0.0
  17957. */
  17958. iterator insert(const_iterator pos, const_iterator first, const_iterator last)
  17959. {
  17960. // insert only works for arrays
  17961. if (JSON_HEDLEY_UNLIKELY(not is_array()))
  17962. {
  17963. JSON_THROW(type_error::create(309, "cannot use insert() with " + std::string(type_name())));
  17964. }
  17965. // check if iterator pos fits to this JSON value
  17966. if (JSON_HEDLEY_UNLIKELY(pos.m_object != this))
  17967. {
  17968. JSON_THROW(invalid_iterator::create(202, "iterator does not fit current value"));
  17969. }
  17970. // check if range iterators belong to the same JSON object
  17971. if (JSON_HEDLEY_UNLIKELY(first.m_object != last.m_object))
  17972. {
  17973. JSON_THROW(invalid_iterator::create(210, "iterators do not fit"));
  17974. }
  17975. if (JSON_HEDLEY_UNLIKELY(first.m_object == this))
  17976. {
  17977. JSON_THROW(invalid_iterator::create(211, "passed iterators may not belong to container"));
  17978. }
  17979. // insert to array and return iterator
  17980. return insert_iterator(pos, first.m_it.array_iterator, last.m_it.array_iterator);
  17981. }
  17982. /*!
  17983. @brief inserts elements
  17984. Inserts elements from initializer list @a ilist before iterator @a pos.
  17985. @param[in] pos iterator before which the content will be inserted; may be
  17986. the end() iterator
  17987. @param[in] ilist initializer list to insert the values from
  17988. @throw type_error.309 if called on JSON values other than arrays; example:
  17989. `"cannot use insert() with string"`
  17990. @throw invalid_iterator.202 if @a pos is not an iterator of *this;
  17991. example: `"iterator does not fit current value"`
  17992. @return iterator pointing to the first element inserted, or @a pos if
  17993. `ilist` is empty
  17994. @complexity Linear in `ilist.size()` plus linear in the distance between
  17995. @a pos and end of the container.
  17996. @liveexample{The example shows how `insert()` is used.,insert__ilist}
  17997. @since version 1.0.0
  17998. */
  17999. iterator insert(const_iterator pos, initializer_list_t ilist)
  18000. {
  18001. // insert only works for arrays
  18002. if (JSON_HEDLEY_UNLIKELY(not is_array()))
  18003. {
  18004. JSON_THROW(type_error::create(309, "cannot use insert() with " + std::string(type_name())));
  18005. }
  18006. // check if iterator pos fits to this JSON value
  18007. if (JSON_HEDLEY_UNLIKELY(pos.m_object != this))
  18008. {
  18009. JSON_THROW(invalid_iterator::create(202, "iterator does not fit current value"));
  18010. }
  18011. // insert to array and return iterator
  18012. return insert_iterator(pos, ilist.begin(), ilist.end());
  18013. }
  18014. /*!
  18015. @brief inserts elements
  18016. Inserts elements from range `[first, last)`.
  18017. @param[in] first begin of the range of elements to insert
  18018. @param[in] last end of the range of elements to insert
  18019. @throw type_error.309 if called on JSON values other than objects; example:
  18020. `"cannot use insert() with string"`
  18021. @throw invalid_iterator.202 if iterator @a first or @a last does does not
  18022. point to an object; example: `"iterators first and last must point to
  18023. objects"`
  18024. @throw invalid_iterator.210 if @a first and @a last do not belong to the
  18025. same JSON value; example: `"iterators do not fit"`
  18026. @complexity Logarithmic: `O(N*log(size() + N))`, where `N` is the number
  18027. of elements to insert.
  18028. @liveexample{The example shows how `insert()` is used.,insert__range_object}
  18029. @since version 3.0.0
  18030. */
  18031. void insert(const_iterator first, const_iterator last)
  18032. {
  18033. // insert only works for objects
  18034. if (JSON_HEDLEY_UNLIKELY(not is_object()))
  18035. {
  18036. JSON_THROW(type_error::create(309, "cannot use insert() with " + std::string(type_name())));
  18037. }
  18038. // check if range iterators belong to the same JSON object
  18039. if (JSON_HEDLEY_UNLIKELY(first.m_object != last.m_object))
  18040. {
  18041. JSON_THROW(invalid_iterator::create(210, "iterators do not fit"));
  18042. }
  18043. // passed iterators must belong to objects
  18044. if (JSON_HEDLEY_UNLIKELY(not first.m_object->is_object()))
  18045. {
  18046. JSON_THROW(invalid_iterator::create(202, "iterators first and last must point to objects"));
  18047. }
  18048. m_value.object->insert(first.m_it.object_iterator, last.m_it.object_iterator);
  18049. }
  18050. /*!
  18051. @brief updates a JSON object from another object, overwriting existing keys
  18052. Inserts all values from JSON object @a j and overwrites existing keys.
  18053. @param[in] j JSON object to read values from
  18054. @throw type_error.312 if called on JSON values other than objects; example:
  18055. `"cannot use update() with string"`
  18056. @complexity O(N*log(size() + N)), where N is the number of elements to
  18057. insert.
  18058. @liveexample{The example shows how `update()` is used.,update}
  18059. @sa https://docs.python.org/3.6/library/stdtypes.html#dict.update
  18060. @since version 3.0.0
  18061. */
  18062. void update(const_reference j)
  18063. {
  18064. // implicitly convert null value to an empty object
  18065. if (is_null())
  18066. {
  18067. m_type = value_t::object;
  18068. m_value.object = create<object_t>();
  18069. assert_invariant();
  18070. }
  18071. if (JSON_HEDLEY_UNLIKELY(not is_object()))
  18072. {
  18073. JSON_THROW(type_error::create(312, "cannot use update() with " + std::string(type_name())));
  18074. }
  18075. if (JSON_HEDLEY_UNLIKELY(not j.is_object()))
  18076. {
  18077. JSON_THROW(type_error::create(312, "cannot use update() with " + std::string(j.type_name())));
  18078. }
  18079. for (auto it = j.cbegin(); it != j.cend(); ++it)
  18080. {
  18081. m_value.object->operator[](it.key()) = it.value();
  18082. }
  18083. }
  18084. /*!
  18085. @brief updates a JSON object from another object, overwriting existing keys
  18086. Inserts all values from from range `[first, last)` and overwrites existing
  18087. keys.
  18088. @param[in] first begin of the range of elements to insert
  18089. @param[in] last end of the range of elements to insert
  18090. @throw type_error.312 if called on JSON values other than objects; example:
  18091. `"cannot use update() with string"`
  18092. @throw invalid_iterator.202 if iterator @a first or @a last does does not
  18093. point to an object; example: `"iterators first and last must point to
  18094. objects"`
  18095. @throw invalid_iterator.210 if @a first and @a last do not belong to the
  18096. same JSON value; example: `"iterators do not fit"`
  18097. @complexity O(N*log(size() + N)), where N is the number of elements to
  18098. insert.
  18099. @liveexample{The example shows how `update()` is used__range.,update}
  18100. @sa https://docs.python.org/3.6/library/stdtypes.html#dict.update
  18101. @since version 3.0.0
  18102. */
  18103. void update(const_iterator first, const_iterator last)
  18104. {
  18105. // implicitly convert null value to an empty object
  18106. if (is_null())
  18107. {
  18108. m_type = value_t::object;
  18109. m_value.object = create<object_t>();
  18110. assert_invariant();
  18111. }
  18112. if (JSON_HEDLEY_UNLIKELY(not is_object()))
  18113. {
  18114. JSON_THROW(type_error::create(312, "cannot use update() with " + std::string(type_name())));
  18115. }
  18116. // check if range iterators belong to the same JSON object
  18117. if (JSON_HEDLEY_UNLIKELY(first.m_object != last.m_object))
  18118. {
  18119. JSON_THROW(invalid_iterator::create(210, "iterators do not fit"));
  18120. }
  18121. // passed iterators must belong to objects
  18122. if (JSON_HEDLEY_UNLIKELY(not first.m_object->is_object()
  18123. or not last.m_object->is_object()))
  18124. {
  18125. JSON_THROW(invalid_iterator::create(202, "iterators first and last must point to objects"));
  18126. }
  18127. for (auto it = first; it != last; ++it)
  18128. {
  18129. m_value.object->operator[](it.key()) = it.value();
  18130. }
  18131. }
  18132. /*!
  18133. @brief exchanges the values
  18134. Exchanges the contents of the JSON value with those of @a other. Does not
  18135. invoke any move, copy, or swap operations on individual elements. All
  18136. iterators and references remain valid. The past-the-end iterator is
  18137. invalidated.
  18138. @param[in,out] other JSON value to exchange the contents with
  18139. @complexity Constant.
  18140. @liveexample{The example below shows how JSON values can be swapped with
  18141. `swap()`.,swap__reference}
  18142. @since version 1.0.0
  18143. */
  18144. void swap(reference other) noexcept (
  18145. std::is_nothrow_move_constructible<value_t>::value and
  18146. std::is_nothrow_move_assignable<value_t>::value and
  18147. std::is_nothrow_move_constructible<json_value>::value and
  18148. std::is_nothrow_move_assignable<json_value>::value
  18149. )
  18150. {
  18151. std::swap(m_type, other.m_type);
  18152. std::swap(m_value, other.m_value);
  18153. assert_invariant();
  18154. }
  18155. /*!
  18156. @brief exchanges the values
  18157. Exchanges the contents of a JSON array with those of @a other. Does not
  18158. invoke any move, copy, or swap operations on individual elements. All
  18159. iterators and references remain valid. The past-the-end iterator is
  18160. invalidated.
  18161. @param[in,out] other array to exchange the contents with
  18162. @throw type_error.310 when JSON value is not an array; example: `"cannot
  18163. use swap() with string"`
  18164. @complexity Constant.
  18165. @liveexample{The example below shows how arrays can be swapped with
  18166. `swap()`.,swap__array_t}
  18167. @since version 1.0.0
  18168. */
  18169. void swap(array_t& other)
  18170. {
  18171. // swap only works for arrays
  18172. if (JSON_HEDLEY_LIKELY(is_array()))
  18173. {
  18174. std::swap(*(m_value.array), other);
  18175. }
  18176. else
  18177. {
  18178. JSON_THROW(type_error::create(310, "cannot use swap() with " + std::string(type_name())));
  18179. }
  18180. }
  18181. /*!
  18182. @brief exchanges the values
  18183. Exchanges the contents of a JSON object with those of @a other. Does not
  18184. invoke any move, copy, or swap operations on individual elements. All
  18185. iterators and references remain valid. The past-the-end iterator is
  18186. invalidated.
  18187. @param[in,out] other object to exchange the contents with
  18188. @throw type_error.310 when JSON value is not an object; example:
  18189. `"cannot use swap() with string"`
  18190. @complexity Constant.
  18191. @liveexample{The example below shows how objects can be swapped with
  18192. `swap()`.,swap__object_t}
  18193. @since version 1.0.0
  18194. */
  18195. void swap(object_t& other)
  18196. {
  18197. // swap only works for objects
  18198. if (JSON_HEDLEY_LIKELY(is_object()))
  18199. {
  18200. std::swap(*(m_value.object), other);
  18201. }
  18202. else
  18203. {
  18204. JSON_THROW(type_error::create(310, "cannot use swap() with " + std::string(type_name())));
  18205. }
  18206. }
  18207. /*!
  18208. @brief exchanges the values
  18209. Exchanges the contents of a JSON string with those of @a other. Does not
  18210. invoke any move, copy, or swap operations on individual elements. All
  18211. iterators and references remain valid. The past-the-end iterator is
  18212. invalidated.
  18213. @param[in,out] other string to exchange the contents with
  18214. @throw type_error.310 when JSON value is not a string; example: `"cannot
  18215. use swap() with boolean"`
  18216. @complexity Constant.
  18217. @liveexample{The example below shows how strings can be swapped with
  18218. `swap()`.,swap__string_t}
  18219. @since version 1.0.0
  18220. */
  18221. void swap(string_t& other)
  18222. {
  18223. // swap only works for strings
  18224. if (JSON_HEDLEY_LIKELY(is_string()))
  18225. {
  18226. std::swap(*(m_value.string), other);
  18227. }
  18228. else
  18229. {
  18230. JSON_THROW(type_error::create(310, "cannot use swap() with " + std::string(type_name())));
  18231. }
  18232. }
  18233. /// @}
  18234. public:
  18235. //////////////////////////////////////////
  18236. // lexicographical comparison operators //
  18237. //////////////////////////////////////////
  18238. /// @name lexicographical comparison operators
  18239. /// @{
  18240. /*!
  18241. @brief comparison: equal
  18242. Compares two JSON values for equality according to the following rules:
  18243. - Two JSON values are equal if (1) they are from the same type and (2)
  18244. their stored values are the same according to their respective
  18245. `operator==`.
  18246. - Integer and floating-point numbers are automatically converted before
  18247. comparison. Note that two NaN values are always treated as unequal.
  18248. - Two JSON null values are equal.
  18249. @note Floating-point inside JSON values numbers are compared with
  18250. `json::number_float_t::operator==` which is `double::operator==` by
  18251. default. To compare floating-point while respecting an epsilon, an alternative
  18252. [comparison function](https://github.com/mariokonrad/marnav/blob/master/include/marnav/math/floatingpoint.hpp#L34-#L39)
  18253. could be used, for instance
  18254. @code {.cpp}
  18255. template<typename T, typename = typename std::enable_if<std::is_floating_point<T>::value, T>::type>
  18256. inline bool is_same(T a, T b, T epsilon = std::numeric_limits<T>::epsilon()) noexcept
  18257. {
  18258. return std::abs(a - b) <= epsilon;
  18259. }
  18260. @endcode
  18261. Or you can self-defined operator equal function like this:
  18262. @code {.cpp}
  18263. bool my_equal(const_reference lhs, const_reference rhs) {
  18264. const auto lhs_type lhs.type();
  18265. const auto rhs_type rhs.type();
  18266. if (lhs_type == rhs_type) {
  18267. switch(lhs_type)
  18268. // self_defined case
  18269. case value_t::number_float:
  18270. return std::abs(lhs - rhs) <= std::numeric_limits<float>::epsilon();
  18271. // other cases remain the same with the original
  18272. ...
  18273. }
  18274. ...
  18275. }
  18276. @endcode
  18277. @note NaN values never compare equal to themselves or to other NaN values.
  18278. @param[in] lhs first JSON value to consider
  18279. @param[in] rhs second JSON value to consider
  18280. @return whether the values @a lhs and @a rhs are equal
  18281. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  18282. @complexity Linear.
  18283. @liveexample{The example demonstrates comparing several JSON
  18284. types.,operator__equal}
  18285. @since version 1.0.0
  18286. */
  18287. friend bool operator==(const_reference lhs, const_reference rhs) noexcept
  18288. {
  18289. const auto lhs_type = lhs.type();
  18290. const auto rhs_type = rhs.type();
  18291. if (lhs_type == rhs_type)
  18292. {
  18293. switch (lhs_type)
  18294. {
  18295. case value_t::array:
  18296. return *lhs.m_value.array == *rhs.m_value.array;
  18297. case value_t::object:
  18298. return *lhs.m_value.object == *rhs.m_value.object;
  18299. case value_t::null:
  18300. return true;
  18301. case value_t::string:
  18302. return *lhs.m_value.string == *rhs.m_value.string;
  18303. case value_t::boolean:
  18304. return lhs.m_value.boolean == rhs.m_value.boolean;
  18305. case value_t::number_integer:
  18306. return lhs.m_value.number_integer == rhs.m_value.number_integer;
  18307. case value_t::number_unsigned:
  18308. return lhs.m_value.number_unsigned == rhs.m_value.number_unsigned;
  18309. case value_t::number_float:
  18310. return lhs.m_value.number_float == rhs.m_value.number_float;
  18311. case value_t::binary:
  18312. return *lhs.m_value.binary == *rhs.m_value.binary;
  18313. default:
  18314. return false;
  18315. }
  18316. }
  18317. else if (lhs_type == value_t::number_integer and rhs_type == value_t::number_float)
  18318. {
  18319. return static_cast<number_float_t>(lhs.m_value.number_integer) == rhs.m_value.number_float;
  18320. }
  18321. else if (lhs_type == value_t::number_float and rhs_type == value_t::number_integer)
  18322. {
  18323. return lhs.m_value.number_float == static_cast<number_float_t>(rhs.m_value.number_integer);
  18324. }
  18325. else if (lhs_type == value_t::number_unsigned and rhs_type == value_t::number_float)
  18326. {
  18327. return static_cast<number_float_t>(lhs.m_value.number_unsigned) == rhs.m_value.number_float;
  18328. }
  18329. else if (lhs_type == value_t::number_float and rhs_type == value_t::number_unsigned)
  18330. {
  18331. return lhs.m_value.number_float == static_cast<number_float_t>(rhs.m_value.number_unsigned);
  18332. }
  18333. else if (lhs_type == value_t::number_unsigned and rhs_type == value_t::number_integer)
  18334. {
  18335. return static_cast<number_integer_t>(lhs.m_value.number_unsigned) == rhs.m_value.number_integer;
  18336. }
  18337. else if (lhs_type == value_t::number_integer and rhs_type == value_t::number_unsigned)
  18338. {
  18339. return lhs.m_value.number_integer == static_cast<number_integer_t>(rhs.m_value.number_unsigned);
  18340. }
  18341. return false;
  18342. }
  18343. /*!
  18344. @brief comparison: equal
  18345. @copydoc operator==(const_reference, const_reference)
  18346. */
  18347. template<typename ScalarType, typename std::enable_if<
  18348. std::is_scalar<ScalarType>::value, int>::type = 0>
  18349. friend bool operator==(const_reference lhs, const ScalarType rhs) noexcept
  18350. {
  18351. return lhs == basic_json(rhs);
  18352. }
  18353. /*!
  18354. @brief comparison: equal
  18355. @copydoc operator==(const_reference, const_reference)
  18356. */
  18357. template<typename ScalarType, typename std::enable_if<
  18358. std::is_scalar<ScalarType>::value, int>::type = 0>
  18359. friend bool operator==(const ScalarType lhs, const_reference rhs) noexcept
  18360. {
  18361. return basic_json(lhs) == rhs;
  18362. }
  18363. /*!
  18364. @brief comparison: not equal
  18365. Compares two JSON values for inequality by calculating `not (lhs == rhs)`.
  18366. @param[in] lhs first JSON value to consider
  18367. @param[in] rhs second JSON value to consider
  18368. @return whether the values @a lhs and @a rhs are not equal
  18369. @complexity Linear.
  18370. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  18371. @liveexample{The example demonstrates comparing several JSON
  18372. types.,operator__notequal}
  18373. @since version 1.0.0
  18374. */
  18375. friend bool operator!=(const_reference lhs, const_reference rhs) noexcept
  18376. {
  18377. return not (lhs == rhs);
  18378. }
  18379. /*!
  18380. @brief comparison: not equal
  18381. @copydoc operator!=(const_reference, const_reference)
  18382. */
  18383. template<typename ScalarType, typename std::enable_if<
  18384. std::is_scalar<ScalarType>::value, int>::type = 0>
  18385. friend bool operator!=(const_reference lhs, const ScalarType rhs) noexcept
  18386. {
  18387. return lhs != basic_json(rhs);
  18388. }
  18389. /*!
  18390. @brief comparison: not equal
  18391. @copydoc operator!=(const_reference, const_reference)
  18392. */
  18393. template<typename ScalarType, typename std::enable_if<
  18394. std::is_scalar<ScalarType>::value, int>::type = 0>
  18395. friend bool operator!=(const ScalarType lhs, const_reference rhs) noexcept
  18396. {
  18397. return basic_json(lhs) != rhs;
  18398. }
  18399. /*!
  18400. @brief comparison: less than
  18401. Compares whether one JSON value @a lhs is less than another JSON value @a
  18402. rhs according to the following rules:
  18403. - If @a lhs and @a rhs have the same type, the values are compared using
  18404. the default `<` operator.
  18405. - Integer and floating-point numbers are automatically converted before
  18406. comparison
  18407. - In case @a lhs and @a rhs have different types, the values are ignored
  18408. and the order of the types is considered, see
  18409. @ref operator<(const value_t, const value_t).
  18410. @param[in] lhs first JSON value to consider
  18411. @param[in] rhs second JSON value to consider
  18412. @return whether @a lhs is less than @a rhs
  18413. @complexity Linear.
  18414. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  18415. @liveexample{The example demonstrates comparing several JSON
  18416. types.,operator__less}
  18417. @since version 1.0.0
  18418. */
  18419. friend bool operator<(const_reference lhs, const_reference rhs) noexcept
  18420. {
  18421. const auto lhs_type = lhs.type();
  18422. const auto rhs_type = rhs.type();
  18423. if (lhs_type == rhs_type)
  18424. {
  18425. switch (lhs_type)
  18426. {
  18427. case value_t::array:
  18428. // note parentheses are necessary, see
  18429. // https://github.com/nlohmann/json/issues/1530
  18430. return (*lhs.m_value.array) < (*rhs.m_value.array);
  18431. case value_t::object:
  18432. return (*lhs.m_value.object) < (*rhs.m_value.object);
  18433. case value_t::null:
  18434. return false;
  18435. case value_t::string:
  18436. return (*lhs.m_value.string) < (*rhs.m_value.string);
  18437. case value_t::boolean:
  18438. return (lhs.m_value.boolean) < (rhs.m_value.boolean);
  18439. case value_t::number_integer:
  18440. return (lhs.m_value.number_integer) < (rhs.m_value.number_integer);
  18441. case value_t::number_unsigned:
  18442. return (lhs.m_value.number_unsigned) < (rhs.m_value.number_unsigned);
  18443. case value_t::number_float:
  18444. return (lhs.m_value.number_float) < (rhs.m_value.number_float);
  18445. case value_t::binary:
  18446. return (lhs.m_value.binary) < (rhs.m_value.binary);
  18447. default:
  18448. return false;
  18449. }
  18450. }
  18451. else if (lhs_type == value_t::number_integer and rhs_type == value_t::number_float)
  18452. {
  18453. return static_cast<number_float_t>(lhs.m_value.number_integer) < rhs.m_value.number_float;
  18454. }
  18455. else if (lhs_type == value_t::number_float and rhs_type == value_t::number_integer)
  18456. {
  18457. return lhs.m_value.number_float < static_cast<number_float_t>(rhs.m_value.number_integer);
  18458. }
  18459. else if (lhs_type == value_t::number_unsigned and rhs_type == value_t::number_float)
  18460. {
  18461. return static_cast<number_float_t>(lhs.m_value.number_unsigned) < rhs.m_value.number_float;
  18462. }
  18463. else if (lhs_type == value_t::number_float and rhs_type == value_t::number_unsigned)
  18464. {
  18465. return lhs.m_value.number_float < static_cast<number_float_t>(rhs.m_value.number_unsigned);
  18466. }
  18467. else if (lhs_type == value_t::number_integer and rhs_type == value_t::number_unsigned)
  18468. {
  18469. return lhs.m_value.number_integer < static_cast<number_integer_t>(rhs.m_value.number_unsigned);
  18470. }
  18471. else if (lhs_type == value_t::number_unsigned and rhs_type == value_t::number_integer)
  18472. {
  18473. return static_cast<number_integer_t>(lhs.m_value.number_unsigned) < rhs.m_value.number_integer;
  18474. }
  18475. // We only reach this line if we cannot compare values. In that case,
  18476. // we compare types. Note we have to call the operator explicitly,
  18477. // because MSVC has problems otherwise.
  18478. return operator<(lhs_type, rhs_type);
  18479. }
  18480. /*!
  18481. @brief comparison: less than
  18482. @copydoc operator<(const_reference, const_reference)
  18483. */
  18484. template<typename ScalarType, typename std::enable_if<
  18485. std::is_scalar<ScalarType>::value, int>::type = 0>
  18486. friend bool operator<(const_reference lhs, const ScalarType rhs) noexcept
  18487. {
  18488. return lhs < basic_json(rhs);
  18489. }
  18490. /*!
  18491. @brief comparison: less than
  18492. @copydoc operator<(const_reference, const_reference)
  18493. */
  18494. template<typename ScalarType, typename std::enable_if<
  18495. std::is_scalar<ScalarType>::value, int>::type = 0>
  18496. friend bool operator<(const ScalarType lhs, const_reference rhs) noexcept
  18497. {
  18498. return basic_json(lhs) < rhs;
  18499. }
  18500. /*!
  18501. @brief comparison: less than or equal
  18502. Compares whether one JSON value @a lhs is less than or equal to another
  18503. JSON value by calculating `not (rhs < lhs)`.
  18504. @param[in] lhs first JSON value to consider
  18505. @param[in] rhs second JSON value to consider
  18506. @return whether @a lhs is less than or equal to @a rhs
  18507. @complexity Linear.
  18508. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  18509. @liveexample{The example demonstrates comparing several JSON
  18510. types.,operator__greater}
  18511. @since version 1.0.0
  18512. */
  18513. friend bool operator<=(const_reference lhs, const_reference rhs) noexcept
  18514. {
  18515. return not (rhs < lhs);
  18516. }
  18517. /*!
  18518. @brief comparison: less than or equal
  18519. @copydoc operator<=(const_reference, const_reference)
  18520. */
  18521. template<typename ScalarType, typename std::enable_if<
  18522. std::is_scalar<ScalarType>::value, int>::type = 0>
  18523. friend bool operator<=(const_reference lhs, const ScalarType rhs) noexcept
  18524. {
  18525. return lhs <= basic_json(rhs);
  18526. }
  18527. /*!
  18528. @brief comparison: less than or equal
  18529. @copydoc operator<=(const_reference, const_reference)
  18530. */
  18531. template<typename ScalarType, typename std::enable_if<
  18532. std::is_scalar<ScalarType>::value, int>::type = 0>
  18533. friend bool operator<=(const ScalarType lhs, const_reference rhs) noexcept
  18534. {
  18535. return basic_json(lhs) <= rhs;
  18536. }
  18537. /*!
  18538. @brief comparison: greater than
  18539. Compares whether one JSON value @a lhs is greater than another
  18540. JSON value by calculating `not (lhs <= rhs)`.
  18541. @param[in] lhs first JSON value to consider
  18542. @param[in] rhs second JSON value to consider
  18543. @return whether @a lhs is greater than to @a rhs
  18544. @complexity Linear.
  18545. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  18546. @liveexample{The example demonstrates comparing several JSON
  18547. types.,operator__lessequal}
  18548. @since version 1.0.0
  18549. */
  18550. friend bool operator>(const_reference lhs, const_reference rhs) noexcept
  18551. {
  18552. return not (lhs <= rhs);
  18553. }
  18554. /*!
  18555. @brief comparison: greater than
  18556. @copydoc operator>(const_reference, const_reference)
  18557. */
  18558. template<typename ScalarType, typename std::enable_if<
  18559. std::is_scalar<ScalarType>::value, int>::type = 0>
  18560. friend bool operator>(const_reference lhs, const ScalarType rhs) noexcept
  18561. {
  18562. return lhs > basic_json(rhs);
  18563. }
  18564. /*!
  18565. @brief comparison: greater than
  18566. @copydoc operator>(const_reference, const_reference)
  18567. */
  18568. template<typename ScalarType, typename std::enable_if<
  18569. std::is_scalar<ScalarType>::value, int>::type = 0>
  18570. friend bool operator>(const ScalarType lhs, const_reference rhs) noexcept
  18571. {
  18572. return basic_json(lhs) > rhs;
  18573. }
  18574. /*!
  18575. @brief comparison: greater than or equal
  18576. Compares whether one JSON value @a lhs is greater than or equal to another
  18577. JSON value by calculating `not (lhs < rhs)`.
  18578. @param[in] lhs first JSON value to consider
  18579. @param[in] rhs second JSON value to consider
  18580. @return whether @a lhs is greater than or equal to @a rhs
  18581. @complexity Linear.
  18582. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  18583. @liveexample{The example demonstrates comparing several JSON
  18584. types.,operator__greaterequal}
  18585. @since version 1.0.0
  18586. */
  18587. friend bool operator>=(const_reference lhs, const_reference rhs) noexcept
  18588. {
  18589. return not (lhs < rhs);
  18590. }
  18591. /*!
  18592. @brief comparison: greater than or equal
  18593. @copydoc operator>=(const_reference, const_reference)
  18594. */
  18595. template<typename ScalarType, typename std::enable_if<
  18596. std::is_scalar<ScalarType>::value, int>::type = 0>
  18597. friend bool operator>=(const_reference lhs, const ScalarType rhs) noexcept
  18598. {
  18599. return lhs >= basic_json(rhs);
  18600. }
  18601. /*!
  18602. @brief comparison: greater than or equal
  18603. @copydoc operator>=(const_reference, const_reference)
  18604. */
  18605. template<typename ScalarType, typename std::enable_if<
  18606. std::is_scalar<ScalarType>::value, int>::type = 0>
  18607. friend bool operator>=(const ScalarType lhs, const_reference rhs) noexcept
  18608. {
  18609. return basic_json(lhs) >= rhs;
  18610. }
  18611. /// @}
  18612. ///////////////////
  18613. // serialization //
  18614. ///////////////////
  18615. /// @name serialization
  18616. /// @{
  18617. /*!
  18618. @brief serialize to stream
  18619. Serialize the given JSON value @a j to the output stream @a o. The JSON
  18620. value will be serialized using the @ref dump member function.
  18621. - The indentation of the output can be controlled with the member variable
  18622. `width` of the output stream @a o. For instance, using the manipulator
  18623. `std::setw(4)` on @a o sets the indentation level to `4` and the
  18624. serialization result is the same as calling `dump(4)`.
  18625. - The indentation character can be controlled with the member variable
  18626. `fill` of the output stream @a o. For instance, the manipulator
  18627. `std::setfill('\\t')` sets indentation to use a tab character rather than
  18628. the default space character.
  18629. @param[in,out] o stream to serialize to
  18630. @param[in] j JSON value to serialize
  18631. @return the stream @a o
  18632. @throw type_error.316 if a string stored inside the JSON value is not
  18633. UTF-8 encoded
  18634. @complexity Linear.
  18635. @liveexample{The example below shows the serialization with different
  18636. parameters to `width` to adjust the indentation level.,operator_serialize}
  18637. @since version 1.0.0; indentation character added in version 3.0.0
  18638. */
  18639. friend std::ostream& operator<<(std::ostream& o, const basic_json& j)
  18640. {
  18641. // read width member and use it as indentation parameter if nonzero
  18642. const bool pretty_print = o.width() > 0;
  18643. const auto indentation = pretty_print ? o.width() : 0;
  18644. // reset width to 0 for subsequent calls to this stream
  18645. o.width(0);
  18646. // do the actual serialization
  18647. serializer s(detail::output_adapter<char>(o), o.fill());
  18648. s.dump(j, pretty_print, false, static_cast<unsigned int>(indentation));
  18649. return o;
  18650. }
  18651. /*!
  18652. @brief serialize to stream
  18653. @deprecated This stream operator is deprecated and will be removed in
  18654. future 4.0.0 of the library. Please use
  18655. @ref operator<<(std::ostream&, const basic_json&)
  18656. instead; that is, replace calls like `j >> o;` with `o << j;`.
  18657. @since version 1.0.0; deprecated since version 3.0.0
  18658. */
  18659. JSON_HEDLEY_DEPRECATED(3.0.0)
  18660. friend std::ostream& operator>>(const basic_json& j, std::ostream& o)
  18661. {
  18662. return o << j;
  18663. }
  18664. /// @}
  18665. /////////////////////
  18666. // deserialization //
  18667. /////////////////////
  18668. /// @name deserialization
  18669. /// @{
  18670. /*!
  18671. @brief deserialize from a compatible input
  18672. This function reads from a compatible input. Examples are:
  18673. - an array of 1-byte values
  18674. - strings with character/literal type with size of 1 byte
  18675. - input streams
  18676. - container with contiguous storage of 1-byte values. Compatible container
  18677. types include `std::vector`, `std::string`, `std::array`,
  18678. `std::valarray`, and `std::initializer_list`. Furthermore, C-style
  18679. arrays can be used with `std::begin()`/`std::end()`. User-defined
  18680. containers can be used as long as they implement random-access iterators
  18681. and a contiguous storage.
  18682. @pre Each element of the container has a size of 1 byte. Violating this
  18683. precondition yields undefined behavior. **This precondition is enforced
  18684. with a static assertion.**
  18685. @pre The container storage is contiguous. Violating this precondition
  18686. yields undefined behavior. **This precondition is enforced with an
  18687. assertion.**
  18688. @warning There is no way to enforce all preconditions at compile-time. If
  18689. the function is called with a noncompliant container and with
  18690. assertions switched off, the behavior is undefined and will most
  18691. likely yield segmentation violation.
  18692. @param[in] i input to read from
  18693. @param[in] cb a parser callback function of type @ref parser_callback_t
  18694. which is used to control the deserialization by filtering unwanted values
  18695. (optional)
  18696. @param[in] allow_exceptions whether to throw exceptions in case of a
  18697. parse error (optional, true by default)
  18698. @return deserialized JSON value; in case of a parse error and
  18699. @a allow_exceptions set to `false`, the return value will be
  18700. value_t::discarded.
  18701. @throw parse_error.101 if a parse error occurs; example: `""unexpected end
  18702. of input; expected string literal""`
  18703. @throw parse_error.102 if to_unicode fails or surrogate error
  18704. @throw parse_error.103 if to_unicode fails
  18705. @complexity Linear in the length of the input. The parser is a predictive
  18706. LL(1) parser. The complexity can be higher if the parser callback function
  18707. @a cb has a super-linear complexity.
  18708. @note A UTF-8 byte order mark is silently ignored.
  18709. @liveexample{The example below demonstrates the `parse()` function reading
  18710. from an array.,parse__array__parser_callback_t}
  18711. @liveexample{The example below demonstrates the `parse()` function with
  18712. and without callback function.,parse__string__parser_callback_t}
  18713. @liveexample{The example below demonstrates the `parse()` function with
  18714. and without callback function.,parse__istream__parser_callback_t}
  18715. @liveexample{The example below demonstrates the `parse()` function reading
  18716. from a contiguous container.,parse__contiguouscontainer__parser_callback_t}
  18717. @since version 2.0.3 (contiguous containers)
  18718. */
  18719. JSON_HEDLEY_WARN_UNUSED_RESULT
  18720. static basic_json parse(detail::input_adapter&& i,
  18721. const parser_callback_t cb = nullptr,
  18722. const bool allow_exceptions = true)
  18723. {
  18724. basic_json result;
  18725. parser(i, cb, allow_exceptions).parse(true, result);
  18726. return result;
  18727. }
  18728. static bool accept(detail::input_adapter&& i)
  18729. {
  18730. return parser(i).accept(true);
  18731. }
  18732. /*!
  18733. @brief generate SAX events
  18734. The SAX event lister must follow the interface of @ref json_sax.
  18735. This function reads from a compatible input. Examples are:
  18736. - an array of 1-byte values
  18737. - strings with character/literal type with size of 1 byte
  18738. - input streams
  18739. - container with contiguous storage of 1-byte values. Compatible container
  18740. types include `std::vector`, `std::string`, `std::array`,
  18741. `std::valarray`, and `std::initializer_list`. Furthermore, C-style
  18742. arrays can be used with `std::begin()`/`std::end()`. User-defined
  18743. containers can be used as long as they implement random-access iterators
  18744. and a contiguous storage.
  18745. @pre Each element of the container has a size of 1 byte. Violating this
  18746. precondition yields undefined behavior. **This precondition is enforced
  18747. with a static assertion.**
  18748. @pre The container storage is contiguous. Violating this precondition
  18749. yields undefined behavior. **This precondition is enforced with an
  18750. assertion.**
  18751. @warning There is no way to enforce all preconditions at compile-time. If
  18752. the function is called with a noncompliant container and with
  18753. assertions switched off, the behavior is undefined and will most
  18754. likely yield segmentation violation.
  18755. @param[in] i input to read from
  18756. @param[in,out] sax SAX event listener
  18757. @param[in] format the format to parse (JSON, CBOR, MessagePack, or UBJSON)
  18758. @param[in] strict whether the input has to be consumed completely
  18759. @return return value of the last processed SAX event
  18760. @throw parse_error.101 if a parse error occurs; example: `""unexpected end
  18761. of input; expected string literal""`
  18762. @throw parse_error.102 if to_unicode fails or surrogate error
  18763. @throw parse_error.103 if to_unicode fails
  18764. @complexity Linear in the length of the input. The parser is a predictive
  18765. LL(1) parser. The complexity can be higher if the SAX consumer @a sax has
  18766. a super-linear complexity.
  18767. @note A UTF-8 byte order mark is silently ignored.
  18768. @liveexample{The example below demonstrates the `sax_parse()` function
  18769. reading from string and processing the events with a user-defined SAX
  18770. event consumer.,sax_parse}
  18771. @since version 3.2.0
  18772. */
  18773. template <typename SAX>
  18774. JSON_HEDLEY_NON_NULL(2)
  18775. static bool sax_parse(detail::input_adapter&& i, SAX* sax,
  18776. input_format_t format = input_format_t::json,
  18777. const bool strict = true)
  18778. {
  18779. return format == input_format_t::json
  18780. ? parser(std::move(i)).sax_parse(sax, strict)
  18781. : detail::binary_reader<basic_json, SAX>(std::move(i)).sax_parse(format, sax, strict);
  18782. }
  18783. /*!
  18784. @brief deserialize from an iterator range with contiguous storage
  18785. This function reads from an iterator range of a container with contiguous
  18786. storage of 1-byte values. Compatible container types include
  18787. `std::vector`, `std::string`, `std::array`, `std::valarray`, and
  18788. `std::initializer_list`. Furthermore, C-style arrays can be used with
  18789. `std::begin()`/`std::end()`. User-defined containers can be used as long
  18790. as they implement random-access iterators and a contiguous storage.
  18791. @pre The iterator range is contiguous. Violating this precondition yields
  18792. undefined behavior. **This precondition is enforced with an assertion.**
  18793. @pre Each element in the range has a size of 1 byte. Violating this
  18794. precondition yields undefined behavior. **This precondition is enforced
  18795. with a static assertion.**
  18796. @warning There is no way to enforce all preconditions at compile-time. If
  18797. the function is called with noncompliant iterators and with
  18798. assertions switched off, the behavior is undefined and will most
  18799. likely yield segmentation violation.
  18800. @tparam IteratorType iterator of container with contiguous storage
  18801. @param[in] first begin of the range to parse (included)
  18802. @param[in] last end of the range to parse (excluded)
  18803. @param[in] cb a parser callback function of type @ref parser_callback_t
  18804. which is used to control the deserialization by filtering unwanted values
  18805. (optional)
  18806. @param[in] allow_exceptions whether to throw exceptions in case of a
  18807. parse error (optional, true by default)
  18808. @return deserialized JSON value; in case of a parse error and
  18809. @a allow_exceptions set to `false`, the return value will be
  18810. value_t::discarded.
  18811. @throw parse_error.101 in case of an unexpected token
  18812. @throw parse_error.102 if to_unicode fails or surrogate error
  18813. @throw parse_error.103 if to_unicode fails
  18814. @complexity Linear in the length of the input. The parser is a predictive
  18815. LL(1) parser. The complexity can be higher if the parser callback function
  18816. @a cb has a super-linear complexity.
  18817. @note A UTF-8 byte order mark is silently ignored.
  18818. @liveexample{The example below demonstrates the `parse()` function reading
  18819. from an iterator range.,parse__iteratortype__parser_callback_t}
  18820. @since version 2.0.3
  18821. */
  18822. template<class IteratorType, typename std::enable_if<
  18823. std::is_base_of<
  18824. std::random_access_iterator_tag,
  18825. typename std::iterator_traits<IteratorType>::iterator_category>::value, int>::type = 0>
  18826. static basic_json parse(IteratorType first, IteratorType last,
  18827. const parser_callback_t cb = nullptr,
  18828. const bool allow_exceptions = true)
  18829. {
  18830. basic_json result;
  18831. parser(detail::input_adapter(first, last), cb, allow_exceptions).parse(true, result);
  18832. return result;
  18833. }
  18834. template<class IteratorType, typename std::enable_if<
  18835. std::is_base_of<
  18836. std::random_access_iterator_tag,
  18837. typename std::iterator_traits<IteratorType>::iterator_category>::value, int>::type = 0>
  18838. static bool accept(IteratorType first, IteratorType last)
  18839. {
  18840. return parser(detail::input_adapter(first, last)).accept(true);
  18841. }
  18842. template<class IteratorType, class SAX, typename std::enable_if<
  18843. std::is_base_of<
  18844. std::random_access_iterator_tag,
  18845. typename std::iterator_traits<IteratorType>::iterator_category>::value, int>::type = 0>
  18846. JSON_HEDLEY_NON_NULL(3)
  18847. static bool sax_parse(IteratorType first, IteratorType last, SAX* sax)
  18848. {
  18849. return parser(detail::input_adapter(first, last)).sax_parse(sax);
  18850. }
  18851. /*!
  18852. @brief deserialize from stream
  18853. @deprecated This stream operator is deprecated and will be removed in
  18854. version 4.0.0 of the library. Please use
  18855. @ref operator>>(std::istream&, basic_json&)
  18856. instead; that is, replace calls like `j << i;` with `i >> j;`.
  18857. @since version 1.0.0; deprecated since version 3.0.0
  18858. */
  18859. JSON_HEDLEY_DEPRECATED(3.0.0)
  18860. friend std::istream& operator<<(basic_json& j, std::istream& i)
  18861. {
  18862. return operator>>(i, j);
  18863. }
  18864. /*!
  18865. @brief deserialize from stream
  18866. Deserializes an input stream to a JSON value.
  18867. @param[in,out] i input stream to read a serialized JSON value from
  18868. @param[in,out] j JSON value to write the deserialized input to
  18869. @throw parse_error.101 in case of an unexpected token
  18870. @throw parse_error.102 if to_unicode fails or surrogate error
  18871. @throw parse_error.103 if to_unicode fails
  18872. @complexity Linear in the length of the input. The parser is a predictive
  18873. LL(1) parser.
  18874. @note A UTF-8 byte order mark is silently ignored.
  18875. @liveexample{The example below shows how a JSON value is constructed by
  18876. reading a serialization from a stream.,operator_deserialize}
  18877. @sa parse(std::istream&, const parser_callback_t) for a variant with a
  18878. parser callback function to filter values while parsing
  18879. @since version 1.0.0
  18880. */
  18881. friend std::istream& operator>>(std::istream& i, basic_json& j)
  18882. {
  18883. parser(detail::input_adapter(i)).parse(false, j);
  18884. return i;
  18885. }
  18886. /// @}
  18887. ///////////////////////////
  18888. // convenience functions //
  18889. ///////////////////////////
  18890. /*!
  18891. @brief return the type as string
  18892. Returns the type name as string to be used in error messages - usually to
  18893. indicate that a function was called on a wrong JSON type.
  18894. @return a string representation of a the @a m_type member:
  18895. Value type | return value
  18896. ----------- | -------------
  18897. null | `"null"`
  18898. boolean | `"boolean"`
  18899. string | `"string"`
  18900. number | `"number"` (for all number types)
  18901. object | `"object"`
  18902. array | `"array"`
  18903. binary | `"binary"`
  18904. discarded | `"discarded"`
  18905. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  18906. @complexity Constant.
  18907. @liveexample{The following code exemplifies `type_name()` for all JSON
  18908. types.,type_name}
  18909. @sa @ref type() -- return the type of the JSON value
  18910. @sa @ref operator value_t() -- return the type of the JSON value (implicit)
  18911. @since version 1.0.0, public since 2.1.0, `const char*` and `noexcept`
  18912. since 3.0.0
  18913. */
  18914. JSON_HEDLEY_RETURNS_NON_NULL
  18915. const char* type_name() const noexcept
  18916. {
  18917. {
  18918. switch (m_type)
  18919. {
  18920. case value_t::null:
  18921. return "null";
  18922. case value_t::object:
  18923. return "object";
  18924. case value_t::array:
  18925. return "array";
  18926. case value_t::string:
  18927. return "string";
  18928. case value_t::boolean:
  18929. return "boolean";
  18930. case value_t::binary:
  18931. return "binary";
  18932. case value_t::discarded:
  18933. return "discarded";
  18934. default:
  18935. return "number";
  18936. }
  18937. }
  18938. }
  18939. private:
  18940. //////////////////////
  18941. // member variables //
  18942. //////////////////////
  18943. /// the type of the current element
  18944. value_t m_type = value_t::null;
  18945. /// the value of the current element
  18946. json_value m_value = {};
  18947. //////////////////////////////////////////
  18948. // binary serialization/deserialization //
  18949. //////////////////////////////////////////
  18950. /// @name binary serialization/deserialization support
  18951. /// @{
  18952. public:
  18953. /*!
  18954. @brief create a CBOR serialization of a given JSON value
  18955. Serializes a given JSON value @a j to a byte vector using the CBOR (Concise
  18956. Binary Object Representation) serialization format. CBOR is a binary
  18957. serialization format which aims to be more compact than JSON itself, yet
  18958. more efficient to parse.
  18959. The library uses the following mapping from JSON values types to
  18960. CBOR types according to the CBOR specification (RFC 7049):
  18961. JSON value type | value/range | CBOR type | first byte
  18962. --------------- | ------------------------------------------ | ---------------------------------- | ---------------
  18963. null | `null` | Null | 0xF6
  18964. boolean | `true` | True | 0xF5
  18965. boolean | `false` | False | 0xF4
  18966. number_integer | -9223372036854775808..-2147483649 | Negative integer (8 bytes follow) | 0x3B
  18967. number_integer | -2147483648..-32769 | Negative integer (4 bytes follow) | 0x3A
  18968. number_integer | -32768..-129 | Negative integer (2 bytes follow) | 0x39
  18969. number_integer | -128..-25 | Negative integer (1 byte follow) | 0x38
  18970. number_integer | -24..-1 | Negative integer | 0x20..0x37
  18971. number_integer | 0..23 | Integer | 0x00..0x17
  18972. number_integer | 24..255 | Unsigned integer (1 byte follow) | 0x18
  18973. number_integer | 256..65535 | Unsigned integer (2 bytes follow) | 0x19
  18974. number_integer | 65536..4294967295 | Unsigned integer (4 bytes follow) | 0x1A
  18975. number_integer | 4294967296..18446744073709551615 | Unsigned integer (8 bytes follow) | 0x1B
  18976. number_unsigned | 0..23 | Integer | 0x00..0x17
  18977. number_unsigned | 24..255 | Unsigned integer (1 byte follow) | 0x18
  18978. number_unsigned | 256..65535 | Unsigned integer (2 bytes follow) | 0x19
  18979. number_unsigned | 65536..4294967295 | Unsigned integer (4 bytes follow) | 0x1A
  18980. number_unsigned | 4294967296..18446744073709551615 | Unsigned integer (8 bytes follow) | 0x1B
  18981. number_float | *any value* | Double-Precision Float | 0xFB
  18982. string | *length*: 0..23 | UTF-8 string | 0x60..0x77
  18983. string | *length*: 23..255 | UTF-8 string (1 byte follow) | 0x78
  18984. string | *length*: 256..65535 | UTF-8 string (2 bytes follow) | 0x79
  18985. string | *length*: 65536..4294967295 | UTF-8 string (4 bytes follow) | 0x7A
  18986. string | *length*: 4294967296..18446744073709551615 | UTF-8 string (8 bytes follow) | 0x7B
  18987. array | *size*: 0..23 | array | 0x80..0x97
  18988. array | *size*: 23..255 | array (1 byte follow) | 0x98
  18989. array | *size*: 256..65535 | array (2 bytes follow) | 0x99
  18990. array | *size*: 65536..4294967295 | array (4 bytes follow) | 0x9A
  18991. array | *size*: 4294967296..18446744073709551615 | array (8 bytes follow) | 0x9B
  18992. object | *size*: 0..23 | map | 0xA0..0xB7
  18993. object | *size*: 23..255 | map (1 byte follow) | 0xB8
  18994. object | *size*: 256..65535 | map (2 bytes follow) | 0xB9
  18995. object | *size*: 65536..4294967295 | map (4 bytes follow) | 0xBA
  18996. object | *size*: 4294967296..18446744073709551615 | map (8 bytes follow) | 0xBB
  18997. binary | *size*: 0..23 | byte string | 0x40..0x57
  18998. binary | *size*: 23..255 | byte string (1 byte follow) | 0x58
  18999. binary | *size*: 256..65535 | byte string (2 bytes follow) | 0x59
  19000. binary | *size*: 65536..4294967295 | byte string (4 bytes follow) | 0x5A
  19001. binary | *size*: 4294967296..18446744073709551615 | byte string (8 bytes follow) | 0x5B
  19002. @note The mapping is **complete** in the sense that any JSON value type
  19003. can be converted to a CBOR value.
  19004. @note If NaN or Infinity are stored inside a JSON number, they are
  19005. serialized properly. This behavior differs from the @ref dump()
  19006. function which serializes NaN or Infinity to `null`.
  19007. @note The following CBOR types are not used in the conversion:
  19008. - UTF-8 strings terminated by "break" (0x7F)
  19009. - arrays terminated by "break" (0x9F)
  19010. - maps terminated by "break" (0xBF)
  19011. - byte strings terminated by "break" (0x5F)
  19012. - date/time (0xC0..0xC1)
  19013. - bignum (0xC2..0xC3)
  19014. - decimal fraction (0xC4)
  19015. - bigfloat (0xC5)
  19016. - tagged items (0xC6..0xD4, 0xD8..0xDB)
  19017. - expected conversions (0xD5..0xD7)
  19018. - simple values (0xE0..0xF3, 0xF8)
  19019. - undefined (0xF7)
  19020. - half and single-precision floats (0xF9-0xFA)
  19021. - break (0xFF)
  19022. @param[in] j JSON value to serialize
  19023. @return MessagePack serialization as byte vector
  19024. @complexity Linear in the size of the JSON value @a j.
  19025. @liveexample{The example shows the serialization of a JSON value to a byte
  19026. vector in CBOR format.,to_cbor}
  19027. @sa http://cbor.io
  19028. @sa @ref from_cbor(detail::input_adapter&&, const bool, const bool) for the
  19029. analogous deserialization
  19030. @sa @ref to_msgpack(const basic_json&) for the related MessagePack format
  19031. @sa @ref to_ubjson(const basic_json&, const bool, const bool) for the
  19032. related UBJSON format
  19033. @since version 2.0.9
  19034. */
  19035. static std::vector<uint8_t> to_cbor(const basic_json& j)
  19036. {
  19037. std::vector<uint8_t> result;
  19038. to_cbor(j, result);
  19039. return result;
  19040. }
  19041. static void to_cbor(const basic_json& j, detail::output_adapter<uint8_t> o)
  19042. {
  19043. binary_writer<uint8_t>(o).write_cbor(j);
  19044. }
  19045. static void to_cbor(const basic_json& j, detail::output_adapter<char> o)
  19046. {
  19047. binary_writer<char>(o).write_cbor(j);
  19048. }
  19049. /*!
  19050. @brief create a MessagePack serialization of a given JSON value
  19051. Serializes a given JSON value @a j to a byte vector using the MessagePack
  19052. serialization format. MessagePack is a binary serialization format which
  19053. aims to be more compact than JSON itself, yet more efficient to parse.
  19054. The library uses the following mapping from JSON values types to
  19055. MessagePack types according to the MessagePack specification:
  19056. JSON value type | value/range | MessagePack type | first byte
  19057. --------------- | --------------------------------- | ---------------- | ----------
  19058. null | `null` | nil | 0xC0
  19059. boolean | `true` | true | 0xC3
  19060. boolean | `false` | false | 0xC2
  19061. number_integer | -9223372036854775808..-2147483649 | int64 | 0xD3
  19062. number_integer | -2147483648..-32769 | int32 | 0xD2
  19063. number_integer | -32768..-129 | int16 | 0xD1
  19064. number_integer | -128..-33 | int8 | 0xD0
  19065. number_integer | -32..-1 | negative fixint | 0xE0..0xFF
  19066. number_integer | 0..127 | positive fixint | 0x00..0x7F
  19067. number_integer | 128..255 | uint 8 | 0xCC
  19068. number_integer | 256..65535 | uint 16 | 0xCD
  19069. number_integer | 65536..4294967295 | uint 32 | 0xCE
  19070. number_integer | 4294967296..18446744073709551615 | uint 64 | 0xCF
  19071. number_unsigned | 0..127 | positive fixint | 0x00..0x7F
  19072. number_unsigned | 128..255 | uint 8 | 0xCC
  19073. number_unsigned | 256..65535 | uint 16 | 0xCD
  19074. number_unsigned | 65536..4294967295 | uint 32 | 0xCE
  19075. number_unsigned | 4294967296..18446744073709551615 | uint 64 | 0xCF
  19076. number_float | *any value* | float 64 | 0xCB
  19077. string | *length*: 0..31 | fixstr | 0xA0..0xBF
  19078. string | *length*: 32..255 | str 8 | 0xD9
  19079. string | *length*: 256..65535 | str 16 | 0xDA
  19080. string | *length*: 65536..4294967295 | str 32 | 0xDB
  19081. array | *size*: 0..15 | fixarray | 0x90..0x9F
  19082. array | *size*: 16..65535 | array 16 | 0xDC
  19083. array | *size*: 65536..4294967295 | array 32 | 0xDD
  19084. object | *size*: 0..15 | fix map | 0x80..0x8F
  19085. object | *size*: 16..65535 | map 16 | 0xDE
  19086. object | *size*: 65536..4294967295 | map 32 | 0xDF
  19087. binary | *size*: 0..255 | bin 8 | 0xC4
  19088. binary | *size*: 256..65535 | bin 16 | 0xC5
  19089. binary | *size*: 65536..4294967295 | bin 32 | 0xC6
  19090. @note The mapping is **complete** in the sense that any JSON value type
  19091. can be converted to a MessagePack value.
  19092. @note The following values can **not** be converted to a MessagePack value:
  19093. - strings with more than 4294967295 bytes
  19094. - byte strings with more than 4294967295 bytes
  19095. - arrays with more than 4294967295 elements
  19096. - objects with more than 4294967295 elements
  19097. @note The following MessagePack types are not used in the conversion:
  19098. - float 32 (0xCA)
  19099. @note Any MessagePack output created @ref to_msgpack can be successfully
  19100. parsed by @ref from_msgpack.
  19101. @note If NaN or Infinity are stored inside a JSON number, they are
  19102. serialized properly. This behavior differs from the @ref dump()
  19103. function which serializes NaN or Infinity to `null`.
  19104. @param[in] j JSON value to serialize
  19105. @return MessagePack serialization as byte vector
  19106. @complexity Linear in the size of the JSON value @a j.
  19107. @liveexample{The example shows the serialization of a JSON value to a byte
  19108. vector in MessagePack format.,to_msgpack}
  19109. @sa http://msgpack.org
  19110. @sa @ref from_msgpack for the analogous deserialization
  19111. @sa @ref to_cbor(const basic_json& for the related CBOR format
  19112. @sa @ref to_ubjson(const basic_json&, const bool, const bool) for the
  19113. related UBJSON format
  19114. @since version 2.0.9
  19115. */
  19116. static std::vector<uint8_t> to_msgpack(const basic_json& j)
  19117. {
  19118. std::vector<uint8_t> result;
  19119. to_msgpack(j, result);
  19120. return result;
  19121. }
  19122. static void to_msgpack(const basic_json& j, detail::output_adapter<uint8_t> o)
  19123. {
  19124. binary_writer<uint8_t>(o).write_msgpack(j);
  19125. }
  19126. static void to_msgpack(const basic_json& j, detail::output_adapter<char> o)
  19127. {
  19128. binary_writer<char>(o).write_msgpack(j);
  19129. }
  19130. /*!
  19131. @brief create a UBJSON serialization of a given JSON value
  19132. Serializes a given JSON value @a j to a byte vector using the UBJSON
  19133. (Universal Binary JSON) serialization format. UBJSON aims to be more compact
  19134. than JSON itself, yet more efficient to parse.
  19135. The library uses the following mapping from JSON values types to
  19136. UBJSON types according to the UBJSON specification:
  19137. JSON value type | value/range | UBJSON type | marker
  19138. --------------- | --------------------------------- | ----------- | ------
  19139. null | `null` | null | `Z`
  19140. boolean | `true` | true | `T`
  19141. boolean | `false` | false | `F`
  19142. number_integer | -9223372036854775808..-2147483649 | int64 | `L`
  19143. number_integer | -2147483648..-32769 | int32 | `l`
  19144. number_integer | -32768..-129 | int16 | `I`
  19145. number_integer | -128..127 | int8 | `i`
  19146. number_integer | 128..255 | uint8 | `U`
  19147. number_integer | 256..32767 | int16 | `I`
  19148. number_integer | 32768..2147483647 | int32 | `l`
  19149. number_integer | 2147483648..9223372036854775807 | int64 | `L`
  19150. number_unsigned | 0..127 | int8 | `i`
  19151. number_unsigned | 128..255 | uint8 | `U`
  19152. number_unsigned | 256..32767 | int16 | `I`
  19153. number_unsigned | 32768..2147483647 | int32 | `l`
  19154. number_unsigned | 2147483648..9223372036854775807 | int64 | `L`
  19155. number_float | *any value* | float64 | `D`
  19156. string | *with shortest length indicator* | string | `S`
  19157. array | *see notes on optimized format* | array | `[`
  19158. object | *see notes on optimized format* | map | `{`
  19159. @note The mapping is **complete** in the sense that any JSON value type
  19160. can be converted to a UBJSON value.
  19161. @note The following values can **not** be converted to a UBJSON value:
  19162. - strings with more than 9223372036854775807 bytes (theoretical)
  19163. - unsigned integer numbers above 9223372036854775807
  19164. @note The following markers are not used in the conversion:
  19165. - `Z`: no-op values are not created.
  19166. - `C`: single-byte strings are serialized with `S` markers.
  19167. @note Any UBJSON output created @ref to_ubjson can be successfully parsed
  19168. by @ref from_ubjson.
  19169. @note If NaN or Infinity are stored inside a JSON number, they are
  19170. serialized properly. This behavior differs from the @ref dump()
  19171. function which serializes NaN or Infinity to `null`.
  19172. @note The optimized formats for containers are supported: Parameter
  19173. @a use_size adds size information to the beginning of a container and
  19174. removes the closing marker. Parameter @a use_type further checks
  19175. whether all elements of a container have the same type and adds the
  19176. type marker to the beginning of the container. The @a use_type
  19177. parameter must only be used together with @a use_size = true. Note
  19178. that @a use_size = true alone may result in larger representations -
  19179. the benefit of this parameter is that the receiving side is
  19180. immediately informed on the number of elements of the container.
  19181. @note If the JSON data contains the binary type, the value stored is a list
  19182. of integers, as suggested by the UBJSON documentation. In particular,
  19183. this means that serialization and the deserialization of a JSON
  19184. containing binary values into UBJSON and back will result in a
  19185. different JSON object.
  19186. @param[in] j JSON value to serialize
  19187. @param[in] use_size whether to add size annotations to container types
  19188. @param[in] use_type whether to add type annotations to container types
  19189. (must be combined with @a use_size = true)
  19190. @return UBJSON serialization as byte vector
  19191. @complexity Linear in the size of the JSON value @a j.
  19192. @liveexample{The example shows the serialization of a JSON value to a byte
  19193. vector in UBJSON format.,to_ubjson}
  19194. @sa http://ubjson.org
  19195. @sa @ref from_ubjson(detail::input_adapter&&, const bool, const bool) for the
  19196. analogous deserialization
  19197. @sa @ref to_cbor(const basic_json& for the related CBOR format
  19198. @sa @ref to_msgpack(const basic_json&) for the related MessagePack format
  19199. @since version 3.1.0
  19200. */
  19201. static std::vector<uint8_t> to_ubjson(const basic_json& j,
  19202. const bool use_size = false,
  19203. const bool use_type = false)
  19204. {
  19205. std::vector<uint8_t> result;
  19206. to_ubjson(j, result, use_size, use_type);
  19207. return result;
  19208. }
  19209. static void to_ubjson(const basic_json& j, detail::output_adapter<uint8_t> o,
  19210. const bool use_size = false, const bool use_type = false)
  19211. {
  19212. binary_writer<uint8_t>(o).write_ubjson(j, use_size, use_type);
  19213. }
  19214. static void to_ubjson(const basic_json& j, detail::output_adapter<char> o,
  19215. const bool use_size = false, const bool use_type = false)
  19216. {
  19217. binary_writer<char>(o).write_ubjson(j, use_size, use_type);
  19218. }
  19219. /*!
  19220. @brief Serializes the given JSON object `j` to BSON and returns a vector
  19221. containing the corresponding BSON-representation.
  19222. BSON (Binary JSON) is a binary format in which zero or more ordered key/value pairs are
  19223. stored as a single entity (a so-called document).
  19224. The library uses the following mapping from JSON values types to BSON types:
  19225. JSON value type | value/range | BSON type | marker
  19226. --------------- | --------------------------------- | ----------- | ------
  19227. null | `null` | null | 0x0A
  19228. boolean | `true`, `false` | boolean | 0x08
  19229. number_integer | -9223372036854775808..-2147483649 | int64 | 0x12
  19230. number_integer | -2147483648..2147483647 | int32 | 0x10
  19231. number_integer | 2147483648..9223372036854775807 | int64 | 0x12
  19232. number_unsigned | 0..2147483647 | int32 | 0x10
  19233. number_unsigned | 2147483648..9223372036854775807 | int64 | 0x12
  19234. number_unsigned | 9223372036854775808..18446744073709551615| -- | --
  19235. number_float | *any value* | double | 0x01
  19236. string | *any value* | string | 0x02
  19237. array | *any value* | document | 0x04
  19238. object | *any value* | document | 0x03
  19239. binary | *any value* | binary | 0x05
  19240. @warning The mapping is **incomplete**, since only JSON-objects (and things
  19241. contained therein) can be serialized to BSON.
  19242. Also, integers larger than 9223372036854775807 cannot be serialized to BSON,
  19243. and the keys may not contain U+0000, since they are serialized a
  19244. zero-terminated c-strings.
  19245. @throw out_of_range.407 if `j.is_number_unsigned() && j.get<std::uint64_t>() > 9223372036854775807`
  19246. @throw out_of_range.409 if a key in `j` contains a NULL (U+0000)
  19247. @throw type_error.317 if `!j.is_object()`
  19248. @pre The input `j` is required to be an object: `j.is_object() == true`.
  19249. @note Any BSON output created via @ref to_bson can be successfully parsed
  19250. by @ref from_bson.
  19251. @param[in] j JSON value to serialize
  19252. @return BSON serialization as byte vector
  19253. @complexity Linear in the size of the JSON value @a j.
  19254. @liveexample{The example shows the serialization of a JSON value to a byte
  19255. vector in BSON format.,to_bson}
  19256. @sa http://bsonspec.org/spec.html
  19257. @sa @ref from_bson(detail::input_adapter&&, const bool strict) for the
  19258. analogous deserialization
  19259. @sa @ref to_ubjson(const basic_json&, const bool, const bool) for the
  19260. related UBJSON format
  19261. @sa @ref to_cbor(const basic_json&) for the related CBOR format
  19262. @sa @ref to_msgpack(const basic_json&) for the related MessagePack format
  19263. */
  19264. static std::vector<uint8_t> to_bson(const basic_json& j)
  19265. {
  19266. std::vector<uint8_t> result;
  19267. to_bson(j, result);
  19268. return result;
  19269. }
  19270. /*!
  19271. @brief Serializes the given JSON object `j` to BSON and forwards the
  19272. corresponding BSON-representation to the given output_adapter `o`.
  19273. @param j The JSON object to convert to BSON.
  19274. @param o The output adapter that receives the binary BSON representation.
  19275. @pre The input `j` shall be an object: `j.is_object() == true`
  19276. @sa @ref to_bson(const basic_json&)
  19277. */
  19278. static void to_bson(const basic_json& j, detail::output_adapter<uint8_t> o)
  19279. {
  19280. binary_writer<uint8_t>(o).write_bson(j);
  19281. }
  19282. /*!
  19283. @copydoc to_bson(const basic_json&, detail::output_adapter<uint8_t>)
  19284. */
  19285. static void to_bson(const basic_json& j, detail::output_adapter<char> o)
  19286. {
  19287. binary_writer<char>(o).write_bson(j);
  19288. }
  19289. /*!
  19290. @brief create a JSON value from an input in CBOR format
  19291. Deserializes a given input @a i to a JSON value using the CBOR (Concise
  19292. Binary Object Representation) serialization format.
  19293. The library maps CBOR types to JSON value types as follows:
  19294. CBOR type | JSON value type | first byte
  19295. ---------------------- | --------------- | ----------
  19296. Integer | number_unsigned | 0x00..0x17
  19297. Unsigned integer | number_unsigned | 0x18
  19298. Unsigned integer | number_unsigned | 0x19
  19299. Unsigned integer | number_unsigned | 0x1A
  19300. Unsigned integer | number_unsigned | 0x1B
  19301. Negative integer | number_integer | 0x20..0x37
  19302. Negative integer | number_integer | 0x38
  19303. Negative integer | number_integer | 0x39
  19304. Negative integer | number_integer | 0x3A
  19305. Negative integer | number_integer | 0x3B
  19306. Byte string | binary | 0x40..0x57
  19307. Byte string | binary | 0x58
  19308. Byte string | binary | 0x59
  19309. Byte string | binary | 0x5A
  19310. Byte string | binary | 0x5B
  19311. UTF-8 string | string | 0x60..0x77
  19312. UTF-8 string | string | 0x78
  19313. UTF-8 string | string | 0x79
  19314. UTF-8 string | string | 0x7A
  19315. UTF-8 string | string | 0x7B
  19316. UTF-8 string | string | 0x7F
  19317. array | array | 0x80..0x97
  19318. array | array | 0x98
  19319. array | array | 0x99
  19320. array | array | 0x9A
  19321. array | array | 0x9B
  19322. array | array | 0x9F
  19323. map | object | 0xA0..0xB7
  19324. map | object | 0xB8
  19325. map | object | 0xB9
  19326. map | object | 0xBA
  19327. map | object | 0xBB
  19328. map | object | 0xBF
  19329. False | `false` | 0xF4
  19330. True | `true` | 0xF5
  19331. Null | `null` | 0xF6
  19332. Half-Precision Float | number_float | 0xF9
  19333. Single-Precision Float | number_float | 0xFA
  19334. Double-Precision Float | number_float | 0xFB
  19335. @warning The mapping is **incomplete** in the sense that not all CBOR
  19336. types can be converted to a JSON value. The following CBOR types
  19337. are not supported and will yield parse errors (parse_error.112):
  19338. - date/time (0xC0..0xC1)
  19339. - bignum (0xC2..0xC3)
  19340. - decimal fraction (0xC4)
  19341. - bigfloat (0xC5)
  19342. - tagged items (0xC6..0xD4, 0xD8..0xDB)
  19343. - expected conversions (0xD5..0xD7)
  19344. - simple values (0xE0..0xF3, 0xF8)
  19345. - undefined (0xF7)
  19346. @warning CBOR allows map keys of any type, whereas JSON only allows
  19347. strings as keys in object values. Therefore, CBOR maps with keys
  19348. other than UTF-8 strings are rejected (parse_error.113).
  19349. @note Any CBOR output created @ref to_cbor can be successfully parsed by
  19350. @ref from_cbor.
  19351. @param[in] i an input in CBOR format convertible to an input adapter
  19352. @param[in] strict whether to expect the input to be consumed until EOF
  19353. (true by default)
  19354. @param[in] allow_exceptions whether to throw exceptions in case of a
  19355. parse error (optional, true by default)
  19356. @return deserialized JSON value; in case of a parse error and
  19357. @a allow_exceptions set to `false`, the return value will be
  19358. value_t::discarded.
  19359. @throw parse_error.110 if the given input ends prematurely or the end of
  19360. file was not reached when @a strict was set to true
  19361. @throw parse_error.112 if unsupported features from CBOR were
  19362. used in the given input @a v or if the input is not valid CBOR
  19363. @throw parse_error.113 if a string was expected as map key, but not found
  19364. @complexity Linear in the size of the input @a i.
  19365. @liveexample{The example shows the deserialization of a byte vector in CBOR
  19366. format to a JSON value.,from_cbor}
  19367. @sa http://cbor.io
  19368. @sa @ref to_cbor(const basic_json&) for the analogous serialization
  19369. @sa @ref from_msgpack(detail::input_adapter&&, const bool, const bool) for the
  19370. related MessagePack format
  19371. @sa @ref from_ubjson(detail::input_adapter&&, const bool, const bool) for the
  19372. related UBJSON format
  19373. @since version 2.0.9; parameter @a start_index since 2.1.1; changed to
  19374. consume input adapters, removed start_index parameter, and added
  19375. @a strict parameter since 3.0.0; added @a allow_exceptions parameter
  19376. since 3.2.0
  19377. */
  19378. JSON_HEDLEY_WARN_UNUSED_RESULT
  19379. static basic_json from_cbor(detail::input_adapter&& i,
  19380. const bool strict = true,
  19381. const bool allow_exceptions = true)
  19382. {
  19383. basic_json result;
  19384. detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
  19385. const bool res = binary_reader(detail::input_adapter(i)).sax_parse(input_format_t::cbor, &sdp, strict);
  19386. return res ? result : basic_json(value_t::discarded);
  19387. }
  19388. /*!
  19389. @copydoc from_cbor(detail::input_adapter&&, const bool, const bool)
  19390. */
  19391. template<typename A1, typename A2,
  19392. detail::enable_if_t<std::is_constructible<detail::input_adapter, A1, A2>::value, int> = 0>
  19393. JSON_HEDLEY_WARN_UNUSED_RESULT
  19394. static basic_json from_cbor(A1 && a1, A2 && a2,
  19395. const bool strict = true,
  19396. const bool allow_exceptions = true)
  19397. {
  19398. basic_json result;
  19399. detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
  19400. const bool res = binary_reader(detail::input_adapter(std::forward<A1>(a1), std::forward<A2>(a2))).sax_parse(input_format_t::cbor, &sdp, strict);
  19401. return res ? result : basic_json(value_t::discarded);
  19402. }
  19403. /*!
  19404. @brief create a JSON value from an input in MessagePack format
  19405. Deserializes a given input @a i to a JSON value using the MessagePack
  19406. serialization format.
  19407. The library maps MessagePack types to JSON value types as follows:
  19408. MessagePack type | JSON value type | first byte
  19409. ---------------- | --------------- | ----------
  19410. positive fixint | number_unsigned | 0x00..0x7F
  19411. fixmap | object | 0x80..0x8F
  19412. fixarray | array | 0x90..0x9F
  19413. fixstr | string | 0xA0..0xBF
  19414. nil | `null` | 0xC0
  19415. false | `false` | 0xC2
  19416. true | `true` | 0xC3
  19417. float 32 | number_float | 0xCA
  19418. float 64 | number_float | 0xCB
  19419. uint 8 | number_unsigned | 0xCC
  19420. uint 16 | number_unsigned | 0xCD
  19421. uint 32 | number_unsigned | 0xCE
  19422. uint 64 | number_unsigned | 0xCF
  19423. int 8 | number_integer | 0xD0
  19424. int 16 | number_integer | 0xD1
  19425. int 32 | number_integer | 0xD2
  19426. int 64 | number_integer | 0xD3
  19427. str 8 | string | 0xD9
  19428. str 16 | string | 0xDA
  19429. str 32 | string | 0xDB
  19430. array 16 | array | 0xDC
  19431. array 32 | array | 0xDD
  19432. map 16 | object | 0xDE
  19433. map 32 | object | 0xDF
  19434. bin 8 | binary | 0xC4
  19435. bin 16 | binary | 0xC5
  19436. bin 32 | binary | 0xC6
  19437. ext 8 | binary | 0xC7
  19438. ext 16 | binary | 0xC8
  19439. ext 32 | binary | 0xC9
  19440. fixext 1 | binary | 0xD4
  19441. fixext 2 | binary | 0xD5
  19442. fixext 4 | binary | 0xD6
  19443. fixext 8 | binary | 0xD7
  19444. fixext 16 | binary | 0xD8
  19445. negative fixint | number_integer | 0xE0-0xFF
  19446. @note Any MessagePack output created @ref to_msgpack can be successfully
  19447. parsed by @ref from_msgpack.
  19448. @param[in] i an input in MessagePack format convertible to an input
  19449. adapter
  19450. @param[in] strict whether to expect the input to be consumed until EOF
  19451. (true by default)
  19452. @param[in] allow_exceptions whether to throw exceptions in case of a
  19453. parse error (optional, true by default)
  19454. @return deserialized JSON value; in case of a parse error and
  19455. @a allow_exceptions set to `false`, the return value will be
  19456. value_t::discarded.
  19457. @throw parse_error.110 if the given input ends prematurely or the end of
  19458. file was not reached when @a strict was set to true
  19459. @throw parse_error.112 if unsupported features from MessagePack were
  19460. used in the given input @a i or if the input is not valid MessagePack
  19461. @throw parse_error.113 if a string was expected as map key, but not found
  19462. @complexity Linear in the size of the input @a i.
  19463. @liveexample{The example shows the deserialization of a byte vector in
  19464. MessagePack format to a JSON value.,from_msgpack}
  19465. @sa http://msgpack.org
  19466. @sa @ref to_msgpack(const basic_json&) for the analogous serialization
  19467. @sa @ref from_cbor(detail::input_adapter&&, const bool, const bool) for the
  19468. related CBOR format
  19469. @sa @ref from_ubjson(detail::input_adapter&&, const bool, const bool) for
  19470. the related UBJSON format
  19471. @sa @ref from_bson(detail::input_adapter&&, const bool, const bool) for
  19472. the related BSON format
  19473. @since version 2.0.9; parameter @a start_index since 2.1.1; changed to
  19474. consume input adapters, removed start_index parameter, and added
  19475. @a strict parameter since 3.0.0; added @a allow_exceptions parameter
  19476. since 3.2.0
  19477. */
  19478. JSON_HEDLEY_WARN_UNUSED_RESULT
  19479. static basic_json from_msgpack(detail::input_adapter&& i,
  19480. const bool strict = true,
  19481. const bool allow_exceptions = true)
  19482. {
  19483. basic_json result;
  19484. detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
  19485. const bool res = binary_reader(detail::input_adapter(i)).sax_parse(input_format_t::msgpack, &sdp, strict);
  19486. return res ? result : basic_json(value_t::discarded);
  19487. }
  19488. /*!
  19489. @copydoc from_msgpack(detail::input_adapter&&, const bool, const bool)
  19490. */
  19491. template<typename A1, typename A2,
  19492. detail::enable_if_t<std::is_constructible<detail::input_adapter, A1, A2>::value, int> = 0>
  19493. JSON_HEDLEY_WARN_UNUSED_RESULT
  19494. static basic_json from_msgpack(A1 && a1, A2 && a2,
  19495. const bool strict = true,
  19496. const bool allow_exceptions = true)
  19497. {
  19498. basic_json result;
  19499. detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
  19500. const bool res = binary_reader(detail::input_adapter(std::forward<A1>(a1), std::forward<A2>(a2))).sax_parse(input_format_t::msgpack, &sdp, strict);
  19501. return res ? result : basic_json(value_t::discarded);
  19502. }
  19503. /*!
  19504. @brief create a JSON value from an input in UBJSON format
  19505. Deserializes a given input @a i to a JSON value using the UBJSON (Universal
  19506. Binary JSON) serialization format.
  19507. The library maps UBJSON types to JSON value types as follows:
  19508. UBJSON type | JSON value type | marker
  19509. ----------- | --------------------------------------- | ------
  19510. no-op | *no value, next value is read* | `N`
  19511. null | `null` | `Z`
  19512. false | `false` | `F`
  19513. true | `true` | `T`
  19514. float32 | number_float | `d`
  19515. float64 | number_float | `D`
  19516. uint8 | number_unsigned | `U`
  19517. int8 | number_integer | `i`
  19518. int16 | number_integer | `I`
  19519. int32 | number_integer | `l`
  19520. int64 | number_integer | `L`
  19521. string | string | `S`
  19522. char | string | `C`
  19523. array | array (optimized values are supported) | `[`
  19524. object | object (optimized values are supported) | `{`
  19525. @note The mapping is **complete** in the sense that any UBJSON value can
  19526. be converted to a JSON value.
  19527. @param[in] i an input in UBJSON format convertible to an input adapter
  19528. @param[in] strict whether to expect the input to be consumed until EOF
  19529. (true by default)
  19530. @param[in] allow_exceptions whether to throw exceptions in case of a
  19531. parse error (optional, true by default)
  19532. @return deserialized JSON value; in case of a parse error and
  19533. @a allow_exceptions set to `false`, the return value will be
  19534. value_t::discarded.
  19535. @throw parse_error.110 if the given input ends prematurely or the end of
  19536. file was not reached when @a strict was set to true
  19537. @throw parse_error.112 if a parse error occurs
  19538. @throw parse_error.113 if a string could not be parsed successfully
  19539. @complexity Linear in the size of the input @a i.
  19540. @liveexample{The example shows the deserialization of a byte vector in
  19541. UBJSON format to a JSON value.,from_ubjson}
  19542. @sa http://ubjson.org
  19543. @sa @ref to_ubjson(const basic_json&, const bool, const bool) for the
  19544. analogous serialization
  19545. @sa @ref from_cbor(detail::input_adapter&&, const bool, const bool) for the
  19546. related CBOR format
  19547. @sa @ref from_msgpack(detail::input_adapter&&, const bool, const bool) for
  19548. the related MessagePack format
  19549. @sa @ref from_bson(detail::input_adapter&&, const bool, const bool) for
  19550. the related BSON format
  19551. @since version 3.1.0; added @a allow_exceptions parameter since 3.2.0
  19552. */
  19553. JSON_HEDLEY_WARN_UNUSED_RESULT
  19554. static basic_json from_ubjson(detail::input_adapter&& i,
  19555. const bool strict = true,
  19556. const bool allow_exceptions = true)
  19557. {
  19558. basic_json result;
  19559. detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
  19560. const bool res = binary_reader(detail::input_adapter(i)).sax_parse(input_format_t::ubjson, &sdp, strict);
  19561. return res ? result : basic_json(value_t::discarded);
  19562. }
  19563. /*!
  19564. @copydoc from_ubjson(detail::input_adapter&&, const bool, const bool)
  19565. */
  19566. template<typename A1, typename A2,
  19567. detail::enable_if_t<std::is_constructible<detail::input_adapter, A1, A2>::value, int> = 0>
  19568. JSON_HEDLEY_WARN_UNUSED_RESULT
  19569. static basic_json from_ubjson(A1 && a1, A2 && a2,
  19570. const bool strict = true,
  19571. const bool allow_exceptions = true)
  19572. {
  19573. basic_json result;
  19574. detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
  19575. const bool res = binary_reader(detail::input_adapter(std::forward<A1>(a1), std::forward<A2>(a2))).sax_parse(input_format_t::ubjson, &sdp, strict);
  19576. return res ? result : basic_json(value_t::discarded);
  19577. }
  19578. /*!
  19579. @brief Create a JSON value from an input in BSON format
  19580. Deserializes a given input @a i to a JSON value using the BSON (Binary JSON)
  19581. serialization format.
  19582. The library maps BSON record types to JSON value types as follows:
  19583. BSON type | BSON marker byte | JSON value type
  19584. --------------- | ---------------- | ---------------------------
  19585. double | 0x01 | number_float
  19586. string | 0x02 | string
  19587. document | 0x03 | object
  19588. array | 0x04 | array
  19589. binary | 0x05 | still unsupported
  19590. undefined | 0x06 | still unsupported
  19591. ObjectId | 0x07 | still unsupported
  19592. boolean | 0x08 | boolean
  19593. UTC Date-Time | 0x09 | still unsupported
  19594. null | 0x0A | null
  19595. Regular Expr. | 0x0B | still unsupported
  19596. DB Pointer | 0x0C | still unsupported
  19597. JavaScript Code | 0x0D | still unsupported
  19598. Symbol | 0x0E | still unsupported
  19599. JavaScript Code | 0x0F | still unsupported
  19600. int32 | 0x10 | number_integer
  19601. Timestamp | 0x11 | still unsupported
  19602. 128-bit decimal float | 0x13 | still unsupported
  19603. Max Key | 0x7F | still unsupported
  19604. Min Key | 0xFF | still unsupported
  19605. @warning The mapping is **incomplete**. The unsupported mappings
  19606. are indicated in the table above.
  19607. @param[in] i an input in BSON format convertible to an input adapter
  19608. @param[in] strict whether to expect the input to be consumed until EOF
  19609. (true by default)
  19610. @param[in] allow_exceptions whether to throw exceptions in case of a
  19611. parse error (optional, true by default)
  19612. @return deserialized JSON value; in case of a parse error and
  19613. @a allow_exceptions set to `false`, the return value will be
  19614. value_t::discarded.
  19615. @throw parse_error.114 if an unsupported BSON record type is encountered
  19616. @complexity Linear in the size of the input @a i.
  19617. @liveexample{The example shows the deserialization of a byte vector in
  19618. BSON format to a JSON value.,from_bson}
  19619. @sa http://bsonspec.org/spec.html
  19620. @sa @ref to_bson(const basic_json&) for the analogous serialization
  19621. @sa @ref from_cbor(detail::input_adapter&&, const bool, const bool) for the
  19622. related CBOR format
  19623. @sa @ref from_msgpack(detail::input_adapter&&, const bool, const bool) for
  19624. the related MessagePack format
  19625. @sa @ref from_ubjson(detail::input_adapter&&, const bool, const bool) for the
  19626. related UBJSON format
  19627. */
  19628. JSON_HEDLEY_WARN_UNUSED_RESULT
  19629. static basic_json from_bson(detail::input_adapter&& i,
  19630. const bool strict = true,
  19631. const bool allow_exceptions = true)
  19632. {
  19633. basic_json result;
  19634. detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
  19635. const bool res = binary_reader(detail::input_adapter(i)).sax_parse(input_format_t::bson, &sdp, strict);
  19636. return res ? result : basic_json(value_t::discarded);
  19637. }
  19638. /*!
  19639. @copydoc from_bson(detail::input_adapter&&, const bool, const bool)
  19640. */
  19641. template<typename A1, typename A2,
  19642. detail::enable_if_t<std::is_constructible<detail::input_adapter, A1, A2>::value, int> = 0>
  19643. JSON_HEDLEY_WARN_UNUSED_RESULT
  19644. static basic_json from_bson(A1 && a1, A2 && a2,
  19645. const bool strict = true,
  19646. const bool allow_exceptions = true)
  19647. {
  19648. basic_json result;
  19649. detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
  19650. const bool res = binary_reader(detail::input_adapter(std::forward<A1>(a1), std::forward<A2>(a2))).sax_parse(input_format_t::bson, &sdp, strict);
  19651. return res ? result : basic_json(value_t::discarded);
  19652. }
  19653. /// @}
  19654. //////////////////////////
  19655. // JSON Pointer support //
  19656. //////////////////////////
  19657. /// @name JSON Pointer functions
  19658. /// @{
  19659. /*!
  19660. @brief access specified element via JSON Pointer
  19661. Uses a JSON pointer to retrieve a reference to the respective JSON value.
  19662. No bound checking is performed. Similar to @ref operator[](const typename
  19663. object_t::key_type&), `null` values are created in arrays and objects if
  19664. necessary.
  19665. In particular:
  19666. - If the JSON pointer points to an object key that does not exist, it
  19667. is created an filled with a `null` value before a reference to it
  19668. is returned.
  19669. - If the JSON pointer points to an array index that does not exist, it
  19670. is created an filled with a `null` value before a reference to it
  19671. is returned. All indices between the current maximum and the given
  19672. index are also filled with `null`.
  19673. - The special value `-` is treated as a synonym for the index past the
  19674. end.
  19675. @param[in] ptr a JSON pointer
  19676. @return reference to the element pointed to by @a ptr
  19677. @complexity Constant.
  19678. @throw parse_error.106 if an array index begins with '0'
  19679. @throw parse_error.109 if an array index was not a number
  19680. @throw out_of_range.404 if the JSON pointer can not be resolved
  19681. @liveexample{The behavior is shown in the example.,operatorjson_pointer}
  19682. @since version 2.0.0
  19683. */
  19684. reference operator[](const json_pointer& ptr)
  19685. {
  19686. return ptr.get_unchecked(this);
  19687. }
  19688. /*!
  19689. @brief access specified element via JSON Pointer
  19690. Uses a JSON pointer to retrieve a reference to the respective JSON value.
  19691. No bound checking is performed. The function does not change the JSON
  19692. value; no `null` values are created. In particular, the special value
  19693. `-` yields an exception.
  19694. @param[in] ptr JSON pointer to the desired element
  19695. @return const reference to the element pointed to by @a ptr
  19696. @complexity Constant.
  19697. @throw parse_error.106 if an array index begins with '0'
  19698. @throw parse_error.109 if an array index was not a number
  19699. @throw out_of_range.402 if the array index '-' is used
  19700. @throw out_of_range.404 if the JSON pointer can not be resolved
  19701. @liveexample{The behavior is shown in the example.,operatorjson_pointer_const}
  19702. @since version 2.0.0
  19703. */
  19704. const_reference operator[](const json_pointer& ptr) const
  19705. {
  19706. return ptr.get_unchecked(this);
  19707. }
  19708. /*!
  19709. @brief access specified element via JSON Pointer
  19710. Returns a reference to the element at with specified JSON pointer @a ptr,
  19711. with bounds checking.
  19712. @param[in] ptr JSON pointer to the desired element
  19713. @return reference to the element pointed to by @a ptr
  19714. @throw parse_error.106 if an array index in the passed JSON pointer @a ptr
  19715. begins with '0'. See example below.
  19716. @throw parse_error.109 if an array index in the passed JSON pointer @a ptr
  19717. is not a number. See example below.
  19718. @throw out_of_range.401 if an array index in the passed JSON pointer @a ptr
  19719. is out of range. See example below.
  19720. @throw out_of_range.402 if the array index '-' is used in the passed JSON
  19721. pointer @a ptr. As `at` provides checked access (and no elements are
  19722. implicitly inserted), the index '-' is always invalid. See example below.
  19723. @throw out_of_range.403 if the JSON pointer describes a key of an object
  19724. which cannot be found. See example below.
  19725. @throw out_of_range.404 if the JSON pointer @a ptr can not be resolved.
  19726. See example below.
  19727. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  19728. changes in the JSON value.
  19729. @complexity Constant.
  19730. @since version 2.0.0
  19731. @liveexample{The behavior is shown in the example.,at_json_pointer}
  19732. */
  19733. reference at(const json_pointer& ptr)
  19734. {
  19735. return ptr.get_checked(this);
  19736. }
  19737. /*!
  19738. @brief access specified element via JSON Pointer
  19739. Returns a const reference to the element at with specified JSON pointer @a
  19740. ptr, with bounds checking.
  19741. @param[in] ptr JSON pointer to the desired element
  19742. @return reference to the element pointed to by @a ptr
  19743. @throw parse_error.106 if an array index in the passed JSON pointer @a ptr
  19744. begins with '0'. See example below.
  19745. @throw parse_error.109 if an array index in the passed JSON pointer @a ptr
  19746. is not a number. See example below.
  19747. @throw out_of_range.401 if an array index in the passed JSON pointer @a ptr
  19748. is out of range. See example below.
  19749. @throw out_of_range.402 if the array index '-' is used in the passed JSON
  19750. pointer @a ptr. As `at` provides checked access (and no elements are
  19751. implicitly inserted), the index '-' is always invalid. See example below.
  19752. @throw out_of_range.403 if the JSON pointer describes a key of an object
  19753. which cannot be found. See example below.
  19754. @throw out_of_range.404 if the JSON pointer @a ptr can not be resolved.
  19755. See example below.
  19756. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  19757. changes in the JSON value.
  19758. @complexity Constant.
  19759. @since version 2.0.0
  19760. @liveexample{The behavior is shown in the example.,at_json_pointer_const}
  19761. */
  19762. const_reference at(const json_pointer& ptr) const
  19763. {
  19764. return ptr.get_checked(this);
  19765. }
  19766. /*!
  19767. @brief return flattened JSON value
  19768. The function creates a JSON object whose keys are JSON pointers (see [RFC
  19769. 6901](https://tools.ietf.org/html/rfc6901)) and whose values are all
  19770. primitive. The original JSON value can be restored using the @ref
  19771. unflatten() function.
  19772. @return an object that maps JSON pointers to primitive values
  19773. @note Empty objects and arrays are flattened to `null` and will not be
  19774. reconstructed correctly by the @ref unflatten() function.
  19775. @complexity Linear in the size the JSON value.
  19776. @liveexample{The following code shows how a JSON object is flattened to an
  19777. object whose keys consist of JSON pointers.,flatten}
  19778. @sa @ref unflatten() for the reverse function
  19779. @since version 2.0.0
  19780. */
  19781. basic_json flatten() const
  19782. {
  19783. basic_json result(value_t::object);
  19784. json_pointer::flatten("", *this, result);
  19785. return result;
  19786. }
  19787. /*!
  19788. @brief unflatten a previously flattened JSON value
  19789. The function restores the arbitrary nesting of a JSON value that has been
  19790. flattened before using the @ref flatten() function. The JSON value must
  19791. meet certain constraints:
  19792. 1. The value must be an object.
  19793. 2. The keys must be JSON pointers (see
  19794. [RFC 6901](https://tools.ietf.org/html/rfc6901))
  19795. 3. The mapped values must be primitive JSON types.
  19796. @return the original JSON from a flattened version
  19797. @note Empty objects and arrays are flattened by @ref flatten() to `null`
  19798. values and can not unflattened to their original type. Apart from
  19799. this example, for a JSON value `j`, the following is always true:
  19800. `j == j.flatten().unflatten()`.
  19801. @complexity Linear in the size the JSON value.
  19802. @throw type_error.314 if value is not an object
  19803. @throw type_error.315 if object values are not primitive
  19804. @liveexample{The following code shows how a flattened JSON object is
  19805. unflattened into the original nested JSON object.,unflatten}
  19806. @sa @ref flatten() for the reverse function
  19807. @since version 2.0.0
  19808. */
  19809. basic_json unflatten() const
  19810. {
  19811. return json_pointer::unflatten(*this);
  19812. }
  19813. /// @}
  19814. //////////////////////////
  19815. // JSON Patch functions //
  19816. //////////////////////////
  19817. /// @name JSON Patch functions
  19818. /// @{
  19819. /*!
  19820. @brief applies a JSON patch
  19821. [JSON Patch](http://jsonpatch.com) defines a JSON document structure for
  19822. expressing a sequence of operations to apply to a JSON) document. With
  19823. this function, a JSON Patch is applied to the current JSON value by
  19824. executing all operations from the patch.
  19825. @param[in] json_patch JSON patch document
  19826. @return patched document
  19827. @note The application of a patch is atomic: Either all operations succeed
  19828. and the patched document is returned or an exception is thrown. In
  19829. any case, the original value is not changed: the patch is applied
  19830. to a copy of the value.
  19831. @throw parse_error.104 if the JSON patch does not consist of an array of
  19832. objects
  19833. @throw parse_error.105 if the JSON patch is malformed (e.g., mandatory
  19834. attributes are missing); example: `"operation add must have member path"`
  19835. @throw out_of_range.401 if an array index is out of range.
  19836. @throw out_of_range.403 if a JSON pointer inside the patch could not be
  19837. resolved successfully in the current JSON value; example: `"key baz not
  19838. found"`
  19839. @throw out_of_range.405 if JSON pointer has no parent ("add", "remove",
  19840. "move")
  19841. @throw other_error.501 if "test" operation was unsuccessful
  19842. @complexity Linear in the size of the JSON value and the length of the
  19843. JSON patch. As usually only a fraction of the JSON value is affected by
  19844. the patch, the complexity can usually be neglected.
  19845. @liveexample{The following code shows how a JSON patch is applied to a
  19846. value.,patch}
  19847. @sa @ref diff -- create a JSON patch by comparing two JSON values
  19848. @sa [RFC 6902 (JSON Patch)](https://tools.ietf.org/html/rfc6902)
  19849. @sa [RFC 6901 (JSON Pointer)](https://tools.ietf.org/html/rfc6901)
  19850. @since version 2.0.0
  19851. */
  19852. basic_json patch(const basic_json& json_patch) const
  19853. {
  19854. // make a working copy to apply the patch to
  19855. basic_json result = *this;
  19856. // the valid JSON Patch operations
  19857. enum class patch_operations {add, remove, replace, move, copy, test, invalid};
  19858. const auto get_op = [](const std::string & op)
  19859. {
  19860. if (op == "add")
  19861. {
  19862. return patch_operations::add;
  19863. }
  19864. if (op == "remove")
  19865. {
  19866. return patch_operations::remove;
  19867. }
  19868. if (op == "replace")
  19869. {
  19870. return patch_operations::replace;
  19871. }
  19872. if (op == "move")
  19873. {
  19874. return patch_operations::move;
  19875. }
  19876. if (op == "copy")
  19877. {
  19878. return patch_operations::copy;
  19879. }
  19880. if (op == "test")
  19881. {
  19882. return patch_operations::test;
  19883. }
  19884. return patch_operations::invalid;
  19885. };
  19886. // wrapper for "add" operation; add value at ptr
  19887. const auto operation_add = [&result](json_pointer & ptr, basic_json val)
  19888. {
  19889. // adding to the root of the target document means replacing it
  19890. if (ptr.empty())
  19891. {
  19892. result = val;
  19893. return;
  19894. }
  19895. // make sure the top element of the pointer exists
  19896. json_pointer top_pointer = ptr.top();
  19897. if (top_pointer != ptr)
  19898. {
  19899. result.at(top_pointer);
  19900. }
  19901. // get reference to parent of JSON pointer ptr
  19902. const auto last_path = ptr.back();
  19903. ptr.pop_back();
  19904. basic_json& parent = result[ptr];
  19905. switch (parent.m_type)
  19906. {
  19907. case value_t::null:
  19908. case value_t::object:
  19909. {
  19910. // use operator[] to add value
  19911. parent[last_path] = val;
  19912. break;
  19913. }
  19914. case value_t::array:
  19915. {
  19916. if (last_path == "-")
  19917. {
  19918. // special case: append to back
  19919. parent.push_back(val);
  19920. }
  19921. else
  19922. {
  19923. const auto idx = json_pointer::array_index(last_path);
  19924. if (JSON_HEDLEY_UNLIKELY(static_cast<size_type>(idx) > parent.size()))
  19925. {
  19926. // avoid undefined behavior
  19927. JSON_THROW(out_of_range::create(401, "array index " + std::to_string(idx) + " is out of range"));
  19928. }
  19929. // default case: insert add offset
  19930. parent.insert(parent.begin() + static_cast<difference_type>(idx), val);
  19931. }
  19932. break;
  19933. }
  19934. // if there exists a parent it cannot be primitive
  19935. default: // LCOV_EXCL_LINE
  19936. assert(false); // LCOV_EXCL_LINE
  19937. }
  19938. };
  19939. // wrapper for "remove" operation; remove value at ptr
  19940. const auto operation_remove = [&result](json_pointer & ptr)
  19941. {
  19942. // get reference to parent of JSON pointer ptr
  19943. const auto last_path = ptr.back();
  19944. ptr.pop_back();
  19945. basic_json& parent = result.at(ptr);
  19946. // remove child
  19947. if (parent.is_object())
  19948. {
  19949. // perform range check
  19950. auto it = parent.find(last_path);
  19951. if (JSON_HEDLEY_LIKELY(it != parent.end()))
  19952. {
  19953. parent.erase(it);
  19954. }
  19955. else
  19956. {
  19957. JSON_THROW(out_of_range::create(403, "key '" + last_path + "' not found"));
  19958. }
  19959. }
  19960. else if (parent.is_array())
  19961. {
  19962. // note erase performs range check
  19963. parent.erase(static_cast<size_type>(json_pointer::array_index(last_path)));
  19964. }
  19965. };
  19966. // type check: top level value must be an array
  19967. if (JSON_HEDLEY_UNLIKELY(not json_patch.is_array()))
  19968. {
  19969. JSON_THROW(parse_error::create(104, 0, "JSON patch must be an array of objects"));
  19970. }
  19971. // iterate and apply the operations
  19972. for (const auto& val : json_patch)
  19973. {
  19974. // wrapper to get a value for an operation
  19975. const auto get_value = [&val](const std::string & op,
  19976. const std::string & member,
  19977. bool string_type) -> basic_json &
  19978. {
  19979. // find value
  19980. auto it = val.m_value.object->find(member);
  19981. // context-sensitive error message
  19982. const auto error_msg = (op == "op") ? "operation" : "operation '" + op + "'";
  19983. // check if desired value is present
  19984. if (JSON_HEDLEY_UNLIKELY(it == val.m_value.object->end()))
  19985. {
  19986. JSON_THROW(parse_error::create(105, 0, error_msg + " must have member '" + member + "'"));
  19987. }
  19988. // check if result is of type string
  19989. if (JSON_HEDLEY_UNLIKELY(string_type and not it->second.is_string()))
  19990. {
  19991. JSON_THROW(parse_error::create(105, 0, error_msg + " must have string member '" + member + "'"));
  19992. }
  19993. // no error: return value
  19994. return it->second;
  19995. };
  19996. // type check: every element of the array must be an object
  19997. if (JSON_HEDLEY_UNLIKELY(not val.is_object()))
  19998. {
  19999. JSON_THROW(parse_error::create(104, 0, "JSON patch must be an array of objects"));
  20000. }
  20001. // collect mandatory members
  20002. const std::string op = get_value("op", "op", true);
  20003. const std::string path = get_value(op, "path", true);
  20004. json_pointer ptr(path);
  20005. switch (get_op(op))
  20006. {
  20007. case patch_operations::add:
  20008. {
  20009. operation_add(ptr, get_value("add", "value", false));
  20010. break;
  20011. }
  20012. case patch_operations::remove:
  20013. {
  20014. operation_remove(ptr);
  20015. break;
  20016. }
  20017. case patch_operations::replace:
  20018. {
  20019. // the "path" location must exist - use at()
  20020. result.at(ptr) = get_value("replace", "value", false);
  20021. break;
  20022. }
  20023. case patch_operations::move:
  20024. {
  20025. const std::string from_path = get_value("move", "from", true);
  20026. json_pointer from_ptr(from_path);
  20027. // the "from" location must exist - use at()
  20028. basic_json v = result.at(from_ptr);
  20029. // The move operation is functionally identical to a
  20030. // "remove" operation on the "from" location, followed
  20031. // immediately by an "add" operation at the target
  20032. // location with the value that was just removed.
  20033. operation_remove(from_ptr);
  20034. operation_add(ptr, v);
  20035. break;
  20036. }
  20037. case patch_operations::copy:
  20038. {
  20039. const std::string from_path = get_value("copy", "from", true);
  20040. const json_pointer from_ptr(from_path);
  20041. // the "from" location must exist - use at()
  20042. basic_json v = result.at(from_ptr);
  20043. // The copy is functionally identical to an "add"
  20044. // operation at the target location using the value
  20045. // specified in the "from" member.
  20046. operation_add(ptr, v);
  20047. break;
  20048. }
  20049. case patch_operations::test:
  20050. {
  20051. bool success = false;
  20052. JSON_TRY
  20053. {
  20054. // check if "value" matches the one at "path"
  20055. // the "path" location must exist - use at()
  20056. success = (result.at(ptr) == get_value("test", "value", false));
  20057. }
  20058. JSON_INTERNAL_CATCH (out_of_range&)
  20059. {
  20060. // ignore out of range errors: success remains false
  20061. }
  20062. // throw an exception if test fails
  20063. if (JSON_HEDLEY_UNLIKELY(not success))
  20064. {
  20065. JSON_THROW(other_error::create(501, "unsuccessful: " + val.dump()));
  20066. }
  20067. break;
  20068. }
  20069. default:
  20070. {
  20071. // op must be "add", "remove", "replace", "move", "copy", or
  20072. // "test"
  20073. JSON_THROW(parse_error::create(105, 0, "operation value '" + op + "' is invalid"));
  20074. }
  20075. }
  20076. }
  20077. return result;
  20078. }
  20079. /*!
  20080. @brief creates a diff as a JSON patch
  20081. Creates a [JSON Patch](http://jsonpatch.com) so that value @a source can
  20082. be changed into the value @a target by calling @ref patch function.
  20083. @invariant For two JSON values @a source and @a target, the following code
  20084. yields always `true`:
  20085. @code {.cpp}
  20086. source.patch(diff(source, target)) == target;
  20087. @endcode
  20088. @note Currently, only `remove`, `add`, and `replace` operations are
  20089. generated.
  20090. @param[in] source JSON value to compare from
  20091. @param[in] target JSON value to compare against
  20092. @param[in] path helper value to create JSON pointers
  20093. @return a JSON patch to convert the @a source to @a target
  20094. @complexity Linear in the lengths of @a source and @a target.
  20095. @liveexample{The following code shows how a JSON patch is created as a
  20096. diff for two JSON values.,diff}
  20097. @sa @ref patch -- apply a JSON patch
  20098. @sa @ref merge_patch -- apply a JSON Merge Patch
  20099. @sa [RFC 6902 (JSON Patch)](https://tools.ietf.org/html/rfc6902)
  20100. @since version 2.0.0
  20101. */
  20102. JSON_HEDLEY_WARN_UNUSED_RESULT
  20103. static basic_json diff(const basic_json& source, const basic_json& target,
  20104. const std::string& path = "")
  20105. {
  20106. // the patch
  20107. basic_json result(value_t::array);
  20108. // if the values are the same, return empty patch
  20109. if (source == target)
  20110. {
  20111. return result;
  20112. }
  20113. if (source.type() != target.type())
  20114. {
  20115. // different types: replace value
  20116. result.push_back(
  20117. {
  20118. {"op", "replace"}, {"path", path}, {"value", target}
  20119. });
  20120. return result;
  20121. }
  20122. switch (source.type())
  20123. {
  20124. case value_t::array:
  20125. {
  20126. // first pass: traverse common elements
  20127. std::size_t i = 0;
  20128. while (i < source.size() and i < target.size())
  20129. {
  20130. // recursive call to compare array values at index i
  20131. auto temp_diff = diff(source[i], target[i], path + "/" + std::to_string(i));
  20132. result.insert(result.end(), temp_diff.begin(), temp_diff.end());
  20133. ++i;
  20134. }
  20135. // i now reached the end of at least one array
  20136. // in a second pass, traverse the remaining elements
  20137. // remove my remaining elements
  20138. const auto end_index = static_cast<difference_type>(result.size());
  20139. while (i < source.size())
  20140. {
  20141. // add operations in reverse order to avoid invalid
  20142. // indices
  20143. result.insert(result.begin() + end_index, object(
  20144. {
  20145. {"op", "remove"},
  20146. {"path", path + "/" + std::to_string(i)}
  20147. }));
  20148. ++i;
  20149. }
  20150. // add other remaining elements
  20151. while (i < target.size())
  20152. {
  20153. result.push_back(
  20154. {
  20155. {"op", "add"},
  20156. {"path", path + "/-"},
  20157. {"value", target[i]}
  20158. });
  20159. ++i;
  20160. }
  20161. break;
  20162. }
  20163. case value_t::object:
  20164. {
  20165. // first pass: traverse this object's elements
  20166. for (auto it = source.cbegin(); it != source.cend(); ++it)
  20167. {
  20168. // escape the key name to be used in a JSON patch
  20169. const auto key = json_pointer::escape(it.key());
  20170. if (target.find(it.key()) != target.end())
  20171. {
  20172. // recursive call to compare object values at key it
  20173. auto temp_diff = diff(it.value(), target[it.key()], path + "/" + key);
  20174. result.insert(result.end(), temp_diff.begin(), temp_diff.end());
  20175. }
  20176. else
  20177. {
  20178. // found a key that is not in o -> remove it
  20179. result.push_back(object(
  20180. {
  20181. {"op", "remove"}, {"path", path + "/" + key}
  20182. }));
  20183. }
  20184. }
  20185. // second pass: traverse other object's elements
  20186. for (auto it = target.cbegin(); it != target.cend(); ++it)
  20187. {
  20188. if (source.find(it.key()) == source.end())
  20189. {
  20190. // found a key that is not in this -> add it
  20191. const auto key = json_pointer::escape(it.key());
  20192. result.push_back(
  20193. {
  20194. {"op", "add"}, {"path", path + "/" + key},
  20195. {"value", it.value()}
  20196. });
  20197. }
  20198. }
  20199. break;
  20200. }
  20201. default:
  20202. {
  20203. // both primitive type: replace value
  20204. result.push_back(
  20205. {
  20206. {"op", "replace"}, {"path", path}, {"value", target}
  20207. });
  20208. break;
  20209. }
  20210. }
  20211. return result;
  20212. }
  20213. /// @}
  20214. ////////////////////////////////
  20215. // JSON Merge Patch functions //
  20216. ////////////////////////////////
  20217. /// @name JSON Merge Patch functions
  20218. /// @{
  20219. /*!
  20220. @brief applies a JSON Merge Patch
  20221. The merge patch format is primarily intended for use with the HTTP PATCH
  20222. method as a means of describing a set of modifications to a target
  20223. resource's content. This function applies a merge patch to the current
  20224. JSON value.
  20225. The function implements the following algorithm from Section 2 of
  20226. [RFC 7396 (JSON Merge Patch)](https://tools.ietf.org/html/rfc7396):
  20227. ```
  20228. define MergePatch(Target, Patch):
  20229. if Patch is an Object:
  20230. if Target is not an Object:
  20231. Target = {} // Ignore the contents and set it to an empty Object
  20232. for each Name/Value pair in Patch:
  20233. if Value is null:
  20234. if Name exists in Target:
  20235. remove the Name/Value pair from Target
  20236. else:
  20237. Target[Name] = MergePatch(Target[Name], Value)
  20238. return Target
  20239. else:
  20240. return Patch
  20241. ```
  20242. Thereby, `Target` is the current object; that is, the patch is applied to
  20243. the current value.
  20244. @param[in] apply_patch the patch to apply
  20245. @complexity Linear in the lengths of @a patch.
  20246. @liveexample{The following code shows how a JSON Merge Patch is applied to
  20247. a JSON document.,merge_patch}
  20248. @sa @ref patch -- apply a JSON patch
  20249. @sa [RFC 7396 (JSON Merge Patch)](https://tools.ietf.org/html/rfc7396)
  20250. @since version 3.0.0
  20251. */
  20252. void merge_patch(const basic_json& apply_patch)
  20253. {
  20254. if (apply_patch.is_object())
  20255. {
  20256. if (not is_object())
  20257. {
  20258. *this = object();
  20259. }
  20260. for (auto it = apply_patch.begin(); it != apply_patch.end(); ++it)
  20261. {
  20262. if (it.value().is_null())
  20263. {
  20264. erase(it.key());
  20265. }
  20266. else
  20267. {
  20268. operator[](it.key()).merge_patch(it.value());
  20269. }
  20270. }
  20271. }
  20272. else
  20273. {
  20274. *this = apply_patch;
  20275. }
  20276. }
  20277. /// @}
  20278. };
  20279. /*!
  20280. @brief user-defined to_string function for JSON values
  20281. This function implements a user-defined to_string for JSON objects.
  20282. @param[in] j a JSON object
  20283. @return a std::string object
  20284. */
  20285. NLOHMANN_BASIC_JSON_TPL_DECLARATION
  20286. std::string to_string(const NLOHMANN_BASIC_JSON_TPL& j)
  20287. {
  20288. return j.dump();
  20289. }
  20290. } // namespace nlohmann
  20291. ///////////////////////
  20292. // nonmember support //
  20293. ///////////////////////
  20294. // specialization of std::swap, and std::hash
  20295. namespace std
  20296. {
  20297. /// hash value for JSON objects
  20298. template<>
  20299. struct hash<nlohmann::json>
  20300. {
  20301. /*!
  20302. @brief return a hash value for a JSON object
  20303. @since version 1.0.0
  20304. */
  20305. std::size_t operator()(const nlohmann::json& j) const
  20306. {
  20307. // a naive hashing via the string representation
  20308. const auto& h = hash<nlohmann::json::string_t>();
  20309. return h(j.dump());
  20310. }
  20311. };
  20312. /// specialization for std::less<value_t>
  20313. /// @note: do not remove the space after '<',
  20314. /// see https://github.com/nlohmann/json/pull/679
  20315. template<>
  20316. struct less<::nlohmann::detail::value_t>
  20317. {
  20318. /*!
  20319. @brief compare two value_t enum values
  20320. @since version 3.0.0
  20321. */
  20322. bool operator()(nlohmann::detail::value_t lhs,
  20323. nlohmann::detail::value_t rhs) const noexcept
  20324. {
  20325. return nlohmann::detail::operator<(lhs, rhs);
  20326. }
  20327. };
  20328. /*!
  20329. @brief exchanges the values of two JSON objects
  20330. @since version 1.0.0
  20331. */
  20332. template<>
  20333. inline void swap<nlohmann::json>(nlohmann::json& j1, nlohmann::json& j2) noexcept(
  20334. is_nothrow_move_constructible<nlohmann::json>::value and
  20335. is_nothrow_move_assignable<nlohmann::json>::value
  20336. )
  20337. {
  20338. j1.swap(j2);
  20339. }
  20340. } // namespace std
  20341. /*!
  20342. @brief user-defined string literal for JSON values
  20343. This operator implements a user-defined string literal for JSON objects. It
  20344. can be used by adding `"_json"` to a string literal and returns a JSON object
  20345. if no parse error occurred.
  20346. @param[in] s a string representation of a JSON object
  20347. @param[in] n the length of string @a s
  20348. @return a JSON object
  20349. @since version 1.0.0
  20350. */
  20351. JSON_HEDLEY_NON_NULL(1)
  20352. inline nlohmann::json operator "" _json(const char* s, std::size_t n)
  20353. {
  20354. return nlohmann::json::parse(s, s + n);
  20355. }
  20356. /*!
  20357. @brief user-defined string literal for JSON pointer
  20358. This operator implements a user-defined string literal for JSON Pointers. It
  20359. can be used by adding `"_json_pointer"` to a string literal and returns a JSON pointer
  20360. object if no parse error occurred.
  20361. @param[in] s a string representation of a JSON Pointer
  20362. @param[in] n the length of string @a s
  20363. @return a JSON pointer object
  20364. @since version 2.0.0
  20365. */
  20366. JSON_HEDLEY_NON_NULL(1)
  20367. inline nlohmann::json::json_pointer operator "" _json_pointer(const char* s, std::size_t n)
  20368. {
  20369. return nlohmann::json::json_pointer(std::string(s, n));
  20370. }
  20371. // #include <nlohmann/detail/macro_unscope.hpp>
  20372. // restore GCC/clang diagnostic settings
  20373. #if defined(__clang__) || defined(__GNUC__) || defined(__GNUG__)
  20374. #pragma GCC diagnostic pop
  20375. #endif
  20376. #if defined(__clang__)
  20377. #pragma GCC diagnostic pop
  20378. #endif
  20379. // clean up
  20380. #undef JSON_INTERNAL_CATCH
  20381. #undef JSON_CATCH
  20382. #undef JSON_THROW
  20383. #undef JSON_TRY
  20384. #undef JSON_HAS_CPP_14
  20385. #undef JSON_HAS_CPP_17
  20386. #undef NLOHMANN_BASIC_JSON_TPL_DECLARATION
  20387. #undef NLOHMANN_BASIC_JSON_TPL
  20388. // #include <nlohmann/thirdparty/hedley/hedley_undef.hpp>
  20389. #undef JSON_HEDLEY_ALWAYS_INLINE
  20390. #undef JSON_HEDLEY_ARM_VERSION
  20391. #undef JSON_HEDLEY_ARM_VERSION_CHECK
  20392. #undef JSON_HEDLEY_ARRAY_PARAM
  20393. #undef JSON_HEDLEY_ASSUME
  20394. #undef JSON_HEDLEY_BEGIN_C_DECLS
  20395. #undef JSON_HEDLEY_CLANG_HAS_ATTRIBUTE
  20396. #undef JSON_HEDLEY_CLANG_HAS_BUILTIN
  20397. #undef JSON_HEDLEY_CLANG_HAS_CPP_ATTRIBUTE
  20398. #undef JSON_HEDLEY_CLANG_HAS_DECLSPEC_DECLSPEC_ATTRIBUTE
  20399. #undef JSON_HEDLEY_CLANG_HAS_EXTENSION
  20400. #undef JSON_HEDLEY_CLANG_HAS_FEATURE
  20401. #undef JSON_HEDLEY_CLANG_HAS_WARNING
  20402. #undef JSON_HEDLEY_COMPCERT_VERSION
  20403. #undef JSON_HEDLEY_COMPCERT_VERSION_CHECK
  20404. #undef JSON_HEDLEY_CONCAT
  20405. #undef JSON_HEDLEY_CONCAT3
  20406. #undef JSON_HEDLEY_CONCAT3_EX
  20407. #undef JSON_HEDLEY_CONCAT_EX
  20408. #undef JSON_HEDLEY_CONST
  20409. #undef JSON_HEDLEY_CONSTEXPR
  20410. #undef JSON_HEDLEY_CONST_CAST
  20411. #undef JSON_HEDLEY_CPP_CAST
  20412. #undef JSON_HEDLEY_CRAY_VERSION
  20413. #undef JSON_HEDLEY_CRAY_VERSION_CHECK
  20414. #undef JSON_HEDLEY_C_DECL
  20415. #undef JSON_HEDLEY_DEPRECATED
  20416. #undef JSON_HEDLEY_DEPRECATED_FOR
  20417. #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL
  20418. #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_
  20419. #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED
  20420. #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES
  20421. #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS
  20422. #undef JSON_HEDLEY_DIAGNOSTIC_POP
  20423. #undef JSON_HEDLEY_DIAGNOSTIC_PUSH
  20424. #undef JSON_HEDLEY_DMC_VERSION
  20425. #undef JSON_HEDLEY_DMC_VERSION_CHECK
  20426. #undef JSON_HEDLEY_EMPTY_BASES
  20427. #undef JSON_HEDLEY_EMSCRIPTEN_VERSION
  20428. #undef JSON_HEDLEY_EMSCRIPTEN_VERSION_CHECK
  20429. #undef JSON_HEDLEY_END_C_DECLS
  20430. #undef JSON_HEDLEY_FLAGS
  20431. #undef JSON_HEDLEY_FLAGS_CAST
  20432. #undef JSON_HEDLEY_GCC_HAS_ATTRIBUTE
  20433. #undef JSON_HEDLEY_GCC_HAS_BUILTIN
  20434. #undef JSON_HEDLEY_GCC_HAS_CPP_ATTRIBUTE
  20435. #undef JSON_HEDLEY_GCC_HAS_DECLSPEC_ATTRIBUTE
  20436. #undef JSON_HEDLEY_GCC_HAS_EXTENSION
  20437. #undef JSON_HEDLEY_GCC_HAS_FEATURE
  20438. #undef JSON_HEDLEY_GCC_HAS_WARNING
  20439. #undef JSON_HEDLEY_GCC_NOT_CLANG_VERSION_CHECK
  20440. #undef JSON_HEDLEY_GCC_VERSION
  20441. #undef JSON_HEDLEY_GCC_VERSION_CHECK
  20442. #undef JSON_HEDLEY_GNUC_HAS_ATTRIBUTE
  20443. #undef JSON_HEDLEY_GNUC_HAS_BUILTIN
  20444. #undef JSON_HEDLEY_GNUC_HAS_CPP_ATTRIBUTE
  20445. #undef JSON_HEDLEY_GNUC_HAS_DECLSPEC_ATTRIBUTE
  20446. #undef JSON_HEDLEY_GNUC_HAS_EXTENSION
  20447. #undef JSON_HEDLEY_GNUC_HAS_FEATURE
  20448. #undef JSON_HEDLEY_GNUC_HAS_WARNING
  20449. #undef JSON_HEDLEY_GNUC_VERSION
  20450. #undef JSON_HEDLEY_GNUC_VERSION_CHECK
  20451. #undef JSON_HEDLEY_HAS_ATTRIBUTE
  20452. #undef JSON_HEDLEY_HAS_BUILTIN
  20453. #undef JSON_HEDLEY_HAS_CPP_ATTRIBUTE
  20454. #undef JSON_HEDLEY_HAS_CPP_ATTRIBUTE_NS
  20455. #undef JSON_HEDLEY_HAS_DECLSPEC_ATTRIBUTE
  20456. #undef JSON_HEDLEY_HAS_EXTENSION
  20457. #undef JSON_HEDLEY_HAS_FEATURE
  20458. #undef JSON_HEDLEY_HAS_WARNING
  20459. #undef JSON_HEDLEY_IAR_VERSION
  20460. #undef JSON_HEDLEY_IAR_VERSION_CHECK
  20461. #undef JSON_HEDLEY_IBM_VERSION
  20462. #undef JSON_HEDLEY_IBM_VERSION_CHECK
  20463. #undef JSON_HEDLEY_IMPORT
  20464. #undef JSON_HEDLEY_INLINE
  20465. #undef JSON_HEDLEY_INTEL_VERSION
  20466. #undef JSON_HEDLEY_INTEL_VERSION_CHECK
  20467. #undef JSON_HEDLEY_IS_CONSTANT
  20468. #undef JSON_HEDLEY_IS_CONSTEXPR_
  20469. #undef JSON_HEDLEY_LIKELY
  20470. #undef JSON_HEDLEY_MALLOC
  20471. #undef JSON_HEDLEY_MESSAGE
  20472. #undef JSON_HEDLEY_MSVC_VERSION
  20473. #undef JSON_HEDLEY_MSVC_VERSION_CHECK
  20474. #undef JSON_HEDLEY_NEVER_INLINE
  20475. #undef JSON_HEDLEY_NON_NULL
  20476. #undef JSON_HEDLEY_NO_ESCAPE
  20477. #undef JSON_HEDLEY_NO_RETURN
  20478. #undef JSON_HEDLEY_NO_THROW
  20479. #undef JSON_HEDLEY_NULL
  20480. #undef JSON_HEDLEY_PELLES_VERSION
  20481. #undef JSON_HEDLEY_PELLES_VERSION_CHECK
  20482. #undef JSON_HEDLEY_PGI_VERSION
  20483. #undef JSON_HEDLEY_PGI_VERSION_CHECK
  20484. #undef JSON_HEDLEY_PREDICT
  20485. #undef JSON_HEDLEY_PRINTF_FORMAT
  20486. #undef JSON_HEDLEY_PRIVATE
  20487. #undef JSON_HEDLEY_PUBLIC
  20488. #undef JSON_HEDLEY_PURE
  20489. #undef JSON_HEDLEY_REINTERPRET_CAST
  20490. #undef JSON_HEDLEY_REQUIRE
  20491. #undef JSON_HEDLEY_REQUIRE_CONSTEXPR
  20492. #undef JSON_HEDLEY_REQUIRE_MSG
  20493. #undef JSON_HEDLEY_RESTRICT
  20494. #undef JSON_HEDLEY_RETURNS_NON_NULL
  20495. #undef JSON_HEDLEY_SENTINEL
  20496. #undef JSON_HEDLEY_STATIC_ASSERT
  20497. #undef JSON_HEDLEY_STATIC_CAST
  20498. #undef JSON_HEDLEY_STRINGIFY
  20499. #undef JSON_HEDLEY_STRINGIFY_EX
  20500. #undef JSON_HEDLEY_SUNPRO_VERSION
  20501. #undef JSON_HEDLEY_SUNPRO_VERSION_CHECK
  20502. #undef JSON_HEDLEY_TINYC_VERSION
  20503. #undef JSON_HEDLEY_TINYC_VERSION_CHECK
  20504. #undef JSON_HEDLEY_TI_ARMCL_VERSION
  20505. #undef JSON_HEDLEY_TI_ARMCL_VERSION_CHECK
  20506. #undef JSON_HEDLEY_TI_CL2000_VERSION
  20507. #undef JSON_HEDLEY_TI_CL2000_VERSION_CHECK
  20508. #undef JSON_HEDLEY_TI_CL430_VERSION
  20509. #undef JSON_HEDLEY_TI_CL430_VERSION_CHECK
  20510. #undef JSON_HEDLEY_TI_CL6X_VERSION
  20511. #undef JSON_HEDLEY_TI_CL6X_VERSION_CHECK
  20512. #undef JSON_HEDLEY_TI_CL7X_VERSION
  20513. #undef JSON_HEDLEY_TI_CL7X_VERSION_CHECK
  20514. #undef JSON_HEDLEY_TI_CLPRU_VERSION
  20515. #undef JSON_HEDLEY_TI_CLPRU_VERSION_CHECK
  20516. #undef JSON_HEDLEY_TI_VERSION
  20517. #undef JSON_HEDLEY_TI_VERSION_CHECK
  20518. #undef JSON_HEDLEY_UNAVAILABLE
  20519. #undef JSON_HEDLEY_UNLIKELY
  20520. #undef JSON_HEDLEY_UNPREDICTABLE
  20521. #undef JSON_HEDLEY_UNREACHABLE
  20522. #undef JSON_HEDLEY_UNREACHABLE_RETURN
  20523. #undef JSON_HEDLEY_VERSION
  20524. #undef JSON_HEDLEY_VERSION_DECODE_MAJOR
  20525. #undef JSON_HEDLEY_VERSION_DECODE_MINOR
  20526. #undef JSON_HEDLEY_VERSION_DECODE_REVISION
  20527. #undef JSON_HEDLEY_VERSION_ENCODE
  20528. #undef JSON_HEDLEY_WARNING
  20529. #undef JSON_HEDLEY_WARN_UNUSED_RESULT
  20530. #undef JSON_HEDLEY_WARN_UNUSED_RESULT_MSG
  20531. #undef JSON_HEDLEY_FALL_THROUGH
  20532. #endif // INCLUDE_NLOHMANN_JSON_HPP_